text:
package org.apache.lucene.search;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.ToStringUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

/**
 * A query that applies a filter to the results of another query.
 *
 *
Note: the bits are retrieved from the filter each time this
 * query is used in a search - use a CachingWrapperFilter to avoid
 * regenerating the bits every time.
 * @since   1.4
 * @see     CachingWrapperFilter
 */
public class FilteredQuery extends Query {

  private final Query query;
  private final Filter filter;
  private final FilterStrategy strategy;

  /**
   * Constructs a new query which applies a filter to the results of the original query.
   * {@link Filter#getDocIdSet} will be called every time this query is used in a search.
   * @param query  Query to be filtered, cannot be null.
   * @param filter Filter to apply to query results, cannot be null.
   */
  public FilteredQuery (Query query, Filter filter) {
    this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY);
  }

  /**
   * Expert: Constructs a new query which applies a filter to the results of the original query.
   * {@link Filter#getDocIdSet} will be called every time this query is used in a search.
   * @param query  Query to be filtered, cannot be null.
   * @param filter Filter to apply to query results, cannot be null.
   * @param strategy a filter strategy used to create a filtered scorer.
   *
   * @see FilterStrategy
   */
  public FilteredQuery (Query query, Filter filter, FilterStrategy strategy) {
    if (query == null || filter == null)
      throw new IllegalArgumentException("Query and filter cannot be null.");
    if (strategy == null)
      throw new IllegalArgumentException("FilterStrategy can not be null");
    this.strategy = strategy;
    this.query = query;
    this.filter = filter;
  }

  /**
   * Returns a Weight that applies the filter to the enclosed query's Weight.
   * This is accomplished by overriding the Scorer returned by the Weight.
   */
  @Override
  public Weight createWeight(final IndexSearcher searcher) throws IOException {
    final Weight weight = query.createWeight (searcher);
    return new Weight() {

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

      @Override
      public float getValueForNormalization() throws IOException {
        return weight.getValueForNormalization() * getBoost() * getBoost(); // boost sub-weight
      }

      @Override
      public void normalize (float norm, float topLevelBoost) {
        weight.normalize(norm, topLevelBoost * getBoost()); // incorporate boost
      }

      @Override
      public Explanation explain (AtomicReaderContext ir, int i) throws IOException {
        Explanation inner = weight.explain (ir, i);
        Filter f = FilteredQuery.this.filter;
        DocIdSet docIdSet = f.getDocIdSet(ir, ir.reader().getLiveDocs());
        DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.empty() : docIdSet.iterator();
        if (docIdSetIterator == null) {
          docIdSetIterator = DocIdSetIterator.empty();
        }
        if (docIdSetIterator.advance(i) == i) {
          return inner;
        } else {
          Explanation result = new Explanation
            (0.0f, "failure to match filter: " + f.toString());
          result.addDetail(inner);
          return result;
        }
      }

      // return this query
      @Override
      public Query getQuery() { return FilteredQuery.this; }

      // return a filtering scorer
      @Override
      public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, final Bits acceptDocs) throws IOException {
        assert filter != null;

        final DocIdSet filterDocIdSet = filter.getDocIdSet(context, acceptDocs);
        if (filterDocIdSet == null) {
          // this means the filter does not accept any documents.
          return null;
        }
        return strategy.filteredScorer(context, scoreDocsInOrder, topScorer, weight, filterDocIdSet);

      }
    };
  }

  /**
   * A scorer that consults the filter iff a document was matched by the
   * delegate scorer. This is useful if the filter computation is more expensive
   * than document scoring or if the filter has a linear running time to compute
   * the next matching doc like exact geo distances.
   */
  private static final class QueryFirstScorer extends Scorer {
    private final Scorer scorer;
    private int scorerDoc = -1;
    private Bits filterbits;

    protected QueryFirstScorer(Weight weight, Bits filterBits, Scorer other) {
      super(weight);
      this.scorer = other;
      this.filterbits = filterBits;
    }

    // optimization: we are topScorer and collect directly
    @Override
    public void score(Collector collector) throws IOException {
      // the normalization trick already applies the boost of this query,
      // so we can use the wrapped scorer directly:
      collector.setScorer(scorer);
      for (;;) {
        final int scorerDoc = scorer.nextDoc();
        if (scorerDoc == DocIdSetIterator.NO_MORE_DOCS) {
          break;
        }
        if (filterbits.get(scorerDoc)) {
          collector.collect(scorerDoc);
        }
      }
    }

    @Override
    public int nextDoc() throws IOException {
      int doc;
      for(;;) {
        doc = scorer.nextDoc();
        if (doc == Scorer.NO_MORE_DOCS || filterbits.get(doc)) {
          return scorerDoc = doc;
        }
      }
    }

    @Override
    public int advance(int target) throws IOException {

      int doc = scorer.advance(target);
      if (doc != Scorer.NO_MORE_DOCS && !filterbits.get(doc)) {
        return scorerDoc = nextDoc();
      } else {
        return scorerDoc = doc;
      }

    }

    @Override
    public int docID() {
      return scorerDoc;
    }

    @Override
    public float score() throws IOException {
      return scorer.score();
    }

    @Override
    public int freq() throws IOException { return scorer.freq(); }

    @Override
    public Collection<ChildScorer> getChildren() {
      return Collections.singleton(new ChildScorer(scorer, "FILTERED"));
    }

    @Override
    public long cost() {
      return scorer.cost();
    }
  }

  /**
   * A Scorer that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter
   * take turns trying to advance to each other's next matching document, often
   * jumping past the target document. When both land on the same document, it's
   * collected.
   */
  private static class LeapFrogScorer extends Scorer {
    private final DocIdSetIterator secondary;
    private final DocIdSetIterator primary;
    private final Scorer scorer;
    protected int primaryDoc = -1;
    protected int secondaryDoc = -1;

    protected LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer) {
      super(weight);
      this.primary = primary;
      this.secondary = secondary;
      this.scorer = scorer;
    }

    // optimization: we are topScorer and collect directly using short-circuited algo
    @Override
    public final void score(Collector collector) throws IOException {
      // the normalization trick already applies the boost of this query,
      // so we can use the wrapped scorer directly:
      collector.setScorer(scorer);
      int primDoc = primaryNext();
      int secDoc = secondary.advance(primDoc);
      for (;;) {
        if (primDoc == secDoc) {
          // Check if scorer has exhausted, only before collecting.
          if (primDoc == DocIdSetIterator.NO_MORE_DOCS) {
            break;
          }
          collector.collect(primDoc);
          primDoc = primary.nextDoc();
          secDoc = secondary.advance(primDoc);
        } else if (secDoc > primDoc) {
          primDoc = primary.advance(secDoc);
        } else {
          secDoc = secondary.advance(primDoc);
        }
      }
    }

    private final int advanceToNextCommonDoc() throws IOException {
      for (;;) {
        if (secondaryDoc < primaryDoc) {
          secondaryDoc = secondary.advance(primaryDoc);
        } else if (secondaryDoc == primaryDoc) {
          return primaryDoc;
        } else {
          primaryDoc = primary.advance(secondaryDoc);
        }
      }
    }

    @Override
    public final int nextDoc() throws IOException {
      primaryDoc = primaryNext();
      return advanceToNextCommonDoc();
    }

    protected int primaryNext() throws IOException {
      return primary.nextDoc();
    }

    @Override
    public final int advance(int target) throws IOException {
      if (target > primaryDoc) {
        primaryDoc = primary.advance(target);
      }
      return advanceToNextCommonDoc();
    }

    @Override
    public final int docID() {
      return secondaryDoc;
    }

    @Override
    public final float score() throws IOException {
      return scorer.score();
    }

    @Override
    public final int freq() throws IOException { return scorer.freq(); }

    @Override
    public final Collection<ChildScorer> getChildren() {
      return Collections.singleton(new ChildScorer(scorer, "FILTERED"));
    }

    @Override
    public long cost() {
      return Math.min(primary.cost(), secondary.cost());
    }
  }

  // TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
  private static final class PrimaryAdvancedLeapFrogScorer extends LeapFrogScorer {
    private final int firstFilteredDoc;

    protected PrimaryAdvancedLeapFrogScorer(Weight weight, int firstFilteredDoc, DocIdSetIterator filterIter, Scorer other) {
      super(weight, filterIter, other, other);
      this.firstFilteredDoc = firstFilteredDoc;
      this.primaryDoc = firstFilteredDoc; // initialize to prevent and advance call to move it further
    }

    @Override
    protected int primaryNext() throws IOException {
      if (secondaryDoc != -1) {
        return super.primaryNext();
      } else {
        return firstFilteredDoc;
      }
    }
  }

  /** Rewrites the query. If the wrapped is an instance of
   * {@link MatchAllDocsQuery} it returns a {@link ConstantScoreQuery}. Otherwise
   * it returns a new {@code FilteredQuery} wrapping the rewritten query. */
  @Override
  public Query rewrite(IndexReader reader) throws IOException {
    final Query queryRewritten = query.rewrite(reader);

    if (queryRewritten instanceof MatchAllDocsQuery) {
      // Special case: If the query is a MatchAllDocsQuery, we only
      // return a CSQ(filter).
      final Query rewritten = new ConstantScoreQuery(filter);
      // Combine boost of MatchAllDocsQuery and the wrapped rewritten query:
      rewritten.setBoost(this.getBoost() * queryRewritten.getBoost());
      return rewritten;
    }

    if (queryRewritten != query) {
      // rewrite to a new FilteredQuery wrapping the rewritten query
      final Query rewritten = new FilteredQuery(queryRewritten, filter, strategy);
      rewritten.setBoost(this.getBoost());
      return rewritten;
    } else {
      // nothing to rewrite, we are done!
      return this;
    }
  }

  /** Returns this FilteredQuery's (unfiltered) Query */
  public final Query getQuery() {
    return query;
  }

  /** Returns this FilteredQuery's filter */
  public final Filter getFilter() {
    return filter;
  }

  /** Returns this FilteredQuery's {@link FilterStrategy} */
  public FilterStrategy getFilterStrategy() {
    return this.strategy;
  }

  // inherit javadoc
  @Override
  public void extractTerms(Set<Term> terms) {
    getQuery().extractTerms(terms);
  }

  /** Prints a user-readable version of this query. */
  @Override
  public String toString (String s) {
    StringBuilder buffer = new StringBuilder();
    buffer.append("filtered(");
    buffer.append(query.toString(s));
    buffer.append(")->");
    buffer.append(filter);
    buffer.append(ToStringUtils.boost(getBoost()));
    return buffer.toString();
  }

  /** Returns true iff o is equal to this. */
  @Override
  public boolean equals(Object o) {
    if (o == this)
      return true;
    if (!super.equals(o))
      return false;
    assert o instanceof FilteredQuery;
    final FilteredQuery fq = (FilteredQuery) o;
    return fq.query.equals(this.query) && fq.filter.equals(this.filter) && fq.strategy.equals(this.strategy);
  }

  /** Returns a hash code value for this object. */
  @Override
  public int hashCode() {
    int hash = super.hashCode();
    hash = hash * 31 + strategy.hashCode();
    hash = hash * 31 + query.hashCode();
    hash = hash * 31 + filter.hashCode();
    return hash;
  }

  /**
   * A {@link FilterStrategy} that conditionally uses a random access filter if
   * the given {@link DocIdSet} supports random access (returns a non-null value
   * from {@link DocIdSet#bits()}) and
   * {@link RandomAccessFilterStrategy#useRandomAccess(Bits, int)} returns
   * true. Otherwise this strategy falls back to a "zig-zag join" (
   * {@link FilteredQuery#LEAP_FROG_FILTER_FIRST_STRATEGY}) strategy.
   *
   *

   * Note: this strategy is the default strategy in {@link FilteredQuery}
   *

   */
  public static final FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy();

  /**
   * A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
   * The scorer and the filter
   * take turns trying to advance to each other's next matching document, often
   * jumping past the target document. When both land on the same document, it's
   * collected.
   *

   * Note: This strategy uses the filter to lead the iteration.
   *

   */
  public static final FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false);

  /**
   * A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
   * The scorer and the filter
   * take turns trying to advance to each other's next matching document, often
   * jumping past the target document. When both land on the same document, it's
   * collected.
   *

   * Note: This strategy uses the query to lead the iteration.
   *

   */
  public static final FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true);

  /**
   * A filter strategy that advances the Query or rather its {@link Scorer} first and consults the
   * filter {@link DocIdSet} for each matched document.
   *

   * Note: this strategy requires a {@link DocIdSet#bits()} to return a non-null value. Otherwise
   * this strategy falls back to {@link FilteredQuery#LEAP_FROG_QUERY_FIRST_STRATEGY}
   *

   *

   * Use this strategy if the filter computation is more expensive than document
   * scoring or if the filter has a linear running time to compute the next
   * matching doc like exact geo distances.
   *

   */
  public static final FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy();

  /** Abstract class that defines how the filter ({@link DocIdSet}) applied during document collection. */
  public static abstract class FilterStrategy {

    /**
     * Returns a filtered {@link Scorer} based on this strategy.
     *
     * @param context
     *          the {@link AtomicReaderContext} for which to return the {@link Scorer}.
     * @param scoreDocsInOrder
     *          specifies whether in-order scoring of documents is required. Note
     *          that if set to false (i.e., out-of-order scoring is required),
     *          this method can return whatever scoring mode it supports, as every
     *          in-order scorer is also an out-of-order one. However, an
     *          out-of-order scorer may not support {@link Scorer#nextDoc()}
     *          and/or {@link Scorer#advance(int)}, therefore it is recommended to
     *          request an in-order scorer if use of these methods is required.
     * @param topScorer
     *          if true, {@link Scorer#score(Collector)} will be called; if false,
     *          {@link Scorer#nextDoc()} and/or {@link Scorer#advance(int)} will
     *          be called.
     * @param weight the {@link FilteredQuery} {@link Weight} to create the filtered scorer.
     * @param docIdSet the filter {@link DocIdSet} to apply
     * @return a filtered scorer
     *
     * @throws IOException if an {@link IOException} occurs
     */
    public abstract Scorer filteredScorer(AtomicReaderContext context,
        boolean scoreDocsInOrder, boolean topScorer, Weight weight,
        DocIdSet docIdSet) throws IOException;
  }

  /**
   * A {@link FilterStrategy} that conditionally uses a random access filter if
   * the given {@link DocIdSet} supports random access (returns a non-null value
   * from {@link DocIdSet#bits()}) and
   * {@link RandomAccessFilterStrategy#useRandomAccess(Bits, int)} returns
   * true. Otherwise this strategy falls back to a "zig-zag join" (
   * {@link FilteredQuery#LEAP_FROG_FILTER_FIRST_STRATEGY}) strategy .
   */
  public static class RandomAccessFilterStrategy extends FilterStrategy {

    @Override
    public Scorer filteredScorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Weight weight, DocIdSet docIdSet) throws IOException {
      final DocIdSetIterator filterIter = docIdSet.iterator();
      if (filterIter == null) {
        // this means the filter does not accept any documents.
        return null;
      }

      final int firstFilterDoc = filterIter.nextDoc();
      if (firstFilterDoc == DocIdSetIterator.NO_MORE_DOCS) {
        return null;
      }

      final Bits filterAcceptDocs = docIdSet.bits();
      // force if RA is requested
      final boolean useRandomAccess = (filterAcceptDocs != null && (useRandomAccess(filterAcceptDocs, firstFilterDoc)));
      if (useRandomAccess) {
        // if we are using random access, we return the inner scorer, just with other acceptDocs
        return weight.scorer(context, scoreDocsInOrder, topScorer, filterAcceptDocs);
      } else {
        assert firstFilterDoc > -1;
        // we are gonna advance() this scorer, so we set inorder=true/toplevel=false
        // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
        final Scorer scorer = weight.scorer(context, true, false, null);
        // TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
        return (scorer == null) ? null : new PrimaryAdvancedLeapFrogScorer(weight, firstFilterDoc, filterIter, scorer);
      }
    }

    /**
     * Expert: decides if a filter should be executed as "random-access" or not.
     * random-access means the filter "filters" in a similar way as deleted docs are filtered
     * in Lucene. This is faster when the filter accepts many documents.
     * However, when the filter is very sparse, it can be faster to execute the query+filter
     * as a conjunction in some cases.
     *
     * The default implementation returns true if the first document accepted by the
     * filter is < 100.
     *
     * @lucene.internal
     */
    protected boolean useRandomAccess(Bits bits, int firstFilterDoc) {
      //TODO once we have a cost API on filters and scorers we should rethink this heuristic
      return firstFilterDoc < 100;
    }
  }

  private static final class LeapFrogFilterStrategy extends FilterStrategy {

    private final boolean scorerFirst;

    private LeapFrogFilterStrategy(boolean scorerFirst) {
      this.scorerFirst = scorerFirst;
    }
    @Override
    public Scorer filteredScorer(AtomicReaderContext context,
        boolean scoreDocsInOrder, boolean topScorer, Weight weight,
        DocIdSet docIdSet) throws IOException {
      final DocIdSetIterator filterIter = docIdSet.iterator();
      if (filterIter == null) {
        // this means the filter does not accept any documents.
        return null;
      }
      // we are gonna advance() this scorer, so we set inorder=true/toplevel=false
      // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
      final Scorer scorer = weight.scorer(context, true, false, null);
      if (scorerFirst) {
        return (scorer == null) ? null : new LeapFrogScorer(weight, scorer, filterIter, scorer);
      } else {
        return (scorer == null) ? null : new LeapFrogScorer(weight, filterIter, scorer, scorer);
      }
    }

  }

  /**
   * A filter strategy that advances the {@link Scorer} first and consults the
   * {@link DocIdSet} for each matched document.
   *

   * Note: this strategy requires a {@link DocIdSet#bits()} to return a non-null value. Otherwise
   * this strategy falls back to {@link FilteredQuery#LEAP_FROG_QUERY_FIRST_STRATEGY}
   *

   *

   * Use this strategy if the filter computation is more expensive than document
   * scoring or if the filter has a linear running time to compute the next
   * matching doc like exact geo distances.
   *

   */
  private static final class QueryFirstFilterStrategy extends FilterStrategy {
    @Override
    public Scorer filteredScorer(final AtomicReaderContext context,
        boolean scoreDocsInOrder, boolean topScorer, Weight weight,
        DocIdSet docIdSet) throws IOException {
      Bits filterAcceptDocs = docIdSet.bits();
      if (filterAcceptDocs == null) {
        return LEAP_FROG_QUERY_FIRST_STRATEGY.filteredScorer(context, scoreDocsInOrder, topScorer, weight, docIdSet);
      }
      final Scorer scorer = weight.scorer(context, true, false, null);
      return scorer == null ? null : new QueryFirstScorer(weight,
          filterAcceptDocs, scorer);
    }
  }

}


text:
package org.openxava.test.tests;

import org.openxava.tests.*;

/**
 * @author Javier Paniza
 */

public class CustomerNewOnInitTest extends ModuleTestBase {

	public CustomerNewOnInitTest(String testName) {
		super(testName, "CustomerNewOnInit");
	}

	public void testNewOnInit() throws Exception {
		assertNoErrors();
		assertAction("Mode.list");
		assertNoAction("Mode.detailAndFirst");
	}

	public void testGetValueFromAGroupInSectionAfterNew() throws Exception {
		setValue("name", "Juanillo");
		execute("CustomerNewOnInit.getName");
		assertMessage("The name is Juanillo");
	}

}

redpajama_set_name: RedPajamaGithub


text:
The Listing Web Component provides a web component that allows code listings to
be easily embedded into your website.
I started development on this after discovering that I was
[unable to embed Gists in XHTML pages](https://www.mattunderscore.com/article/42).

The component provides a custom element that loads a resource, applies
[highlight.js](https://highlightjs.org/) and displays it as a code listing.
Currently it is hard coded to use the 'tomorrow' highlight.js theme.

To build the web component run `npm run build`.

The `target/dist/listing-script.js` contains a script that uses
[custom elements](http://w3c.github.io/webcomponents/spec/custom/) and the
[shadow DOM](http://w3c.github.io/webcomponents/spec/shadow/).
A script for highlight.js needs to be explicitly included.
The CSS has been inlined into the script and does not need to be added.

The `target/dist/listing-import.html` contains an
[HTML import](http://w3c.github.io/webcomponents/spec/imports/) that uses
[custom elements](http://w3c.github.io/webcomponents/spec/custom/), the
[shadow DOM](http://w3c.github.io/webcomponents/spec/shadow/) and
[HTML templates](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element).

The `examples` directory provides two usage examples.
One example demonstrates `listing-script.js` and the other `listing-import.html`.
Otherwise their content is the same.
Two code listings one hosted on GistHub and the other with code inlined into the
custom element.

Automated tests are run using `web-component-tester` with the command
`npm run build`.


text:
'use strict';

promise_test(async testCase => {
  await cookieStore.set('cookie-name', 'cookie-value');
  testCase.add_cleanup(async () => {
    await cookieStore.delete('cookie-name');
  });

  const eventPromise = new Promise((resolve) => {
    cookieStore.onchange = resolve;
  });
  await cookieStore.delete('cookie-name');
  const event = await eventPromise;
  assert_true(event instanceof CookieChangeEvent);
  assert_equals(event.type, 'change');
  assert_equals(event.deleted.length, 1);
  assert_equals(event.deleted[0].name, 'cookie-name');
  assert_equals(
      event.deleted[0].value, undefined,
      'Cookie change events for deletions should not have cookie values');
  assert_equals(event.changed.length, 0);
}, 'cookieStore fires change event for cookie deleted by cookieStore.delete()');


text:
import params
import unittest, time, datetime, os, sys
import sst.actions
#from robot.api import logger

# XXX FIXME XXX
__TESTCASE_ID__ = None

class ActionsLibBaseTest(unittest.TestCase):
	@classmethod
	def setUpClass(cls):
		sst.actions.start()

	@classmethod
	def tearDownClass(cls):
		sst.actions.stop()

	def setUp(self):
		global __TESTCASE_ID__
		__TESTCASE_ID__ = self.id()

	def tearDown(self):
		pass

class FailedSeleniumAssertion(object):
	def __init__(self, error, screenshot, pagedump):
		self.error = error
		self.screenshot = screenshot
		self.pagedump = pagedump

	def __call__(self, f):
		def wrappedfunction(*args, **kwargs):
			try:
				return f(*args, **kwargs)
			except self.error:
				sst.actions._print("Caught an AssertionError: <<< " + str(sys.exc_info()[1]) + " >>>")
				if self.screenshot is not None: self.screenshot()
				if self.pagedump is not None: self.pagedump()
				raise
		return wrappedfunction

sst.config.results_directory = os.getenv('SCREENSHOT_DIR','screenshots')
sst.actions._make_results_dir()
params.SCREENSHOT_DIR = sst.config.results_directory

def take_screenshot(name=None):
	global __TESTCASE_ID__

	if name==None:
		filename = '%s.png' % __TESTCASE_ID__
	else:
		filename = '%s.png' % (str(name)+'-'+datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
	sst.actions.take_screenshot(filename)
	with open(os.path.join(params.SCREENSHOT_DIR,filename),'rb') as f:
		import base64
		#logger.info('<img src="data:image/png;base64,%s" width="1200px"/>' % (base64.b64encode(f.read())), True, False)

def dump_pagesource(name=None):
	global __TESTCASE_ID__

	sst.actions._print('Capturing page source')
	if name==None:
		filename = '%s.html' % __TESTCASE_ID__
	else:
		filename = '%s.html' % name

	path = os.path.join(sst.config.results_directory, filename)
	import codecs
	with codecs.open(path, 'w', encoding='utf-8') as f:
		f.write(sst.actions.get_page_source())

def start():
    sst.actions.start()

def stop():
    sst.actions.stop()

def go_to(url):
    sst.actions.go_to(url)

def go_back():
    sst.actions.go_back()

def set_base_url(url):
	sst.actions.set_base_url(url)

def get_base_url(url):
	return sst.actions.get_base_url(url)

def get_page_source():
    return sst.actions.get_page_source()

def sleep(secs):
    sst.actions.sleep(secs)

def refresh():
    sst.actions.refresh()

def maximize_window():
	get_selenium_driver_object().maximize_window()

def close_window():
	sst.actions.close_window()

def clear_cookies():
	sst.actions.clear_cookies()

def get_cookies():
	return sst.actions.get_cookies()

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_element(tag=None, css_class=None, id=None, text=None, text_regex=None, **kwargs):
	return sst.actions.get_element(tag=tag, css_class=css_class, id=id, text=text, text_regex=text_regex, **kwargs)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_elements(tag=None, css_class=None, id=None, text=None, text_regex=None, **kwargs):
	return sst.actions.get_elements(tag=tag, css_class=css_class, id=id, text=text, text_regex=text_regex, **kwargs)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_elements_by_css(selector):
	return sst.actions.get_elements_by_css(selector)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_element_by_css(selector):
	return sst.actions.get_element_by_css(selector)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_element_by_xpath(selector):
	return sst.actions.get_element_by_xpath(selector)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_elements_by_xpath(selector):
	return sst.actions.get_elements_by_xpath(selector)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def exists_element(tag=None, css_class=None, id=None, text=None, text_regex=None, **kwargs):
	return sst.actions.exists_element(tag=tag, css_class=css_class, id=id, text=text, text_regex=text_regex, **kwargs)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def click_link(id_or_elem):
	sst.actions.click_link(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def click_element(id_or_elem):
	sst.actions.click_element(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def click_button(id_or_elem):
	sst.actions.click_button(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def write_textfield(id_or_elem, text):
	sst.actions.write_textfield(id_or_elem, text)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def toggle_checkbox(id_or_elem):
	sst.actions.toggle_checkbox(id_or_elem)

def set_wait_timeout(timeout):
	sst.actions.set_wait_timeout(timeout)

def wait_for(condition, *args, **kwargs):
	sst.actions.wait_for(condition, *args, **kwargs)

def wait_for_and_refresh(condition):
	sst.actions.wait_for_and_refresh(condition)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def set_dropdown_value(id_or_elem, text=None, value=None):
	sst.actions.set_dropdown_value(id_or_elem, text, value)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def set_radio_value(id_or_elem):
	sst.actions.set_radio_value(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def get_text(elem):
	sst.actions._get_text(elem)

def get_selenium_driver_object():
	return sst.actions.browser

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_fail(msg):
    assert False, msg

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_dropdown(id_or_elem):
	sst.actions.assert_dropdown(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_dropdown_value(id_or_elem, text_in):
	sst.actions.assert_dropdown_value(id_or_elem, text_in)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_radio(id_or_elem):
	sst.actions.assert_radio(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_radio_value(id_or_elem, value):
	sst.actions.assert_radio_value(id_or_elem, value)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_element(tag=None, css_class=None, id=None, text=None, text_regex=None, **kwargs):
	sst.actions.assert_element(tag=tag, css_class=css_class, id=id, text=text, text_regex=text_regex, **kwargs)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_button(id_or_elem):
	sst.actions.assert_button(id_or_elem)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_textfield(id_or_elem):
	assert sst.actions.assert_textfield(id_or_elem) is not None

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_checkbox(id_or_elem):
	assert sst.actions.assert_checkbox(id_or_elem) is not None

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_link(id_or_elem):
	assert sst.actions.assert_link(id_or_elem) is not None

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_element_exist(id):
	assert sst.actions.exists_element(id=id), "Element %s doesn't exist" % id

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_element(tag=None, css_class=None, id=None, text=None, text_regex=None, **kwargs):
	assert sst.actions.assert_element(tag=tag, css_class=css_class, id=id, text=text, text_regex=text_regex, **kwargs) is not None

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_attribute(id_or_elem, attribute, value, regex=True):
	sst.actions.assert_attribute(id_or_elem, attribute, value, regex)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_css_property(id_or_elem, property, value, regex=True):
	sst.actions.assert_css_property(id_or_elem, property, value, regex)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_displayed(id_or_elem):
	assert sst.actions.assert_displayed(id_or_elem) is not None

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_page_contains(text):
	_assert_in_page(text)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_page_does_not_contain(text):
	_assert_not_in_page(text)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_title(title):
	sst.actions.assert_title(title)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_title_contains(text, regex=True):
	sst.actions.assert_title_contains(text, regex)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_url(url):
	sst.actions.assert_url(url)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_url_contains(text, regex=True):
	sst.actions.assert_url_contains(text, regex)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_table_has_rows(id_or_elem, num_rows):
	sst.actions.assert_table_has_rows(id_or_elem, num_rows)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_table_row_contains_text(id_or_elem, row, contents, regex=True):
	sst.actions.assert_table_row_contains_text(id_or_elem, row, contents, regex)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_text(id_or_elem, text):
	sst.actions.assert_text(id_or_elem, text)

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_text_contains(id_or_elem, text, regex=True):
	sst.actions.assert_text_contains(id_or_elem, text, regex)

def _assert_in_page(item, msg = "assertion failed: expected %(item)r in %(sequence)r"):
    """Assert that the item is in the sequence."""
    sequence = sst.actions.get_page_source()
    assert item in sequence, msg % {'item':item, 'sequence':sequence}

def _assert_not_in_page(item, msg="assertion failed: expected %(item)r not in %(sequence)r"):
    """Assert that the item is not in the sequence."""
    sequence = sst.actions.get_page_source()
    assert item not in sequence, msg % {'item':item, 'sequence':sequence}

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_equal(first, second):
    """Assert two objects are equal."""
    sst.actions.assert_equal(first, second)

#assert_equals = assert_equal

@FailedSeleniumAssertion(error=AssertionError, screenshot=take_screenshot, pagedump=dump_pagesource)
def assert_not_equal(first, second):
    """Assert two objects are not equal."""
    sst.actions.assert_not_equal(first, second)

#assert_not_equals = assert_not_equal

'''
def set_bpx():
	import pdb; pdb.set_trace()
'''


text:
import logging

from mobly import asserts
from mobly import base_test
from mobly import test_runner
from tests.lib import mock_controller

class IntegrationTest(base_test.BaseTestClass):

  def setup_class(self):
    self.register_controller(mock_controller)

  def test_hello_world(self):
    asserts.assert_equal(self.user_params['icecream'], 42)
    asserts.assert_equal(self.user_params['extra_param'], 'haha')
    logging.info('This is a bare minimal test to make sure the basic MOBLY'
                 ' test flow works.')
    asserts.explicit_pass(
        'Hello World',
        # Use a unicode string here to make sure the full log pipeline
        # works with unicode.
        extras=u'\u2022')

if __name__ == '__main__':
  test_runner.main()


text:
<?php
class SessionState{
    protected $sessionStructure;
    public function SessionState($session = null){

        if ($session == null){
            $this->sessionStructure = new Textsecure_SessionStructure();
        }
        else if($session instanceof SessionState){
            $this->sessionStructure = new Textsecure_SessionStructure();
            $this->sessionStructure->parseFromString($session->getStructure()->serializeToString());
        }
        else{
            $this->sessionStructure = $session;
        }
    }
    public function getStructure(){
        return $this->sessionStructure;
    }
    public function getAliceBaseKey(){
        return $this->sessionStructure->getAliceBaseKey();
    }
    public function setAliceBaseKey($aliceBaseKey){
        $this->sessionStructure->setAliceBaseKey($aliceBaseKey);
    }

    public function setSessionVersion($version){
        $this->sessionStructure->setSessionVersion($version);
    }

    public function getSessionVersion(){
        $sessionVersion = $this->sessionStructure->getSessionVersion();
        return $sessionVersion == 0?2:$sessionVersion;
    }
    public function setRemoteIdentityKey($identityKey){
        $this->sessionStructure->setRemoteIdentityPublic($identityKey->serialize());
    }

    public function setLocalIdentityKey($identityKey){
        $this->sessionStructure->setLocalIdentityPublic($identityKey->serialize());
    }

    public function getRemoteIdentityKey(){
        if($this->sessionStructure->getRemoteIdentityPublic() == null)
            return null;
        return new IdentityKey($this->sessionStructure->getRemoteIdentityPublic(), 0);
    }
    public function getLocalIdentityKey(){
        return new IdentityKey($this->sessionStructure->getLocalIdentityPublic(), 0);
    }
    public function getPreviousCounter(){
        return $this->sessionStructure->getPreviousCounter();
    }
    public function setPreviousCounter($previousCounter){
        $this->sessionStructure->setPreviousCounter($previousCounter);
    }

    public function getRootKey(){
        return new RootKey(HKDF::createFor($this->getSessionVersion()), $this->sessionStructure->getRootKey());
    }
    public function setRootKey($rootKey){
        $this->sessionStructure->setRootKey($rootKey->getKeyBytes());
    }

    public function getSenderRatchetKey(){
        return Curve::decodePoint($this->sessionStructure->getSenderChain()->getSenderRatchetKey(), 0);
    }
    public function getSenderRatchetKeyPair(){
        $publicKey = $this->getSenderRatchetKey();
        $privateKey = Curve::decodePrivatePoint($this->sessionStructure->getSenderChain()->getSenderRatchetKeyPrivate());

        return new ECKeyPair($publicKey, $privateKey);
    }
    public function hasReceiverChain($ECPublickKey_senderEphemeral){
        return $this->getReceiverChain($ECPublickKey_senderEphemeral) != null;
    }
    public function hasSenderChain(){
        return $this->sessionStructure->getSenderChain() != null;
    }
    public function getReceiverChain($ECPublickKey_senderEphemeral){
        $receiverChains = $this->sessionStructure->getReceiverChains();
        $index = 0;
        foreach($receiverChains as $receiverChain){
            $chainSenderRatchetKey = Curve::decodePoint($receiverChain->getSenderRatchetKey(), 0);
            if ($chainSenderRatchetKey == $ECPublickKey_senderEphemeral){
                return [$receiverChain, $index];
            }
            $index += 1;
        }
    }
    public function getReceiverChainKey($ECPublicKey_senderEphemeral){
        $receiverChainAndIndex = $this->getReceiverChain($ECPublicKey_senderEphemeral);
        $receiverChain = $receiverChainAndIndex[0];
        if ($receiverChain == null)
            return null;

        return new ChainKey(HKDF::createFor($this->getSessionVersion()),
                        $receiverChain->getChainKey()->getKey(),
                        $receiverChain->getChainKey()->getIndex());
    }
    public function addReceiverChain($ECPublickKey_senderRatchetKey, $chainKey){
        $senderRatchetKey = $ECPublickKey_senderRatchetKey;

        $chain = new Textsecure_SessionStructure_Chain();
        $chain->setSenderRatchetKey($senderRatchetKey->serialize());
        $chain->setChainKey(new Textsecure_SessionStructure_Chain_ChainKey());
        $chain->getChainKey()->setKey($chainKey->getKey());
        $chain->getChainKey()->setIndex($chainKey->getIndex());

        $this->sessionStructure->appendReceiverChains($chain);

        if (count($this->sessionStructure->getReceiverChains()) > 5){
            $chains = $this->sessionStructure->getReceiverChains();
            $chains = array_slice($chains, 1);
            $this->sessionStructure->clearReceiverChains();
            foreach($chains as $chain)
                $this->sessionStructure->appendReceiverChains($chain);
            //$this->sessionStructure->setReceiverChains($chains);
        }

    }
    public function setSenderChain($ECKeyPair_senderRatchetKeyPair, $chainKey){
        $senderRatchetKeyPair = $ECKeyPair_senderRatchetKeyPair;

        $senderChain = new Textsecure_SessionStructure_Chain();
        $this->sessionStructure->setSenderChain($senderChain);
        $this->sessionStructure->getSenderChain()->setSenderRatchetKey($senderRatchetKeyPair->getPublicKey()->serialize());
        $this->sessionStructure->getSenderChain()->setSenderRatchetKeyPrivate($senderRatchetKeyPair->getPrivateKey()->serialize());
        $this->sessionStructure->getSenderChain()->setChainKey(new Textsecure_SessionStructure_Chain_ChainKey());
        $this->sessionStructure->getSenderChain()->getChainKey()->setKey($chainKey->getKey());
        $this->sessionStructure->getSenderChain()->getChainKey()->setIndex($chainKey->getIndex());
    }
    public function getSenderChainKey(){
        $chainKeyStructure = $this->sessionStructure->getSenderChain()->getChainKey();
        return new ChainKey(HKDF::createFor($this->getSessionVersion()),
                        $chainKeyStructure->getKey(), $chainKeyStructure->getIndex());
    }
    public function setSenderChainKey($ChainKey_nextChainKey){
        $nextChainKey = $ChainKey_nextChainKey;

        $this->sessionStructure->getSenderChain()->getChainKey()->setKey($nextChainKey->getKey());
        $this->sessionStructure->getSenderChain()->getChainKey()->setIndex($nextChainKey->getIndex());

    }
    public function hasMessageKeys($ECPublickKey_senderEphemeral, $counter){
        $senderEphemeral = $ECPublickKey_senderEphemeral;
        $chainAndIndex = $this->getReceiverChain($senderEphemeral);
        $chain = $chainAndIndex[0];
        if ($chain == null)
            return false;

        $messageKeyList = $chain->getMessageKeys();
        foreach($messageKeyList as $messageKey){
            if($messageKey->getIndex() == $counter)
                return true;
        }

        return false;
    }
    public function removeMessageKeys($ECPublicKey_senderEphemeral, $counter){
        $senderEphemeral = $ECPublicKey_senderEphemeral;
        $chainAndIndex = $this->getReceiverChain($senderEphemeral);
        $chain = $chainAndIndex[0];
        if($chain  == null)
            return null;

        $messageKeyList = $chain->getMessageKeys();
        $result = null;

        for ($i =0;$i<count($messageKeyList);$i++)
        {
            $messageKey = $messageKeyList[$i];
            if ($messageKey->getIndex() == $counter){
                $result = new MessageKeys($messageKey->getCipherKey(), $messageKey->getMacKey(), $messageKey->getIv(), $messageKey->getIndex());
                unset($messageKeyList[$i]);
                //del messageKeyList[i] <- 1. is a copy of the original array so go to 2
                break;
            }
        }
        $chain->clearMessageKeys();
        foreach($messageKeyList as $msgKey){
          $chain->appendMessageKeys($msgKey);
        }
        $this->sessionStructure->getReceiverChains()[$chainAndIndex[1]]->parseFromString($chain->serializeToString());

        return $result;
    }
    public function setMessageKeys($ECPublicKey_senderEphemeral, $messageKeys){
        $senderEphemeral = $ECPublicKey_senderEphemeral;
        $chainAndIndex = $this->getReceiverChain($senderEphemeral);
        $chain = $chainAndIndex[0];
        $messageKeyStructure = new Textsecure_SessionStructure_Chain_MessageKey();//$chain->messageKeys.add() #storageprotos.SessionStructure.Chain.MessageKey()
        $messageKeyStructure->setCipherKey($messageKeys->getCipherKey());
        $messageKeyStructure->setMacKey($messageKeys->getMacKey());
        $messageKeyStructure->setIndex($messageKeys->getCounter());
        $messageKeyStructure->setIv($messageKeys->getIv());
        $chain->appendMessageKeys($messageKeyStructure); //$chain->messageKeys.add()

        #chain.messageKeys.append(messageKeyStructure)

        $this->sessionStructure->getReceiverChains()[$chainAndIndex[1]]->parseFromString($chain->serializeToString());
    }
    public function setReceiverChainKey($ECPublicKey_senderEphemeral, $chainKey){
        $senderEphemeral = $ECPublicKey_senderEphemeral;
        $chainAndIndex = $this->getReceiverChain($senderEphemeral);
        $chain = $chainAndIndex[0];
        $chain->getChainKey()->setKey($chainKey->getKey());
        $chain->getChainKey()->setIndex($chainKey->getIndex());

        #$this->sessionStructure.receiverChains[chainAndIndex[1]].ClearField()
        $this->sessionStructure->getReceiverChains()[$chainAndIndex[1]]->parseFromString($chain->serializeToString());
    }

    public function setPendingKeyExchange($sequence, $ourBaseKey, $ourRatchetKey, $ourIdentityKey){
        /*
        :type sequence: int
        :type ourBaseKey: ECKeyPair
        :type ourRatchetKey: ECKeyPair
        :type  ourIdentityKey: IdentityKeyPair
        */

        $structure = $this->sessionStructure->getPendingKeyExchange();
        if($structure == null) $structure = new Textsecure_SessionStructure_PendingKeyExchange();
        $structure->setSequence($sequence);
        $structure->setLocalBaseKey($ourBaseKey->getPublicKey()->serialize());
        $structure->setLocalBaseKeyPrivate($ourBaseKey->getPrivateKey()->serialize());
        $structure->setLocalRatchetKey($ourRatchetKey->getPublicKey()->serialize());
        $structure->setLocalRatchetKeyPrivate($ourRatchetKey->getPrivateKey()->serialize());
        $structure->setLocalIdentityKey($ourIdentityKey->getPublicKey()->serialize());
        $structure->setLocalIdentityKeyPrivate($ourIdentityKey->getPrivateKey()->serialize());

        $this->sessionStructure->setPendingKeyExchange($structure); // should be the same as merge since it only have string/int fields and none of them repeated
    }
    public function getPendingKeyExchangeSequence(){
        return $this->sessionStructure->getPendingKeyExchange()->getSequence();
    }
    public function getPendingKeyExchangeBaseKey(){
        $publicKey = Curve::decodePoint($this->sessionStructure->getPendingKeyExchange()->getLocalBaseKey(), 0);
        $privateKey = Curve::decodePrivatePoint($this->sessionStructure->getPendingKeyExchange()->getLocalBaseKeyPrivate());
        return new ECKeyPair($publicKey, $privateKey);
    }

    public function getPendingKeyExchangeRatchetKey(){
        $publicKey = Curve::decodePoint($this->sessionStructure->getPendingKeyExchange()->getLocalRatchetKey(), 0);
        $privateKey = Curve::decodePrivatePoint($this->sessionStructure->getPendingKeyExchange()->getLocalRatchetKeyPrivate());
        return new ECKeyPair($publicKey, $privateKey);

    }
    public function getPendingKeyExchangeIdentityKey(){
        $publicKey = new IdentityKey($this->sessionStructure->getPendingKeyExchange()->getLocalIdentityKey(), 0);

        $privateKey = Curve::decodePrivatePoint($this->sessionStructure->getPendingKeyExchange()->getLocalIdentityKeyPrivate());
        return new IdentityKeyPair($publicKey, $privateKey);
    }
    public function hasPendingKeyExchange(){
        return $this->sessionStructure->getPendingKeyExchange() != null;
    }

    public function setUnacknowledgedPreKeyMessage($preKeyId, $signedPreKeyId, $baseKey){
        /*
        :type preKeyId: int
        :type signedPreKeyId: int
        :type baseKey: ECPublicKey
        */
        if(!$this->hasUnacknowledgedPreKeyMessage())
            $this->sessionStructure->setPendingPreKey(new Textsecure_SessionStructure_PendingPreKey());
        $this->sessionStructure->getPendingPreKey()->setSignedPreKeyId($signedPreKeyId);
        $this->sessionStructure->getPendingPreKey()->setBaseKey($baseKey->serialize());

        if ($preKeyId != null)
            $this->sessionStructure->getPendingPreKey()->setPreKeyId($preKeyId);
    }
    public function hasUnacknowledgedPreKeyMessage(){
        return $this->sessionStructure->getPendingPreKey() != null;
    }
    public function getUnacknowledgedPreKeyMessageItems(){
        $preKeyId = null;
        if($this->sessionStructure->getPendingPreKey()->getPreKeyId() != null){
            $preKeyId = $this->sessionStructure->getPendingPreKey()->getPreKeyId();
        }

        return new UnacknowledgedPreKeyMessageItems($preKeyId,
                                     $this->sessionStructure->getPendingPreKey()->getSignedPreKeyId(),
                                     Curve::decodePoint($this->sessionStructure->getPendingPreKey()->getBaseKey(), 0));
    }
    public function clearUnacknowledgedPreKeyMessage(){
        $this->sessionStructure->clearPendingPreKey();
    }
    public function setRemoteRegistrationId($registrationId){
        $this->sessionStructure->setRemoteRegistrationId($registrationId);
    }

    public function getRemoteRegistrationId($registrationId){
        return $this->sessionStructure->getRemoteRegistrationId();
    }
    public function setLocalRegistrationId($registrationId){
        $this->sessionStructure->setLocalRegistrationId($registrationId);
    }
    public function getLocalRegistrationId(){
        return $this->sessionStructure->getLocalRegistrationId();
    }
    public function serialize(){
        return $this->sessionStructure->serializeToString();
    }

}
class UnacknowledgedPreKeyMessageItems{
    public function UnacknowledgedPreKeyMessageItems($preKeyId, $signedPreKeyId, $baseKey){
        /*
        :type preKeyId: int
        :type signedPreKeyId: int
        :type baseKey: ECPublicKey
        */
        $this->preKeyId       = $preKeyId;
        $this->signedPreKeyId = $signedPreKeyId;
        $this->baseKey        = $baseKey;
    }

    public function getPreKeyId(){
        return $this->preKeyId;
    }
    public function getSignedPreKeyId(){
        return $this->signedPreKeyId;
    }
    public function getBaseKey(){
        return $this->baseKey;
    }
}


text:
set -o pipefail

# trace ERR through 'time command' and other functions
set -o errtrace

# set -u : exit the script if you try to use an uninitialised variable
set -o nounset

# set -e : exit the script if any statement returns a non-true return value
set -o errexit

# Ensure that this is being run inside a CI
if [ ! -n "$CI" ] || [ "${CI}" != "true" ]; then
    echo "This script is designed to run inside a CI container only. Exiting"
    exit 1
fi

CURRENT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
TRAVIS_BUILD_DIR="${TRAVIS_BUILD_DIR:-$(dirname $(dirname $CURRENT_DIR))}"

PARSER_DIR=$HOME/zephir-parser-${ZEPHIR_PARSER_VERSION}

# Use Travis cache
if [ ! -f ${PARSER_DIR}/unit-tests/ci/install-travis ]; then
    git clone --depth=1 -v https://github.com/phalcon/php-zephir-parser.git -b ${ZEPHIR_PARSER_VERSION} ${PARSER_DIR}
fi

cd ${PARSER_DIR}

bash ./unit-tests/ci/install-travis &> /dev/null


text:
"""
Package that contains all tools for the command line tool of the repoguard.
"""

__import__('pkg_resources').declare_namespace(__name__)


text:
{% extends 'base.html' %}

{% block bodyid %}contact{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>NSF/DOE Public Access Repository Services for Office of Science and Technology Policy (OSTP) Memorandum, "Increasing Access to the Results of Federally Funded Scientific Research</AwardTitle>
    <AwardEffectiveDate>08/01/2014</AwardEffectiveDate>
    <AwardExpirationDate>07/31/2016</AwardExpirationDate>
    <AwardAmount>2964000</AwardAmount>
    <AwardInstrument>
      <Value>Interagency Agreement</Value>
    </AwardInstrument>
    <Organization>
      04010000
      <Directorate>
        <LongName>Direct For Social, Behav & Economic Scie</LongName>
      </Directorate>
      <Division>
        <LongName>SBE Off Of Multidisciplinary Activities</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Alan Tomkins</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>07/22/2014</MinAmdLetterDate>
    <MaxAmdLetterDate>11/24/2015</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1444365</AwardID>
    <Investigator>
      <FirstName>BRIAN</FirstName>
      <LastName>HITSON</LastName>
      <EmailAddress/>
      <StartDate>07/22/2014</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Department of Energy, Office of Scientific and Technical Informa</Name>
      <CityName>Oak Ridge</CityName>
      <ZipCode>378310062</ZipCode>
      <PhoneNumber/>
      <StreetAddress>P.O. Box 62</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Tennessee</StateName>
      <StateCode>TN</StateCode>
    </Institution>
    <ProgramElement>
      7414
      <Text>NSF Public Access Initiative</Text>
    </ProgramElement>
    <ProgramElement>
      177T
      <Text>OTHER MISSION RELATED APPS</Text>
    </ProgramElement>
  </Award>
</rootTag>


text:
var HeadingLevelComponent = require('HeadingLevelComponent');
var HeaderH4 = {
  run: function (test) {
    HeadingLevelComponent(test, {
      headingLevel: 4
    });
  },

  meta: {
    testability: 0,
    title: {
      en: 'The header following an h4 is not an h6',
      nl: 'De header volgend op een h4 is geen h6'
    },
    description: {
      en: 'Header order should not skip a level. Do not follow a h4 haeder with a h6.',
      nl: 'Headers mogen geen niveau overslaan. Laat een h4/code> header niet volgen door een h6.'
    },
    guidelines: {
      wcag: {
        '2.4.6': {
          techniques: [
            'G130'
          ]
        }
      }
    },
    tags: [
      'header',
      'content'
    ]
  }
};
module.exports = HeaderH4;


text:
using System;
using System.Runtime.InteropServices;

namespace CSCapstone.Arm64 {
    /// <summary>
    ///     Native ARM64 Instruction Detail.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct NativeArm64InstructionDetail {
        /// <summary>
        ///     Instruction's Code Condition.
        /// </summary>
        public int CodeCondition;

        /// <summary>
        ///     Instruction's Update Flags Flag.
        /// </summary>
        /// <remarks>
        ///     Interestingly enough, the default .NET Marshaller is marshalling this field from unmanaged memory as
        ///     4 bytes! The result is an overlapping problem. The attribute helps resolves this. Theoretically,
        ///     declaring the field as a byte would also solve the problem but the field is declared in unmanaged memory
        ///     as a boolean. Even more interesting, for other structures, the default .NET Marshaller does not seem
        ///     to have this problem! For an example, see <c>NativeX86InstructionDetail</c>.
        /// </remarks>
        [MarshalAs(UnmanagedType.I1)] public bool UpdateFlags;

        /// <summary>
        ///     Instruction's Write Back Flag.
        /// </summary>
        [MarshalAs(UnmanagedType.I1)] public bool WriteBack;

        /// <summary>
        ///     Number of Instruction's Operands.
        /// </summary>
        public byte OperandCount;

        /// <summary>
        ///     Instruction's First Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand1;

        /// <summary>
        ///     Instruction's Second Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand2;

        /// <summary>
        ///     Instruction's Third Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand3;

        /// <summary>
        ///     Instruction's Fourth Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand4;

        /// <summary>
        ///     Instruction's Fifth Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand5;

        /// <summary>
        ///     Instruction's Sixth Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand6;

        /// <summary>
        ///     Instruction's Seventh Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand7;

        /// <summary>
        ///     Instruction's Eighth Operand.
        /// </summary>
        public NativeArm64InstructionOperand Operand8;

        /// <summary>
        ///     Get Instruction's Managed Code Condition.
        /// </summary>
        /// <value>
        ///     Convenient property to retrieve the instruction's code condition as a managed enumerated type.
        /// </value>
        public Arm64CodeCondition ManagedCodeCondition {
            get {
                var eCodeCondition = (Arm64CodeCondition) this.CodeCondition;
                return eCodeCondition;
            }
        }

        /// <summary>
        ///     Get Instruction's Managed Operands.
        /// </summary>
        /// <value>
        ///     Convenient property to retrieve the instruction's operands as a managed collection. The codeSize of the
        ///     managed collection will always be equal to the value represented by
        ///     <c>NativeArm64InstructionDetail.OperandCount</c>. This property allocates managed memory for a new
        ///     managed collection and copies by value the required <c>NativeArm64InstructionDetail.Operand</c>
        ///     fields every time it is invoked.
        /// </value>
        public NativeArm64InstructionOperand[] ManagedOperands {
            get {
                // Create Managed Collection.
                //
                // Unfortunately, C# does not support fixed arrays, or buffers, for user defined structures. To work
                // around alignment issues with the default .NET Marshaller, and because the convenience of the
                // Capstone API allows it, each operand is declared as an individual field. The following ugly code
                // segment deals with composing those individual fields in an appropriately sized collection.
                //
                // I am so sorry for this ugly code.
                var managedOperands = new NativeArm64InstructionOperand[this.OperandCount];
                var thisType = this.GetType();
                for (var i = 1; i <= managedOperands.Length; i++) {
                    // Get Operand Using Reflection.
                    //
                    // This is a relatively expensive operation. An better approach needs to be investigated.
                    var operandPropertyName = String.Format("Operand{0}", i);
                    var operandProperty = thisType.GetField(operandPropertyName);
                    var operandPropertyValue = (NativeArm64InstructionOperand) operandProperty.GetValue(this);

                    managedOperands[(i - 1)] = operandPropertyValue;
                }

                return managedOperands;
            }
        }
    }
}


text:
package com.wizzardo.tools.cache;

import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by wizzardo on 08/10/16.
 */
public class CacheStatistics {
    protected final AtomicLong getCount = new AtomicLong();
    protected final AtomicLong putCount = new AtomicLong();
    protected final AtomicLong removeCount = new AtomicLong();
    protected final AtomicLong computeCount = new AtomicLong();
    protected final AtomicLong getLatency = new AtomicLong();
    protected final AtomicLong putLatency = new AtomicLong();
    protected final AtomicLong removeLatency = new AtomicLong();
    protected final AtomicLong computeLatency = new AtomicLong();
    protected final AtomicInteger size = new AtomicInteger();
    protected final String cacheName;
    protected final WeakReference<Cache> cache;

    public CacheStatistics(Cache cache) {
        this.cacheName = cache.getName();
        this.cache = new WeakReference<Cache>(cache);
    }

    public boolean isValid() {
        Cache cache = this.cache.get();
        return cache != null && !cache.isDestroyed();
    }

    public long getGetCount() {
        return getCount.get();
    }

    public long getPutCount() {
        return putCount.get();
    }

    public long getRemoveCount() {
        return removeCount.get();
    }

    public long getComputeCount() {
        return computeCount.get();
    }

    public long getGetLatency() {
        return getLatency.get();
    }

    public long getPutLatency() {
        return putLatency.get();
    }

    public long getRemoveLatency() {
        return removeLatency.get();
    }

    public long getComputeLatency() {
        return computeLatency.get();
    }

    public int getSize() {
        return size.get();
    }

    public String getCacheName() {
        return cacheName;
    }
}


text:
package moviesuggestion.suggest.service;

import moviesuggestion.suggest.model.movie.MPAA;
import moviesuggestion.suggest.model.movie.Movie;
import moviesuggestion.suggest.model.search.SearchRequest;
import moviesuggestion.suggest.repository.MovieRepository;
import moviesuggestion.suggest.repository.SearchRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sburroughs on 9/23/2016.
 */
@Service
public class SearchService {

    @Autowired
    private MovieRepository movieRepository;

    @Autowired
    private SearchRepository searchRepository;

    public List<Movie> search(SearchRequest searchRequest) {

        List<Movie> results = new ArrayList<>();

        List<String> titles = searchRequest.getLikes();
        results.addAll(searchRepository.findByTitleIn(titles));

        if (results.size() > 0) {
            Movie currentMovie = results.get(0);
            MPAA rated = currentMovie.getRated();
            results.addAll(searchRepository.findTop10ByRated(rated));
        }

        return results;

    }

}


text:
<menu id="BigCountMenu">
    <menu-item id="item_ran">@Strings.ran</menu-item>
    <menu-item id="item_left">@Strings.left</menu-item>
</menu>


text: from app import flask_app


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ttp="http://stix.mitre.org/TTP-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-15b170cd-f456-48d5-ba33-614c2133074b" version="1.1.1" timestamp="2013-12-30T22:04:23+00:00">
    <stix:TTPs>
        <stix:TTP id="example:ttp-3e6b4e44-6b6a-488b-ae4c-934f5fb6b233" timestamp="2014-12-22T16:22:23.028000+00:00" xsi:type='ttp:TTPType'>
            <ttp:Behavior>
                <ttp:Attack_Patterns>
                    <ttp:Attack_Pattern capec_id="CAPEC-66">
                        <ttp:Title>SQL Injection</ttp:Title>
                    </ttp:Attack_Pattern>
                </ttp:Attack_Patterns>
            </ttp:Behavior>
        </stix:TTP>
    </stix:TTPs>
    <stix:Incidents>
        <stix:Incident id="example:incident-712aa8fb-007f-4a70-ae58-1e6445f8a7e1" timestamp="2014-04-27T19:37:02+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>Vodafone Iceland has been hacked and 77,000 customer records spaffed across the internet. The Icelandic National Broadcasting Service ruv.is reports that the hack became apparent on Saturday. By Sunday Vodafone Iceland had 'fessed up to the breach but denied other reports that personal details including bank account numbers and passwords had been revealed to the world.</incident:Title>
            <incident:External_ID source="VERIS">0C6826E8-15C3-4B87-BEE9-24AB2CACFBB4</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="year">2013-01-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">blackfist</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Vodafone</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>IS</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Web application</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Personal</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Modify data,Repurpose</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Leveraged_TTPs>
                <incident:Leveraged_TTP>
                    <stixCommon:TTP idref="example:ttp-3e6b4e44-6b6a-488b-ae4c-934f5fb6b233" xsi:type='ttp:TTPType'/>
                </incident:Leveraged_TTP>
            </incident:Leveraged_TTPs>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-4806a7f1-1944-4c8c-87fd-5972fbfa133c" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Agent Disclosure</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://www.cyberwarnews.info/2013/11/30/official-vodafone-iceland-hacked-and-defaced-with-77000-accounts-leaked/#.UpliZJmm088.twitter (20131230)</stixCommon:Reference>
                    <stixCommon:Reference>http://www.cyberwarnews.info/reports/official-vodafone-iceland-breach-contents-report-breakdown/#.UpmRLWxTLEI.twitter (20131230)</stixCommon:Reference>
                    <stixCommon:Reference>http://thehackernews.com/2013/11/vodafone-iceland-hacked-and-exposed.html# (20131230)</stixCommon:Reference>
                    <stixCommon:Reference>http://www.theregister.co.uk/2013/12/02/vodafone_iceland_hacked/ (20131230)</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-4806a7f1-1944-4c8c-87fd-5972fbfa133c" timestamp="2014-12-22T16:22:23.028000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Description>Notes: twitter @AgentCoOfficial or otherwise known as Maxn3y who in the past has leaked data from electronic giants, fast food companys, American citys and even airports.</ta:Description>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>TR</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:22:23.028000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Hacktivist</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:22:23.028000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:MotivationVocab-1.1">Ideological</stixCommon:Value>
            </ta:Motivation>
            <ta:Observed_TTPs>
                <ta:Observed_TTP>
                    <stixCommon:TTP idref="example:ttp-3e6b4e44-6b6a-488b-ae4c-934f5fb6b233" xsi:type='ttp:TTPType'/>
                </ta:Observed_TTP>
            </ta:Observed_TTPs>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
using System.Collections.Generic;
using System.Runtime.Serialization;
using mGitHub.SampleApp.Model;

namespace mGitHub.SampleApp.Services
{
	[DataContract]
	public class UserContainer
	{
		[DataMember(Name = "user")]
		public User User { get; set; }
	}

	[DataContract]
	public class RepositoryContainer
	{
		[DataMember(Name = "repository")]
		public Repository Repository { get; set; }
	}

	[DataContract]
    public class RepositoryCollection
    {
        [DataMember(Name = "repositories")]
        public IEnumerable<Repository> Repositories { get; set; }
    }

	[DataContract]
	public class ContributorCollection
	{
		[DataMember(Name = "contributors")]
		public IEnumerable<Contributor> Contributors { get; set; }
	}
}


text:
#ifndef _EC_ARCH_H_
#define _EC_ARCH_H_

#ifdef __APPLE__
	#include <AvailabilityMacros.h>
#endif

/*
#define IS_X86
#define IS_X64

#define IS_WINDOWS // ioctlsocket
#define IS_LINUX
#define IS_MACOS
#define IS_SUN
*/

#ifdef __linux__
	#define HAVE_EPOLL 1
	#define IS_LINUX 1
#endif

#if (defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__)
	#define HAVE_KQUEUE 1
	#define IS_MACOS 1
#endif

#ifdef __sun
	#include <sys/feature_tests.h>
	#ifdef _DTRACE_VERSION
		#define HAVE_EVPORT 1
		#define IS_SUN 1
	#endif
#endif

#if (defined(_WIN32) || defined(_MSC_VER)) // TODO
	#define HAVE_IOCTL 1
	#define IS_WINDOWS 1
#endif

#endif


text:
Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    items: [
        {
            layout: 'hbox',
            border: false,
            items: [
                {
                    xtype: 'container',
                    itemId: 'chart1',
                    flex: 1
                }
            ]
        },
        {
            layout: 'hbox',
            border: false,
            items: [
                {
                    xtype: 'component',
                    itemId: 'text1',
                    html: '

Defects by Root Cause Trend displays a trend of the number of defects in each release split up by their root cause.

'
                }
            ]
        }
    ],
    launch: function() {
        var project = Rally.environment.getContext().getProject();
        var projectOID = project.ObjectID;

        // Query for all releases in the current project
        Ext.create('Rally.data.WsapiDataStore', {
            model: 'Release',
            autoLoad: true,
            listeners: {
                load: this._onReleases,
                scope: this
            },
            fetch: ['Name', 'Project'],
            filters: [
                {
                    property: 'Project.ObjectID',
                    value: projectOID
                }
            ]
        });
    },

    // called when all releases for the current project are returned
    _onReleases: function(store, data, success) {
        this.releaseOids = [];
        this.releaseNames = [];
        var that = this;
        var nonReleases = [
            // LYNXX
            6494344025, // Ungroomed Backlog
            9775860800, // Groomed Backlog
            9775970872, // Graveyard
            9801311596, // US Pricing
            9801312467, // Administrative
            9775859117, // Backlog Grooming Candidates
            5170917313, // On Hold: LYNXX EU Direct Only
            5802742946, // Release 4.0 U.S. Continued

            // Beacon
            15782467405,// Beacon 2013 Code Requests
            16111291351, // Beacon 2014 Code Requests

            // IDEXX.com
            3824207614, // Archive
            10441352563, // Template Backups
            5757464555, // Tablet
            5916754739, // Water and Dairy
            6731062746  // E-Commerce
        ];

        // store each of the releases objectIDs and Names for later use
        _.each(data, function(d) {
            if (!_.contains(nonReleases, d.data.ObjectID)) {    // Knock out non-releases
                that.releaseOids.push(d.data.ObjectID);
                that.releaseNames.push(d.data.Name);
            }
        });

        // Fetch a list of all of the root causes
        Rally.data.ModelFactory.getModel({
            type: 'Defect',
            success: function(model) {
                that.rootCauses = Ext.Array.pluck(model.getField('c_RootCause').allowedValues, 'StringValue');
            }
        });

        // Retrieve all defects from all releases
        Ext.create('Rally.data.lookback.SnapshotStore', {
            autoLoad: true,
            listeners: {
                load: that._aggregateData,
                scope: that
            },
            fetch: ['ObjectID','Name', 'Release', 'c_RootCause'],
            filters: [
                {
                  property: '_TypeHierarchy',
                  operator: 'in',
                  value: ['Defect']
                },
                {
                    property: 'Release',
                    operator: 'in',
                    value: that.releaseOids
                },
                {
                    property: '__At',
                    value: 'current'
                }
            ]
        });
    },

    // Produce counts of defects by root cause
    _aggregateData : function(store, data, success) {
        var that = this;
        var rootCauseData = [];

        // Initialize the series data structure that gets passed to HighCharts
        for (var j = 0; j < that.rootCauses.length; j++) {
            rootCauseData[j] = {
                type: 'line',
                name: that.rootCauses[j],
                data: new Array(that.releaseOids.length)    // Array of data points for each release
            };

            for (var k = 0; k < that.releaseOids.length; k++) {
                rootCauseData[j].data[k] = 0;
            }
        }

        // Generate counts of each defect by root cause
        _.each(data, function(d) {
             ++rootCauseData[_.indexOf(that.rootCauses, d.data.c_RootCause)].data[_.indexOf(that.releaseOids, d.data.Release)];
        });

         // Fixes the formatting of null values for root causes
        for (var i = 0; i < rootCauseData.length; i++) {
            if (rootCauseData[i].name === '') {
                rootCauseData[i].name = 'Not Specified';
            }
        }

        that._showCharts(rootCauseData);
    },

    _showCharts: function(data) {
        var that = this;
        var chart1 = this.down("#chart1");
        chart1.removeAll();

        var extChart1 = Ext.create('Rally.ui.chart.Chart', {
            width: 1200,
            height: 400,
            chartData: {
                series: data,
                categories: that.releaseNames
            },
            chartConfig: {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                title: {
                    text: 'Defects by Root Cause Trend',
                    style: {
                        color: '#000000'
                    }
                },
                yAxis: {
                    title: {
                        text: 'Defect Count'
                    },
                    min: 0
                }
            }
        });

        chart1.add(extChart1);

        // This block is a way to prevent a spinning "loading" icon and mask above the chart
        // Appears to be an artifact from Ext JS
        var p = Ext.get(chart1.id);
        var elems = p.query("div.x-mask");
        _.each(elems, function(e) { e.remove(); });
        elems = p.query("div.x-mask-msg");
        _.each(elems, function(e) { e.remove(); });
    }
});


text:
import path from 'path';

import dedent from 'dedent';
import loopback from 'loopback';
import moment from 'moment';

export const renderSignUpEmail = loopback.template(
  path.join(
    __dirname,
    '..',
    '..',
    'server',
    'views',
    'emails',
    'user-request-sign-up.ejs'
  )
);

export const renderSignInEmail = loopback.template(
  path.join(
    __dirname,
    '..',
    '..',
    'server',
    'views',
    'emails',
    'user-request-sign-in.ejs'
  )
);

export const renderEmailChangeEmail = loopback.template(
  path.join(
    __dirname,
    '..',
    '..',
    'server',
    'views',
    'emails',
    'user-request-update-email.ejs'
  )
);

export function getWaitPeriod(ttl) {
  const fiveMinutesAgo = moment().subtract(5, 'minutes');
  const lastEmailSentAt = moment(new Date(ttl || null));
  const isWaitPeriodOver = ttl
    ? lastEmailSentAt.isBefore(fiveMinutesAgo)
    : true;

  if (!isWaitPeriodOver) {
    const minutesLeft = 5 - (moment().minutes() - lastEmailSentAt.minutes());
    return minutesLeft;
  }

  return 0;
}

export function getWaitMessage(ttl) {
  const minutesLeft = getWaitPeriod(ttl);
  if (minutesLeft <= 0) {
    return null;
  }

  const timeToWait = minutesLeft
    ? `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}`
    : 'a few seconds';

  return dedent`
    Please wait ${timeToWait} to resend an authentication link.
  `;
}

export function getEncodedEmail(email) {
  if (!email) {
    return null;
  }
  return Buffer.from(email).toString('base64');
}

export const decodeEmail = email => Buffer.from(email, 'base64').toString();


text:
using namespace Framework;

HFONT Win32::CreateFont(const TCHAR* faceName, unsigned int height)
{
	LOGFONT font;
	memset(&font, 0, sizeof(font));
	font.lfHeight			= -MulDiv(height, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 72);
	font.lfWidth			= 0;
	font.lfOrientation		= 0;
	font.lfWeight			= FW_NORMAL;
	font.lfItalic			= FALSE;
	font.lfUnderline		= FALSE;
	font.lfStrikeOut		= FALSE;
	font.lfCharSet			= DEFAULT_CHARSET;
	font.lfOutPrecision		= OUT_DEFAULT_PRECIS;
	font.lfClipPrecision	= CLIP_DEFAULT_PRECIS;
	font.lfQuality			= DEFAULT_QUALITY;
	font.lfPitchAndFamily	= DEFAULT_PITCH;
	_tcsncpy(font.lfFaceName, faceName, LF_FACESIZE);
	return CreateFontIndirect(&font);
}

SIZE Win32::GetFixedFontSize(HFONT font)
{
	Framework::Win32::CClientDeviceContext dc(NULL);

	dc.SelectObject(font);

	SIZE s = { 0, 0 };
	GetTextExtentPoint32(dc, _T("0"), 1, &s);
	return s;
}


text:
"""
Surface strings, tokens, and alignments.
"""

from typing import TypeVar, Type, Mapping, Tuple

from penman.types import BasicTriple
from penman.graph import Graph
from penman.epigraph import Epidatum
from penman.exceptions import SurfaceError

T = TypeVar('T', bound='AlignmentMarker')  # for classmethods

class AlignmentMarker(Epidatum):

    __slots__ = 'indices', 'prefix',

    def __init__(self, indices: Tuple[int, ...], prefix: str = None):
        super().__init__()
        self.indices = indices
        self.prefix = prefix

    @classmethod
    def from_string(cls: Type[T], s: str) -> T:
        """
        Instantiate the alignment marker from its string *s*.

        Examples:
            >>> from penman import surface
            >>> surface.Alignment.from_string('1')
            Alignment((1,))
            >>> surface.RoleAlignment.from_string('e.2,3')
            RoleAlignment((2, 3), prefix='e.')
        """

        _s = s.lstrip('~')
        prefix = None
        try:
            if _s[0].isalpha():  # ...~e
                i = 1
                if _s[1] == '.':  # ...~e.
                    i = 2
                prefix = _s[0:i]
                _s = _s[i:]
        except IndexError as exc:
            raise SurfaceError(
                f'invalid alignment marker: {s!r}'
            ) from exc

        try:
            indices = tuple(map(int, _s.split(',')))
        except ValueError as exc:
            raise SurfaceError(
                f'invalid alignments: {s!r}'
            ) from exc

        return cls(indices, prefix=prefix)

    def __repr__(self):
        args = repr(self.indices)
        if self.prefix:
            args += f', prefix={self.prefix!r}'
        name = type(self).__name__
        return f'{name}({args})'

    def __str__(self):
        return '~{}{}'.format(self.prefix or '',
                              ','.join(map(str, self.indices)))

    def __eq__(self, other):
        if not isinstance(other, AlignmentMarker):
            return False
        return (self.prefix == other.prefix
                and self.indices == other.indices)

class Alignment(AlignmentMarker):
    __slots__ = ()
    mode = 2

class RoleAlignment(AlignmentMarker):
    __slots__ = ()
    mode = 1

_Alignments = Mapping[BasicTriple, AlignmentMarker]

def alignments(g: Graph) -> _Alignments:
    """
    Return a mapping of triples to alignments in graph *g*.

    Args:
        g: a :class:`~penman.graph.Graph` containing alignment data
    Returns:
        A :class:`dict` mapping :class:`~penman.graph.Triple` objects
        to their corresponding :class:`Alignment` objects, if any.
    Example:
        >>> from penman import decode
        >>> from penman import surface
        >>> g = decode(
        ...   '(c / chase-01~4'
        ...   '   :ARG0~5 (d / dog~7)'
        ...   '   :ARG0~3 (c / cat~2))')
        >>> surface.alignments(g)  # doctest: +NORMALIZE_WHITESPACE
        {('c', ':instance', 'chase-01'): Alignment((4,)),
         ('d', ':instance', 'dog'): Alignment((7,)),
         ('c', ':instance', 'cat'): Alignment((2,))}
    """
    return _get_alignments(g, Alignment)

def role_alignments(g: Graph) -> _Alignments:
    """
    Return a mapping of triples to role alignments in graph *g*.

    Args:
        g: a :class:`~penman.graph.Graph` containing role alignment
        data
    Returns:
        A :class:`dict` mapping :class:`~penman.graph.Triple` objects
        to their corresponding :class:`RoleAlignment` objects, if any.
    Example:
        >>> from penman import decode
        >>> from penman import surface
        >>> g = decode(
        ...   '(c / chase-01~4'
        ...   '   :ARG0~5 (d / dog~7)'
        ...   '   :ARG0~3 (c / cat~2))')
        >>> surface.role_alignments(g)  # doctest: +NORMALIZE_WHITESPACE
        {('c', ':ARG0', 'd'): RoleAlignment((5,)),
         ('c', ':ARG0', 'c'): RoleAlignment((3,))}
    """
    return _get_alignments(g, RoleAlignment)

def _get_alignments(g: Graph,
                    alignment_type: Type[AlignmentMarker]) -> _Alignments:
    alns = {}
    triple = None
    for triple, epidata in g.epidata.items():
        for epidatum in epidata:
            if isinstance(epidatum, alignment_type):
                alns[triple] = epidatum
    return alns


text:
"use strict";

const isStandardSyntaxRule = require("../../utils/isStandardSyntaxRule");
const parseSelector = require("../../utils/parseSelector");
const report = require("../../utils/report");
const ruleMessages = require("../../utils/ruleMessages");
const validateOptions = require("../../utils/validateOptions");

const ruleName = "selector-attribute-quotes";

const messages = ruleMessages(ruleName, {
  expected: value => `Expected quotes around "${value}"`,
  rejected: value => `Unexpected quotes around "${value}"`
});

const rule = function(expectation) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: expectation,
      possible: ["always", "never"]
    });
    if (!validOptions) {
      return;
    }

    root.walkRules(rule => {
      if (!isStandardSyntaxRule(rule)) {
        return;
      }
      if (
        rule.selector.indexOf("[") === -1 ||
        rule.selector.indexOf("=") === -1
      ) {
        return;
      }

      parseSelector(rule.selector, result, rule, selectorTree => {
        selectorTree.walkAttributes(attributeNode => {
          if (!attributeNode.operator) {
            return;
          }

          const attributeSelectorString = attributeNode.toString();

          if (!attributeNode.quoted && expectation === "always") {
            complain(
              messages.expected(attributeNode.raws.unquoted),
              attributeNode.sourceIndex +
                attributeSelectorString.indexOf(attributeNode.value)
            );
          }

          if (attributeNode.quoted && expectation === "never") {
            complain(
              messages.rejected(attributeNode.raws.unquoted),
              attributeNode.sourceIndex +
                attributeSelectorString.indexOf(attributeNode.value)
            );
          }
        });
      });

      function complain(message, index) {
        report({
          message,
          index,
          result,
          ruleName,
          node: rule
        });
      }
    });
  };
};

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;


text:
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended;

namespace XmasHell.Physics.Collision
{
    public class CollisionConvexPolygon : CollisionElement
    {
        private Vector2 _relativePosition;
        // Local positions relative to the entity position
        protected readonly List<Vector2> Vertices = new List<Vector2>();

        public CollisionConvexPolygon(IPhysicsEntity entity, Vector2 relativePosition, List<Vector2> vertices) : base(entity)
        {
            _relativePosition = relativePosition;
            Vertices = vertices;
        }

        protected CollisionConvexPolygon(IPhysicsEntity entity) : base(entity)
        {
        }

        public virtual Vector2 GetWorldPosition(Vector2 vertex)
        {
            var entityTransformMatrix = GetMatrix();
            var vertexPosition = new Vector3(vertex + _relativePosition, 0f);
            var transformedVertexPosition = Vector3.Transform(vertexPosition, entityTransformMatrix);
            var newPosition = new Vector2(transformedVertexPosition.X, transformedVertexPosition.Y);

            return newPosition;
        }

        public override bool Intersects(CollisionCircle circle)
        {
            var radiusSquared = circle.GetRadius() * circle.GetRadius();
            var vertex = GetWorldPosition(Vertices[Vertices.Count - 1]);
            var circleCenter = circle.GetCenter();
            var nearestDistance = float.MaxValue;
            var nearestIsInside = false;
            var nearestVertex = -1;
            var lastIsInside = false;

            for (var i = 0; i < Vertices.Count; i++)
            {
                var nextVertex = GetWorldPosition(Vertices[i]);
                var axis = circleCenter - vertex;
                var distance = axis.LengthSquared() - radiusSquared;

                if (distance <= 0)
                    return true;

                var isInside = false;
                var edge = nextVertex - vertex;
                var edgeLengthSquared = edge.LengthSquared();

                if (!edgeLengthSquared.Equals(0))
                {
                    // Check whether the circle overlap an edge of the polyhon
                    var dot = Vector2.Dot(edge, axis);

                    if (dot >= 0 && dot <= edgeLengthSquared)
                    {
                        var projection = vertex + (dot / edgeLengthSquared) * edge;
                        axis = projection - circleCenter;

                        if (axis.LengthSquared() <= radiusSquared)
                            return true;

                        if (edge.X > 0)
                        {
                            if (axis.Y > 0)
                                return false;
                        }
                        else if (edge.X < 0)
                        {
                            if (axis.Y < 0)
                                return false;
                        }
                        else if (edge.Y > 0)
                        {
                            if (axis.X < 0)
                                return false;
                        }
                        else if (edge.Y < 0)
                        {
                            if (axis.X > 0)
                                return false;
                        }

                        isInside = true;
                    }
                }

                if (distance < nearestDistance)
                {
                    nearestDistance = distance;
                    nearestIsInside = isInside;// || lastIsInside;
                    nearestVertex = i;
                }

                vertex = nextVertex;
                lastIsInside = isInside;
            }

            if (nearestVertex == 0)
                return nearestIsInside || lastIsInside;

            return nearestIsInside;
        }

        public override bool Intersects(CollisionConvexPolygon element)
        {
            throw new System.NotImplementedException();
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            if (Vertices.Count == 0)
                return;

            var previousPosition = GetWorldPosition(Vertices[0]);

            for (int i = 1; i <= Vertices.Count; i++)
            {
                var position = GetWorldPosition(i == Vertices.Count ? Vertices[0] : Vertices[i]);

                // Draw edges
                spriteBatch.DrawLine(
                    previousPosition.X,
                    previousPosition.Y,
                    position.X,
                    position.Y,
                    Color.Red,
                    5f
                );

                // Draw normals
                Vector2 axis = Vector2.Normalize(position - previousPosition);
                spriteBatch.DrawLine(
                    (previousPosition.X + position.X) / 2f,
                    (previousPosition.Y + position.Y) / 2f,
                    (previousPosition.X) + axis.Y * 2000,
                    (previousPosition.Y) - axis.X * 2000,
                    Color.Red,
                    2f);

                previousPosition = position;
            }
        }
    }
}