text:
module NetSuite
  module Records
    class SalesOrder
      include Support::Fields
      include Support::RecordRefs
      include Support::Records
      include Support::Actions
      include Namespaces::TranSales

      actions :attach_file, :get, :get_list, :add, :initialize, :delete, :update, :upsert, :upsert_list, :search

      fields :alt_handling_cost, :alt_shipping_cost, :amount_paid, :amount_remaining, :auto_apply, :balance,
        :bill_address, :cc_approved, :contrib_pct, :created_date, :currency_name, :deferred_revenue, :discount_rate, :email, :end_date,
        :est_gross_profit, :exchange_rate, :exclude_commission, :fax, :gift_cert_applied,
        :gift_cert_available, :gift_cert_total, :handling_cost, :handling_tax1_rate, :handling_tax2_rate, :is_taxable,
        :last_modified_date, :memo, :message, :on_credit_hold, :order_status, :other_ref_num, :recognized_revenue,
        :rev_rec_on_rev_commitment, :sales_effective_date, :ship_complete, :ship_date, :shipping_cost, :shipping_tax1_rate, :shipping_tax2_rate, :source,
        :start_date, :status, :sync_partner_teams, :sync_sales_teams, :tax2_total, :tax_rate, :to_be_emailed, :to_be_faxed,
        :to_be_printed, :total_cost_estimate, :tran_date, :tran_id, :tran_is_vsoe_bundle, :vat_reg_num,
        :linked_tracking_numbers, :vsoe_auto_calc, :quantity, :bill_city, :bill_state, :ship_city, :ship_state, :cost_estimate,
        :amount, :is_ship_address, :auth_code, :pn_ref_num, :is_multi_ship_to

      # NOTE API >= 2014_2 only
      field :shipping_address, Address
      field :billing_address, Address

      # NOTE transaction address fields only applicable for API < 2014_2
      field :transaction_ship_address, ShipAddress
      field :transaction_bill_address, BillAddress

      field :item_list,                   SalesOrderItemList
      field :custom_field_list,           CustomFieldList
      field :gift_cert_redemption_list,   GiftCertRedemptionList
      field :ship_group_list,             SalesOrderShipGroupList
      field :promotions_list,             PromotionsList
      field :null_field_list,             NullFieldList

      read_only_fields :applied, :discount_total, :sub_total, :tax_total, :total, :unapplied,
                       :est_gross_profit_percent

      record_refs :account, :bill_address_list, :created_from, :currency, :custom_form, :department, :discount_item, :entity, :gift_cert,
        :handling_tax_code, :job, :klass, :lead_source, :location, :message_sel, :opportunity, :partner, :posting_period, :promo_code,
        :sales_group, :sales_rep, :ship_method, :shipping_tax_code, :subsidiary, :terms, :tax_item, :payment_method, :ship_address_list

      attr_reader :internal_id
      attr_accessor :external_id

      def initialize(attributes = {})
        @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id)
        @external_id = attributes.delete(:external_id) || attributes.delete(:@external_id)
        initialize_from_attributes_hash(attributes)
      end

      def self.search_class_name
        "Transaction"
      end

    end
  end
end


text:
#include "berryEmptyTabItem.h"

namespace berry
{

QRect EmptyTabItem::GetBounds()
{
  return QRect();
}

void EmptyTabItem::SetInfo(const PartInfo&  /*info*/)
{

}

void EmptyTabItem::Dispose()
{

}

Object::Pointer EmptyTabItem::GetData()
{
  return Object::Pointer(nullptr);
}

void EmptyTabItem::SetData(Object::Pointer  /*data*/)
{

}

}

redpajama_set_name: RedPajamaGithub


text:
<TITLE>XML::Handler::Composer - Another XML printer/writer/generator</TITLE>
NAME

XML::Handler::Composer - Another XML printer/writer/generator

SYNOPSIS

use XML::Handler::Composer;

my $composer = new XML::Handler::Composer ( [OPTIONS] );

DESCRIPTION

XML::Handler::Composer is similar to XML::Writer, XML::Handler::XMLWriter,
XML::Handler::YAWriter etc. in that it generates XML output.

This implementation may not be fast and it may not be the best solution for
your particular problem, but it has some features that may be missing in the
other implementations:

Supports every output encoding that XML::UM supports

XML::UM supports every encoding for which there is a mapping file
in the XML::Encoding distribution.

* Pretty printing

When used with XML::Filter::Reindent.

* Fine control over which kind of quotes are used

See options below.

* Supports PerlSAX interface

Constructor Options

* EndWithNewline (Default: 1)

Whether to print a newline at the end of the file (i.e. after the root element)

* Newline (Default: undef)

If defined, which newline to use for printing.
(Note that XML::Parser etc. convert newlines into "\x0A".)

If undef, newlines will not be converted and XML::Handler::Composer will
use "\x0A" when printing.

A value of "\n" will convert the internal newlines into the platform
specific line separator.

See the PreserveWS option in the characters event (below) for finer control
over when newline conversion is active.

* DocTypeIndent (Default: a Newline and 2 spaces)

Newline plus indent that is used to separate lines inside the DTD.

* IndentAttList (Default: 8 spaces)

Indent used when printing an <!ATTLIST> declaration that has more than one
attribute definition, e.g.

 <!ATTLIST my_elem
        attr1 CDATA "foo"
        attr2 CDATA "bar"
 >

* Quote (Default: { XMLDecl => '"', Attr => '"', Entity => '"', SystemLiteral => '"' })

Quote contains a reference to a hash that defines which quoting characters
to use when printing XML declarations (XMLDecl), attribute values (Attr),
<!ENTITY> values (Entity) and system/public literals (SystemLiteral)
as found in <!DOCTYPE>, <!ENTITY> declarations etc.

* PrintDefaultAttr (Default: 0)

If 1, prints attribute values regardless of whether they are default
attribute values (as defined in <!ATTLIST> declarations.)
Normally, default attributes are not printed.

* Encoding (Default: undef)

Defines the output encoding (if specified.)
Note that future calls to the xml_decl() handler may override this setting
(if they contain an Encoding definition.)

* EncodeUnmapped (Default: \&XML::UM::encode_unmapped_dec)

Defines how Unicode characters not found in the mapping file (of the
specified encoding) are printed.
By default, they are converted to decimal entity references, like '&#123;'

Use \&XML::UM::encode_unmapped_hex for hexadecimal constants, like '&#xAB;'

* Print (Default: sub { print @_ }, which prints to stdout)

The subroutine that is used to print the encoded XML output.
The default prints the string to stdout.

Method: get_compressed_element_suffix ($event)

Override this method to support the different styles for printing
empty elements in compressed notation, e.g. <p/>, <p></p>, <p />, <p>.

The default returns "/>", which results in <p/>.
Use " />" for XHTML style elements or ">" for certain HTML style elements.

The $event parameter is the hash reference that was received from the
start_element() handler.

Extra PerlSAX event information

XML::Handler::Composer relies on hints from previous SAX filters to
format certain parts of the XML.
These SAX filters (e.g. XML::Filter::Reindent) pass extra information by adding
name/value pairs to the appropriate PerlSAX events (the events themselves are
hash references.)

* entity_reference: Parameter => 1

If Parameter is 1, it means that it is a parameter entity reference.
A parameter entity is referenced with %ent; instead of &ent; and the
entity declaration starts with <!ENTITY % ent ...> instead of <!ENTITY ent ...>

NOTE: This should be added to the PerlSAX interface!

* start_element/end_element: Compress => 1

If Compress is 1 in both the start_element and end_element event, the element
will be printed in compressed form, e.g. <a/> instead of <a></a>.

* start_element: PreserveWS => 1

If newline conversion is active (i.e. Newline was defined in the constructor),
then newlines will *NOT* be converted in text (character events) within this
element.

* attlist_decl: First, MoreFollow

The First and MoreFollow options can be used to force successive <!ATTLIST>
declarations for the same element to be merged, e.g.

 <!ATTLIST my_elem
        attr1 CDATA "foo"
        attr2 CDATA "bar"
        attr3 CDATA "quux"
 >

In this example, the attlist_decl event for foo should contain
(First => 1, MoreFollow => 1) and the event for bar should contain
(MoreFollow => 1). The quux event should have no extra info.

'First' indicates that the event is the first of a sequence.
'MoreFollow' indicates that more events will follow in this sequence.

If neither option is set by the preceding PerlSAX filter, each attribute
definition will be printed as a separate <!ATTLIST> line.

CAVEATS

This code is highly experimental!
It has not been tested well and the API may change.

AUTHOR

Send bug reports, hints, tips, suggestions to Enno Derksen at
<enno@att.com>.

Last updated: Wed Feb 23 13:37:31 2000


text:
package org.apache.usergrid.persistence.cassandra;

import java.math.BigInteger;
import java.util.Iterator;
import java.util.UUID;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.TokenRewriteStream;
import org.junit.Test;
import org.apache.usergrid.cassandra.Concurrent;
import org.apache.usergrid.persistence.Query;
import org.apache.usergrid.persistence.exceptions.PersistenceException;
import org.apache.usergrid.persistence.query.ir.AndNode;
import org.apache.usergrid.persistence.query.ir.NotNode;
import org.apache.usergrid.persistence.query.ir.OrNode;
import org.apache.usergrid.persistence.query.ir.QuerySlice;
import org.apache.usergrid.persistence.query.ir.SliceNode;
import org.apache.usergrid.persistence.query.ir.WithinNode;
import org.apache.usergrid.persistence.query.tree.QueryFilterLexer;
import org.apache.usergrid.persistence.query.tree.QueryFilterParser;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

/** @author tnine */
@Concurrent()
public class QueryProcessorTest {

    @Test
    public void equality() throws Exception {
        String queryString = "select * where a = 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( BigInteger.valueOf( 5 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 5 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void lessThan() throws Exception {
        String queryString = "select * where a < 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertNull( slice.getStart() );

        assertEquals( BigInteger.valueOf( 5 ), slice.getFinish().getValue() );
        assertFalse( slice.getFinish().isInclusive() );
    }

    @Test
    public void lessThanEquals() throws Exception {
        String queryString = "select * where a <= 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertNull( slice.getStart() );

        assertEquals( BigInteger.valueOf( 5 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void greaterThan() throws Exception {
        String queryString = "select * where a > 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( BigInteger.valueOf( 5 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertNull( slice.getFinish() );
    }

    @Test
    public void greaterThanEquals() throws Exception {
        String queryString = "select * where a >= 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( BigInteger.valueOf( 5 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertNull( slice.getFinish() );
    }

    @Test
    public void contains() throws Exception {
        String queryString = "select * where a contains 'foo'";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a.keywords", slice.getPropertyName() );

        assertEquals( "foo", slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertEquals( "foo", slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void containsLower() throws Exception {
        String queryString = "select * where a contains 'FOO'";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a.keywords", slice.getPropertyName() );

        assertEquals( "foo", slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertEquals( "foo", slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void containsRange() throws Exception, PersistenceException {
        String queryString = "select * where a contains 'foo*'";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a.keywords", slice.getPropertyName() );

        assertEquals( "foo", slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertEquals( "foo\uffff", slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void within() throws Exception {
        String queryString = "select * where a within .5 of 157.00, 0.00";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        WithinNode node = ( WithinNode ) processor.getFirstNode();

        assertEquals( "a.coordinates", node.getPropertyName() );
        assertEquals( .5f, node.getDistance(), 0 );
        assertEquals( 157f, node.getLattitude(), 0 );
        assertEquals( 0f, node.getLongitude(), 0 );
    }

    @Test
    public void andEquality() throws Exception {
        assertAndQuery( "select * where a = 1 and b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 AND b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 AnD b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 ANd b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 anD b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 ANd b = 2 and c = 3" );
        assertAndQuery( "select * where a = 1 && b = 2 && c = 3" );
    }

    private void assertAndQuery( String queryString ) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );

        slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );

        slice = slices.next();

        assertEquals( "c", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 3 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 3 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void orEquality() throws Exception {
        assertOrQuery( "select * where a = 1 or b = 2" );
        assertOrQuery( "select * where a = 1 OR b = 2" );
        assertOrQuery( "select * where a = 1 oR b = 2" );
        assertOrQuery( "select * where a = 1 Or b = 2" );
        assertOrQuery( "select * where a = 1 || b = 2" );
    }

    private void assertOrQuery( String queryString ) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        OrNode node = ( OrNode ) processor.getFirstNode();

        SliceNode sliceNode = ( SliceNode ) node.getLeft();

        Iterator<QuerySlice> slices = sliceNode.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );

        sliceNode = ( SliceNode ) node.getRight();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    /** Tests that when properties are not siblings, they are properly assigned to a SliceNode */
    @Test
    public void nestedCompression() throws Exception {
        String queryString =
                "select * where (a > 1 and b > 10 and a < 10 and b < 20 ) or ( c >= 20 and d >= 30 and c <= 30 and d "
                        + "<= 40)";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        OrNode node = ( OrNode ) processor.getFirstNode();

        SliceNode sliceNode = ( SliceNode ) node.getLeft();

        Iterator<QuerySlice> slices = sliceNode.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertEquals( BigInteger.valueOf( 10 ), slice.getFinish().getValue() );
        assertFalse( slice.getFinish().isInclusive() );

        slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 10 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertEquals( BigInteger.valueOf( 20 ), slice.getFinish().getValue() );
        assertFalse( slice.getFinish().isInclusive() );

        sliceNode = ( SliceNode ) node.getRight();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "c", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 20 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 30 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );

        slice = slices.next();

        assertEquals( "d", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 30 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 40 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    /** Tests that when there are multiple or with and clauses, the tree is constructed correctly */
    @Test
    public void nestedOrCompression() throws Exception {
        String queryString =
                "select * where ((a > 1 and  a < 10) or (b > 10 and b < 20 )) or (( c >= 20 and c <= 30 ) or (d >= 30"
                        + "  and d <= 40))";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        OrNode rootNode = ( OrNode ) processor.getFirstNode();

        OrNode node = ( OrNode ) rootNode.getLeft();

        // get the left node of the or

        SliceNode sliceNode = ( SliceNode ) node.getLeft();

        Iterator<QuerySlice> slices = sliceNode.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertEquals( BigInteger.valueOf( 10 ), slice.getFinish().getValue() );
        assertFalse( slice.getFinish().isInclusive() );

        // get our right node
        sliceNode = ( SliceNode ) node.getRight();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 10 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertEquals( BigInteger.valueOf( 20 ), slice.getFinish().getValue() );
        assertFalse( slice.getFinish().isInclusive() );

        node = ( OrNode ) rootNode.getRight();

        sliceNode = ( SliceNode ) node.getLeft();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "c", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 20 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 30 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );

        sliceNode = ( SliceNode ) node.getRight();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "d", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 30 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 40 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    /** Tests that when NOT is not the root operand the tree has a different root */
    @Test
    public void andNot() throws Exception {
        String queryString = "select * where a > 1 and not b = 2";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        AndNode rootNode = ( AndNode ) processor.getFirstNode();

        SliceNode sliceNode = ( SliceNode ) rootNode.getLeft();

        Iterator<QuerySlice> slices = sliceNode.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 1 ), slice.getStart().getValue() );
        assertFalse( slice.getStart().isInclusive() );

        assertNull( slice.getFinish() );

        NotNode notNode = ( NotNode ) rootNode.getRight();

        // now get the child of the not node
        sliceNode = ( SliceNode ) notNode.getSubtractNode();

        slices = sliceNode.getAllSlices().iterator();

        slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    /** Tests that when NOT is the root operand, a full scan range is performed. */
    @Test
    public void notRootOperand() throws Exception {
        String queryString = "select * where not b = 2";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        NotNode rootNode = ( NotNode ) processor.getFirstNode();

        SliceNode sliceNode = ( SliceNode ) rootNode.getSubtractNode();

        Iterator<QuerySlice> slices = sliceNode.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "b", slice.getPropertyName() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 2 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void stringWithSpaces() throws Exception {
        String queryString = "select * where a = 'foo with bar'";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );

        assertEquals( "foo with bar", slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertEquals( "foo with bar", slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void fieldWithDash() throws Exception {
        String queryString = "select * where a-foo = 5";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a-foo", slice.getPropertyName() );

        assertEquals( BigInteger.valueOf( 5 ), slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( BigInteger.valueOf( 5 ), slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void stringWithDash() throws Exception {
        String queryString = "select * where a = 'foo-bar'";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "a", slice.getPropertyName() );

        assertEquals( "foo-bar", slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );

        assertEquals( "foo-bar", slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }

    @Test
    public void uuidParse() throws Exception {

        //    UUID value = UUID.fromString("4b91a9c2-86a1-11e2-b7fa-68a86d52fa56");
        //
        //
        //    String queryString = "select * where uuid = 4b91a9c2-86a1-11e2-b7fa-68a86d52fa56";

        UUID value = UUID.fromString( "c6ee8a1c-3ef4-11e2-8861-02e81adcf3d0" );
        String queryString = "select * where uuid = c6ee8a1c-3ef4-11e2-8861-02e81adcf3d0";

        ANTLRStringStream in = new ANTLRStringStream( queryString );
        QueryFilterLexer lexer = new QueryFilterLexer( in );
        TokenRewriteStream tokens = new TokenRewriteStream( lexer );
        QueryFilterParser parser = new QueryFilterParser( tokens );

        Query query = parser.ql().query;

        QueryProcessor processor = new QueryProcessor( query, null, null, null );

        SliceNode node = ( SliceNode ) processor.getFirstNode();

        Iterator<QuerySlice> slices = node.getAllSlices().iterator();

        QuerySlice slice = slices.next();

        assertEquals( "uuid", slice.getPropertyName() );

        assertEquals( value, slice.getStart().getValue() );
        assertTrue( slice.getStart().isInclusive() );
        assertEquals( value, slice.getFinish().getValue() );
        assertTrue( slice.getFinish().isInclusive() );
    }
}


text:
CKEDITOR.plugins.add('nf_button', {
    requires: 'widget',
    icons: 'nf_button',

    init: function( editor ) {
        editor.widgets.add( 'nf_button', {
            editables: {
                content: {
                    selector: '.nf-button-content',
                }
            },

            template:
                '<button type="button" class="btn btn-default nf-button">'+
                'Content...'+
                '</button>',

            upcast: function( element ) {
                return element.name == 'div' && element.hasClass( 'nf-button' );
            }
        } );
    }
});


text:
(function (jasmine) {
    'use strict';
    var module = {};

    module.getProps = function (constructor, StopAtConstructor) {
        var constructorKeys,
            getKeys = function (obj) {
                var key, keys = [];

                for (key in obj.prototype) {
                    keys.push(key);
                }

                return _.uniq(keys);
            };

        constructorKeys = getKeys(constructor);

        if (_.isFunction(StopAtConstructor)) {
            constructorKeys = _.difference(constructorKeys, getKeys(StopAtConstructor));
        }

        return constructorKeys;
    };

    module.create = function (constructor, StopAtConstructor) {
        var stopAtConstructorInstance, spyObject, key;
        if (!_.isFunction(StopAtConstructor)) {
            StopAtConstructor = null;
        }
        spyObject = jasmine.createSpyObj('mock', module.getProps(constructor, StopAtConstructor));
        if (StopAtConstructor) {
            stopAtConstructorInstance = new StopAtConstructor();
            for (key in spyObject) {
                stopAtConstructorInstance[key] = spyObject[key];
            }
            spyObject = stopAtConstructorInstance;
        }

        return spyObject;
    };

    jasmine.mock = module;
}(jasmine));


text:
;(function($) {

  $.fn.extend({
    afTasks: function(options) {
      if (!options || (options && typeof(options) !== 'string')) {
        options = $.extend( {}, $.afTasks._callbacks, options || {} );
      }

      this.each(function() {
        var tasks_obj = null;

        if (options && typeof(options) === 'string') {
          tasks_obj = $.data(this, 'afTasks');

          if (options === 'clearCompletedTasks') {
            tasks_obj.clearCompletedTasks(this);
          }
          return;
        }

         $.data(this, 'afTasks', new $.afTasks(this, options));
      });

      return;
    }
  });

  $.afTasks = function (_elem, _options) {
    var self = this;
    this.callbacks = _options;

    this.clearCompletedTasks = function (elem) {
      $('.completed', $(elem)).hide(200, function() {
        $(this).remove();
      });
      this.callbacks.clearCallback(elem);
    };

    $('.widget-tasks').on('click', '.task input[type=checkbox]', function (e) {
      $(this).parents('.task').toggleClass('completed');
      if ($(this).parents('.task').hasClass('completed')) {
        self.callbacks.completeCallback(_elem, e);
      } else {
        self.callbacks.cancelCallback(_elem, e);
      }
    });

    $('.widget-tasks').on('click', '.task a', function () {
      $('input', $(this).prev('div')).click();
      return false;
    });
  };

  $.afTasks._callbacks = {
     completeCallback: function (elem, event) {},
     cancelCallback: function (elem, event) {},
     clearCallback: function (elem) {}
  };

})(jQuery);


text:
#region License
// Copyright (c) Amos Voron. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE in the project root for license information.
#endregion

namespace QueryTalk.Wall
{
    /// <summary>
    /// This class is not intended for public use.
    /// </summary>
    public sealed class BeginTableColumnNullableChainer : Chainer, IStatement,
        IBeginTableColumn,
        IBeginTablePrimaryKey,
        IBeginTableUniqueKey,
        IEndTable
    {
        internal BeginTableColumnNullableChainer(Chainer prev, bool isNullable)
            : base(prev)
        {
            GetPrev<BeginTableColumnChainer>().IsNullable = isNullable;
        }
    }
}


text:
"""Data model classes for parsing and generating XML for the Contacts API."""

__author__ = 'vinces1979@gmail.com (Vince Spicer)'

import atom.core
import gdata
import gdata.data

PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'

EXTERNAL_ID_ORGANIZATION = 'organization'

RELATION_MANAGER = 'manager'

CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
CONTACTS_TEMPLATE = '{%s}%%s' % CONTACTS_NAMESPACE

class BillingInformation(atom.core.XmlElement):
  """
  gContact:billingInformation
  Specifies billing information of the entity represented by the contact. The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'billingInformation'

class Birthday(atom.core.XmlElement):
  """
 Stores birthday date of the person represented by the contact. The element cannot be repeated.
 """

  _qname = CONTACTS_TEMPLATE % 'birthday'
  when = 'when'

class ContactLink(atom.data.Link):
  """
  Extends atom.data.Link to add gd:etag attribute for photo link.
  """
  etag = gdata.data.GD_TEMPLATE % 'etag'

class CalendarLink(atom.core.XmlElement):
  """
  Storage for URL of the contact's calendar. The element can be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'calendarLink'
  rel = 'rel'
  label = 'label'
  primary = 'primary'
  href = 'href'

class DirectoryServer(atom.core.XmlElement):
  """
  A directory server associated with this contact.
  May not be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'directoryServer'

class Event(atom.core.XmlElement):
  """
  These elements describe events associated with a contact.
  They may be repeated
  """

  _qname = CONTACTS_TEMPLATE % 'event'
  label = 'label'
  rel = 'rel'
  when = gdata.data.When

class ExternalId(atom.core.XmlElement):
  """
   Describes an ID of the contact in an external system of some kind.
  This element may be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'externalId'
  label = 'label'
  rel = 'rel'
  value = 'value'

def ExternalIdFromString(xml_string):
  return atom.core.parse(ExternalId, xml_string)

class Gender(atom.core.XmlElement):
  """
  Specifies the gender of the person represented by the contact.
  The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'gender'
  value = 'value'

class Hobby(atom.core.XmlElement):
  """
  Describes an ID of the contact in an external system of some kind.
  This element may be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'hobby'

class Initials(atom.core.XmlElement):
  """ Specifies the initials of the person represented by the contact. The
  element cannot be repeated. """

  _qname = CONTACTS_TEMPLATE % 'initials'

class Jot(atom.core.XmlElement):
  """
  Storage for arbitrary pieces of information about the contact. Each jot
  has a type specified by the rel attribute and a text value.
  The element can be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'jot'
  rel = 'rel'

class Language(atom.core.XmlElement):
  """
 Specifies the preferred languages of the contact.
 The element can be repeated.

  The language must be specified using one of two mutually exclusive methods:
  using the freeform @label attribute, or using the @code attribute, whose value
  must conform to the IETF BCP 47 specification.
  """

  _qname = CONTACTS_TEMPLATE % 'language'
  code = 'code'
  label = 'label'

class MaidenName(atom.core.XmlElement):
  """
  Specifies maiden name of the person represented by the contact.
  The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'maidenName'

class Mileage(atom.core.XmlElement):
  """
  Specifies the mileage for the entity represented by the contact.
  Can be used for example to document distance needed for reimbursement
  purposes. The value is not interpreted. The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'mileage'

class NickName(atom.core.XmlElement):
  """
  Specifies the nickname of the person represented by the contact.
  The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'nickname'

class Occupation(atom.core.XmlElement):
  """
  Specifies the occupation/profession of the person specified by the contact.
  The element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'occupation'

class Priority(atom.core.XmlElement):
  """
  Classifies importance of the contact into 3 categories:
    * Low
    * Normal
    * High

  The priority element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'priority'

class Relation(atom.core.XmlElement):
  """
  This element describe another entity (usually a person) that is in a
  relation of some kind with the contact.
  """

  _qname = CONTACTS_TEMPLATE % 'relation'
  rel = 'rel'
  label = 'label'

class Sensitivity(atom.core.XmlElement):
  """
  Classifies sensitivity of the contact into the following categories:
    * Confidential
    * Normal
    * Personal
    * Private

  The sensitivity element cannot be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'sensitivity'
  rel = 'rel'

class UserDefinedField(atom.core.XmlElement):
  """
  Represents an arbitrary key-value pair attached to the contact.
  """

  _qname = CONTACTS_TEMPLATE % 'userDefinedField'
  key = 'key'
  value = 'value'

def UserDefinedFieldFromString(xml_string):
  return atom.core.parse(UserDefinedField, xml_string)

class Website(atom.core.XmlElement):
  """
  Describes websites associated with the contact, including links.
  May be repeated.
  """

  _qname = CONTACTS_TEMPLATE % 'website'

  href = 'href'
  label = 'label'
  primary = 'primary'
  rel = 'rel'

def WebsiteFromString(xml_string):
  return atom.core.parse(Website, xml_string)

class HouseName(atom.core.XmlElement):
  """
  Used in places where houses or buildings have names (and
  not necessarily numbers), eg. "The Pillars".
  """

  _qname = CONTACTS_TEMPLATE % 'housename'

class Street(atom.core.XmlElement):
  """
  Can be street, avenue, road, etc. This element also includes the house
  number and room/apartment/flat/floor number.
  """

  _qname = CONTACTS_TEMPLATE % 'street'

class POBox(atom.core.XmlElement):
  """
  Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not
  always mutually exclusive with street
  """

  _qname = CONTACTS_TEMPLATE % 'pobox'

class Neighborhood(atom.core.XmlElement):
  """
  This is used to disambiguate a street address when a city contains more than
  one street with the same name, or to specify a small place whose mail is
  routed through a larger postal town. In China it could be a county or a
  minor city.
  """

  _qname = CONTACTS_TEMPLATE % 'neighborhood'

class City(atom.core.XmlElement):
  """
  Can be city, village, town, borough, etc. This is the postal town and not
  necessarily the place of residence or place of business.
  """

  _qname = CONTACTS_TEMPLATE % 'city'

class SubRegion(atom.core.XmlElement):
  """
  Handles administrative districts such as U.S. or U.K. counties that are not
   used for mail addressing purposes. Subregion is not intended for
   delivery addresses.
  """

  _qname = CONTACTS_TEMPLATE % 'subregion'

class Region(atom.core.XmlElement):
  """
  A state, province, county (in Ireland), Land (in Germany),
  departement (in France), etc.
  """

  _qname = CONTACTS_TEMPLATE % 'region'

class PostalCode(atom.core.XmlElement):
  """
  Postal code. Usually country-wide, but sometimes specific to the
  city (e.g. "2" in "Dublin 2, Ireland" addresses).
  """

  _qname = CONTACTS_TEMPLATE % 'postcode'

class Country(atom.core.XmlElement):
  """ The name or code of the country. """

  _qname = CONTACTS_TEMPLATE % 'country'

class Status(atom.core.XmlElement):
  """Person's status element."""

  _qname = CONTACTS_TEMPLATE % 'status'
  indexed = 'indexed'

class PersonEntry(gdata.data.BatchEntry):
  """Represents a google contact"""

  link = [ContactLink]

  billing_information = BillingInformation
  birthday = Birthday
  calendar_link = [CalendarLink]
  directory_server = DirectoryServer
  event = [Event]
  external_id = [ExternalId]
  gender = Gender
  hobby = [Hobby]
  initials = Initials
  jot = [Jot]
  language= [Language]
  maiden_name = MaidenName
  mileage = Mileage
  nickname = NickName
  occupation = Occupation
  priority = Priority
  relation = [Relation]
  sensitivity = Sensitivity
  user_defined_field = [UserDefinedField]
  website = [Website]

  name = gdata.data.Name
  phone_number = [gdata.data.PhoneNumber]
  organization = gdata.data.Organization
  postal_address = [gdata.data.PostalAddress]
  email = [gdata.data.Email]
  im = [gdata.data.Im]
  structured_postal_address = [gdata.data.StructuredPostalAddress]
  extended_property = [gdata.data.ExtendedProperty]

  status = Status

class Deleted(atom.core.XmlElement):
  """If present, indicates that this contact has been deleted."""
  _qname = gdata.GDATA_TEMPLATE % 'deleted'

class GroupMembershipInfo(atom.core.XmlElement):
  """
  Identifies the group to which the contact belongs or belonged.
  The group is referenced by its id.
  """

  _qname = CONTACTS_TEMPLATE % 'groupMembershipInfo'

  href = 'href'
  deleted = 'deleted'

class ContactEntry(PersonEntry):
  """A Google Contacts flavor of an Atom Entry."""

  deleted = Deleted
  group_membership_info = [GroupMembershipInfo]
  organization = gdata.data.Organization

  def GetPhotoLink(self):
    for a_link in self.link:
      if a_link.rel == PHOTO_LINK_REL:
        return a_link
    return None

  def GetPhotoEditLink(self):
    for a_link in self.link:
      if a_link.rel == PHOTO_EDIT_LINK_REL:
        return a_link
    return None

class ContactsFeed(gdata.data.BatchFeed):
  """A collection of Contacts."""
  entry = [ContactEntry]

class SystemGroup(atom.core.XmlElement):
  """The contacts systemGroup element.

  When used within a contact group entry, indicates that the group in
  question is one of the predefined system groups."""

  _qname = CONTACTS_TEMPLATE % 'systemGroup'
  id = 'id'

class GroupEntry(gdata.data.BatchEntry):
  """Represents a contact group."""
  extended_property = [gdata.data.ExtendedProperty]
  system_group = SystemGroup

class GroupsFeed(gdata.data.BatchFeed):
  """A Google contact groups feed flavor of an Atom Feed."""
  entry = [GroupEntry]

class ProfileEntry(PersonEntry):
  """A Google Profiles flavor of an Atom Entry."""

def ProfileEntryFromString(xml_string):
  """Converts an XML string into a ProfileEntry object.

  Args:
    xml_string: string The XML describing a Profile entry.

  Returns:
    A ProfileEntry object corresponding to the given XML.
  """
  return atom.core.parse(ProfileEntry, xml_string)

class ProfilesFeed(gdata.data.BatchFeed):
  """A Google Profiles feed flavor of an Atom Feed."""
  _qname = atom.data.ATOM_TEMPLATE % 'feed'
  entry = [ProfileEntry]

def ProfilesFeedFromString(xml_string):
  """Converts an XML string into a ProfilesFeed object.

  Args:
    xml_string: string The XML describing a Profiles feed.

  Returns:
    A ProfilesFeed object corresponding to the given XML.
  """
  return atom.core.parse(ProfilesFeed, xml_string)


text:
namespace Epic
{
	template<class T = float>
	class Degree;

	template<class T = float>
	class Radian;
}

//////////////////////////////////////////////////////////////////////////////

// Conversions
namespace Epic
{
	namespace
	{
		// Convert a degree value to radians
		template<class T>
		constexpr T DegToRad(const T value) noexcept
		{
			return Epic::Pi<T> * value / T(180);
		}

		// Convert a radian value to degrees
		template<class T>
		constexpr T RadToDeg(const T value) noexcept
		{
			return T(180) * value / Epic::Pi<T>;
		}
	}
}

//////////////////////////////////////////////////////////////////////////////

// Radian
template<class T>
class Epic::Radian
{
public:
	using Type = Epic::Radian<T>;
	using value_type = T;

private:
	value_type m_Value;

public:
	Radian() noexcept = default;
	Radian(const Type&) noexcept = default;
	Radian(Type&&) noexcept = default;

	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>
	constexpr Radian(U value) noexcept
		: m_Value(static_cast<T>(value)) { }

	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>
	constexpr Radian(Degree<U> value) noexcept
		: m_Value(Epic::DegToRad(static_cast<T>(value.Value()))) { }

public:
	constexpr T Value() const noexcept
	{
		return m_Value;
	}

	constexpr T Sin() const noexcept
	{
		return static_cast<T>(std::sin(m_Value));
	}

	constexpr T Cos() const noexcept
	{
		return static_cast<T>(std::cos(m_Value));
	}

	constexpr std::pair<T, T> SinCos() const noexcept
	{
		return std::make_pair(Sin(), Cos());
	}

	constexpr T Tan() const noexcept
	{
		return static_cast<T>(std::tan(m_Value));
	}

	Type& Normalize(T min = T(0)) noexcept
	{
		m_Value = std::remainder(m_Value + min, Epic::TwoPi<T>);
		m_Value -= (m_Value < T(0)) ? min - Epic::TwoPi<T> : min;

		return *this;
	}

public:
	static Type NormalOf(Type value, T min = T(0)) noexcept
	{
		return value.Normalize(min);
	}

public:
	constexpr Type operator - () const
	{
		return { -m_Value };
	}

public:
	#pragma region Assignment Operators

	#define CREATE_ASSIGNMENT_OPERATOR(Op)	\
																					\
	Type& operator Op (value_type value) noexcept									\
	{																				\
		m_Value Op std::move(value);												\
		return *this;																\
	}																				\
																					\
	Type& operator Op (Type value) noexcept											\
	{																				\
		m_Value Op value.Value();													\
		return *this;																\
	}																				\
																					\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>		\
	Type& operator Op (Radian<U> value) noexcept									\
	{																				\
		m_Value Op static_cast<T>(value.Value());									\
		return *this;																\
	}																				\
																					\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>		\
	Type& operator Op (Degree<U> value) noexcept									\
	{																				\
		m_Value Op Epic::DegToRad(static_cast<T>(value.Value()));					\
		return *this;																\
	}

	CREATE_ASSIGNMENT_OPERATOR(= );
	CREATE_ASSIGNMENT_OPERATOR(+= );
	CREATE_ASSIGNMENT_OPERATOR(-= );
	CREATE_ASSIGNMENT_OPERATOR(*= );
	CREATE_ASSIGNMENT_OPERATOR(/= );

	#undef CREATE_ASSIGNMENT_OPERATOR

	#pragma endregion

public:
	#pragma region Arithmetic Operators
	#define CREATE_ARITHMETIC_OPERATOR(Op) 	\
																	\
	Type operator Op (value_type value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	Type operator Op (Type value) const noexcept					\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	template<class U>												\
	Type operator Op (Radian<U> value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	template<class U>												\
	Type operator Op (Degree<U> value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	friend Type operator Op (value_type value, Type rad) noexcept	\
	{																\
		Type result{ rad };											\
		result Op= std::move(value);								\
		return result;												\
	}

	CREATE_ARITHMETIC_OPERATOR(+);
	CREATE_ARITHMETIC_OPERATOR(-);
	CREATE_ARITHMETIC_OPERATOR(*);
	CREATE_ARITHMETIC_OPERATOR(/);

	#undef CREATE_ARITHMETIC_OPERATOR
	#pragma endregion

public:
	#pragma region Comparison Operators
	#define CREATE_COMPARISON_OPERATOR(Op)	\
																				\
	constexpr bool operator Op (value_type value) const noexcept				\
	{																			\
		return m_Value Op std::move(value);										\
	}																			\
																				\
	constexpr bool operator Op (Type value) const noexcept						\
	{																			\
		return m_Value Op value.Value();										\
	}																			\
																				\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>	\
	constexpr bool operator Op (Radian<U> value) const noexcept					\
	{																			\
		return m_Value Op static_cast<T>(value.Value());						\
	}

	CREATE_COMPARISON_OPERATOR(< );
	CREATE_COMPARISON_OPERATOR(<= );
	CREATE_COMPARISON_OPERATOR(> );
	CREATE_COMPARISON_OPERATOR(>= );
	CREATE_COMPARISON_OPERATOR(== );
	CREATE_COMPARISON_OPERATOR(!= );

	#undef CREATE_COMPARISON_OPERATOR
	#pragma endregion

public:
	static const Type Zero;
	static const Type QuarterCircle;
	static const Type HalfCircle;
	static const Type ThreeQuarterCircle;
	static const Type Circle;
};

template<class T>
const Epic::Radian<T> Epic::Radian<T>::Zero = T(0);

template<class T>
const Epic::Radian<T> Epic::Radian<T>::QuarterCircle = Epic::HalfPi<T>;

template<class T>
const Epic::Radian<T> Epic::Radian<T>::HalfCircle = Epic::Pi<T>;

template<class T>
const Epic::Radian<T> Epic::Radian<T>::ThreeQuarterCircle = Epic::Pi<T> + Epic::HalfPi<T>;

template<class T>
const Epic::Radian<T> Epic::Radian<T>::Circle = Epic::TwoPi<T>;

//////////////////////////////////////////////////////////////////////////////

// Degree
template<class T>
class Epic::Degree
{
public:
	using Type = Epic::Degree<T>;
	using value_type = T;

private:
	value_type m_Value;

public:
	Degree() noexcept = default;
	Degree(const Type&) noexcept = default;
	Degree(Type&&) noexcept = default;

	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>
	constexpr Degree(U value) noexcept
		: m_Value(static_cast<T>(value)) { }

	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>
	constexpr Degree(Radian<U> value) noexcept
		: m_Value(Epic::RadToDeg(static_cast<T>(value.Value()))) { }

public:
	constexpr T Value() const noexcept
	{
		return m_Value;
	}

	constexpr T Sin() const noexcept
	{
		return static_cast<T>(std::sin(Epic::DegToRad(m_Value)));
	}

	constexpr T Cos() const noexcept
	{
		return static_cast<T>(std::cos(Epic::DegToRad(m_Value)));
	}

	constexpr std::pair<T, T> SinCos() const noexcept
	{
		return std::make_pair(Sin(), Cos());
	}

	constexpr T Tan() const noexcept
	{
		return static_cast<T>(std::tan(Epic::DegToRad(m_Value)));
	}

	Type& Normalize(T min = T(0)) noexcept
	{
		m_Value = std::remainder(m_Value - min, T(360));
		if (m_Value < T(0)) m_Value += T(360);
		m_Value += min;

		return *this;
	}

public:
	static Type NormalOf(Type value, T min = T(0)) noexcept
	{
		return value.Normalize(min);
	}

public:
	constexpr Type operator - () const
	{
		return { -m_Value };
	}

public:
	#pragma region Assignment Operators

	#define CREATE_ASSIGNMENT_OPERATOR(Op)	\
																					\
	Type& operator Op (value_type value) noexcept									\
	{																				\
		m_Value Op std::move(value);												\
		return *this;																\
	}																				\
																					\
	Type& operator Op (Type value) noexcept											\
	{																				\
		m_Value Op value.Value();													\
		return *this;																\
	}																				\
																					\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>		\
	Type& operator Op (Degree<U> value) noexcept									\
	{																				\
		m_Value Op static_cast<T>(value.Value());									\
		return *this;																\
	}																				\
																					\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>		\
	Type& operator Op (Radian<U> value) noexcept									\
	{																				\
		m_Value Op Epic::RadToDeg(static_cast<T>(value.Value()));					\
		return *this;																\
	}

	CREATE_ASSIGNMENT_OPERATOR(= );
	CREATE_ASSIGNMENT_OPERATOR(+= );
	CREATE_ASSIGNMENT_OPERATOR(-= );
	CREATE_ASSIGNMENT_OPERATOR(*= );
	CREATE_ASSIGNMENT_OPERATOR(/= );

	#undef CREATE_ASSIGNMENT_OPERATOR

	#pragma endregion

public:
	#pragma region Arithmetic Operators
	#define CREATE_ARITHMETIC_OPERATOR(Op) 	\
																	\
	Type operator Op (value_type value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	Type operator Op (Type value) const noexcept					\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	template<class U>												\
	Type operator Op (Degree<U> value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	template<class U>												\
	Type operator Op (Radian<U> value) const noexcept				\
	{																\
		Type result{ *this };										\
		result Op= std::move(value);								\
		return result;												\
	}																\
																	\
	friend Type operator Op (value_type value, Type deg) noexcept	\
	{																\
		Type result{ deg };											\
		result Op= std::move(value);								\
		return result;												\
	}

	CREATE_ARITHMETIC_OPERATOR(+);
	CREATE_ARITHMETIC_OPERATOR(-);
	CREATE_ARITHMETIC_OPERATOR(*);
	CREATE_ARITHMETIC_OPERATOR(/);

	#undef CREATE_ARITHMETIC_OPERATOR
	#pragma endregion

public:
	#pragma region Comparison Operators
	#define CREATE_COMPARISON_OPERATOR(Op)	\
																				\
	constexpr bool operator Op (value_type value) const noexcept				\
	{																			\
		return m_Value Op value;												\
	}																			\
																				\
	constexpr bool operator Op (Type value) const noexcept						\
	{																			\
		return m_Value Op value.Value();										\
	}																			\
																				\
	template<class U, typename = std::enable_if_t<std::is_convertible_v<U, T>>>	\
	constexpr bool operator Op (Degree<U> value) const noexcept					\
	{																			\
		return m_Value Op static_cast<T>(value.Value());						\
	}

	CREATE_COMPARISON_OPERATOR(< );
	CREATE_COMPARISON_OPERATOR(<= );
	CREATE_COMPARISON_OPERATOR(> );
	CREATE_COMPARISON_OPERATOR(>= );
	CREATE_COMPARISON_OPERATOR(== );
	CREATE_COMPARISON_OPERATOR(!= );

	#undef CREATE_COMPARISON_OPERATOR
	#pragma endregion

public:
	static const Type Zero;
	static const Type QuarterCircle;
	static const Type HalfCircle;
	static const Type ThreeQuarterCircle;
	static const Type Circle;
};

template<class T>
const Epic::Degree<T> Epic::Degree<T>::Zero = T(0);

template<class T>
const Epic::Degree<T> Epic::Degree<T>::QuarterCircle = T(90);

template<class T>
const Epic::Degree<T> Epic::Degree<T>::HalfCircle = T(180);

template<class T>
const Epic::Degree<T> Epic::Degree<T>::ThreeQuarterCircle = T(270);

template<class T>
const Epic::Degree<T> Epic::Degree<T>::Circle = T(360);

//////////////////////////////////////////////////////////////////////////////

// Comparison Operators
namespace Epic
{
	template<class T, class U>
	inline bool operator < (Degree<T> d, Radian<U> r) { return d < Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator < (Radian<T> r, Degree<U> d) { return r < Radian<T>(std::move(d)); }

	template<class T, class U>
	inline bool operator <= (Degree<T> d, Radian<U> r) { return d <= Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator <= (Radian<T> r, Degree<U> d) { return r <= Radian<T>(std::move(d)); }

	template<class T, class U>
	inline bool operator > (Degree<T> d, Radian<U> r) { return d > Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator > (Radian<T> r, Degree<U> d) { return r > Radian<T>(std::move(d)); }

	template<class T, class U>
	inline bool operator >= (Degree<T> d, Radian<U> r) { return d >= Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator >= (Radian<T> r, Degree<U> d) { return r >= Radian<T>(std::move(d)); }

	template<class T, class U>
	inline bool operator == (Degree<T> d, Radian<U> r) { return d == Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator == (Radian<T> r, Degree<U> d) { return r == Radian<T>(std::move(d)); }

	template<class T, class U>
	inline bool operator != (Degree<T> d, Radian<U> r) { return d != Degree<T>(std::move(r)); }

	template<class T, class U>
	inline bool operator != (Radian<T> r, Degree<U> d) { return r != Radian<T>(std::move(d)); }
}

//////////////////////////////////////////////////////////////////////////////

// Stream Operators
namespace Epic
{
	template<class Char, class Traits, class T>
	inline std::basic_ostream<Char, Traits>& operator << (std::basic_ostream<Char, Traits>& out, Epic::Radian<T> value)
	{
		return (out << value.Value());
	}

	template<class Char, class Traits, class T>
	inline std::basic_istream<Char, Traits>& operator >> (std::basic_istream<Char, Traits>& in, Epic::Radian<T>& value)
	{
		T a;
		in >> a;
		value = a;

		return in;
	}

	template<class Char, class Traits, class T>
	inline std::basic_ostream<Char, Traits>& operator << (std::basic_ostream<Char, Traits>& out, Epic::Degree<T> value)
	{
		return (out << value.Value());
	}

	template<class Char, class Traits, class T>
	inline std::basic_istream<Char, Traits>& operator >> (std::basic_istream<Char, Traits>& in, Epic::Degree<T>& value)
	{
		T a;
		in >> a;
		value = a;

		return in;
	}
}

//////////////////////////////////////////////////////////////////////////////

// Aliases
namespace Epic
{
	using RadianF = Radian<float>;
	using RadianD = Radian<double>;

	using Radianf = RadianF;
	using Radiand = RadianD;

	using DegreeF = Degree<float>;
	using DegreeD = Degree<double>;
	using DegreeI = Degree<int>;
	using DegreeL = Degree<long>;

	using Degreef = DegreeF;
	using Degreed = DegreeD;
	using Degreei = DegreeI;
	using Degreel = DegreeL;
}

//////////////////////////////////////////////////////////////////////////////

// UDLs
namespace Epic
{
	namespace UDL
	{
		constexpr Epic::DegreeF operator "" _deg(unsigned long long value)
		{
			return{ float(value) };
		}

		constexpr Epic::DegreeF operator "" _deg(long double value)
		{
			return{ float(value) };
		}

		constexpr Epic::DegreeD operator "" _degd(unsigned long long value)
		{
			return{ double(value) };
		}

		constexpr Epic::DegreeD operator "" _degd(long double value)
		{
			return{ double(value) };
		}

		constexpr Epic::RadianF operator "" _rad(long double value)
		{
			return{ float(value) };
		}

		constexpr Epic::RadianD operator "" _radd(long double value)
		{
			return{ double(value) };
		}
	}
}

//////////////////////////////////////////////////////////////////////////////

// Trigonometric Function Overloads
namespace std
{
	template<class T>
	constexpr T sin(Epic::Radian<T> value) noexcept
	{
		return value.Sin();
	}

	template<class T>
	constexpr T cos(Epic::Radian<T> value) noexcept
	{
		return value.Cos();
	}

	template<class T>
	constexpr T tan(Epic::Radian<T> value) noexcept
	{
		return value.Tan();
	}

	template<class T>
	constexpr T sin(Epic::Degree<T> value) noexcept
	{
		return value.Sin();
	}

	template<class T>
	constexpr T cos(Epic::Degree<T> value) noexcept
	{
		return value.Cos();
	}

	template<class T>
	constexpr T tan(Epic::Degree<T> value) noexcept
	{
		return value.Tan();
	}
}


text:
layout: example
title: How to add Cognito authentication to a serverless API
short_title: Cognito IAM
date: 2021-02-08 00:00:00
lang: en
index: 1
type: iam-auth
description: In this example we will look at how to add Cognito User Pool authentication to a serverless API using SST. We'll be using the Api and Cognito constructs to create an authenticated API.
short_desc: Authenticating with Cognito User Pool and Identity Pool.
repo: api-auth-cognito
ref: how-to-add-cognito-authentication-to-a-serverless-api
comments_id: how-to-add-cognito-authentication-to-a-serverless-api/2316
---

In this example we will look at how to add [Cognito User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) authentication to a serverless API using [SST]({{ site.sst_github_repo }}).

## Requirements

- Node.js >= 10.15.1
- We'll be using TypeScript
- An [AWS account]({% link _chapters/create-an-aws-account.md %}) with the [AWS CLI configured locally]({% link _chapters/configure-the-aws-cli.md %})

## Create an SST app

{%change%} Let's start by creating an SST app.

```bash
$ npx create-sst@latest --template=minimal/typescript-starter api-auth-cognito
$ cd api-auth-cognito
$ npm install
```

By default, our app will be deployed to an environment (or stage) called `dev` and the `us-east-1` AWS region. This can be changed in the `sst.json` in your project root.

```json
{
  "name": "api-auth-cognito",
  "region": "us-east-1",
  "main": "stacks/index.ts"
}
```

## Project layout

An SST app is made up of two parts.

1. `stacks/` — App Infrastructure

   The code that describes the infrastructure of your serverless app is placed in the `stacks/` directory of your project. SST uses [AWS CDK]({% link _chapters/what-is-aws-cdk.md %}), to create the infrastructure.

2. `services/` — App Code

   The code that's run when your API is invoked is placed in the `services/` directory of your project.

## Setting up the API

Let's start by setting up an API.

{%change%} Replace the `stacks/MyStack.ts` with the following.

```ts
import { Api, Cognito, StackContext } from "@serverless-stack/resources";

export function MyStack({ stack }: StackContext) {
  // Create Api
  const api = new Api(stack, "Api", {
    defaults: {
      authorizer: "iam",
    },
    routes: {
      "GET /private": "functions/private.handler",
      "GET /public": {
        function: "functions/public.handler",
        authorizer: "none",
      },
    },
  });

  // Show the API endpoint and other info in the output
  stack.addOutputs({
    ApiEndpoint: api.url,
  });
}
```

We are creating an API here using the [`Api`]({{ site.docs_url }}/constructs/api) construct. And we are adding two routes to it.

```
GET /private
GET /public
```

By default, all routes have the authorization type `AWS_IAM`. This means the caller of the API needs to have the required IAM permissions. The first is a private endpoint. The second is a public endpoint and its authorization type is overriden to `NONE`.

## Setting up authentication

{%change%} Add this below the `Api` definition in `stacks/MyStack.ts`.

```ts
// Create auth provider
const auth = new Cognito(stack, "Auth", {
  login: ["email"],
});

// Allow authenticated users invoke API
auth.attachPermissionsForAuthUsers(stack, [api]);
```

This creates a [Cognito User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html); a user directory that manages user sign up and login. We've configured the User Pool to allow users to login with their email and password.

This also creates a Cognito Identity Pool which assigns IAM permissions to users. We are allowing only the logged in users to have the permission to call the API.

{%change%} Replace the `stack.addOutputs` call with the following.

```ts
stack.addOutputs({
  ApiEndpoint: api.url,
  UserPoolId: auth.userPoolId,
  IdentityPoolId: auth.cognitoIdentityPoolId,
  UserPoolClientId: auth.userPoolClientId,
});
```

We are going to print out the resources that we created for reference.

## Adding function code

We will create two functions, one for the public route, and one for the private route.

{%change%} Add a `services/functions/public.ts`.

```ts
export async function handler() {
  return {
    statusCode: 200,
    body: "Hello stranger!",
  };
}
```

{%change%} Add a `services/functions/private.ts`.

```ts
export async function handler() {
  return {
    statusCode: 200,
    body: "Hello user!",
  };
}
```

Now let's test our new API.

## Starting your dev environment

{%change%} SST features a [Live Lambda Development]({{ site.docs_url }}/live-lambda-development) environment that allows you to work on your serverless apps live.

```bash
$ npm start
```

The first time you run this command it'll take a couple of minutes to do the following:

1. It'll bootstrap your AWS environment to use CDK.
2. Deploy a debug stack to power the Live Lambda Development environment.
3. Deploy your app, but replace the functions in the `services/` directory with ones that connect to your local client.
4. Start up a local client.

Once complete, you should see something like this.

```
===============
 Deploying app
===============

Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-api-auth-cognito-my-stack: deploying...

 ✅  dev-api-auth-cognito-my-stack

Stack dev-api-auth-cognito-my-stack
  Status: deployed
  Outputs:
    UserPoolClientId: 4fb69je3470cat29p0nfm3t27k
    UserPoolId: us-east-1_e8u3sktE1
    ApiEndpoint: https://12mflx0e8e.execute-api.us-east-1.amazonaws.com
    IdentityPoolId: us-east-1:d01df859-f416-4dc2-90ac-0c6fc272d197
```

The `ApiEndpoint` is the API we just created. Make a note of the `UserPoolClientId`, `UserPoolId`, `IdentityPoolId`; we'll need them later.

Now let's try out our public route. Head over to the following in your browser. Make sure to replace the URL with your API.

```
https://12mflx0e8e.execute-api.us-east-1.amazonaws.com/public
```

You should see the greeting `Hello stranger!`.

And if you try to visit the private route, you will see `{"message":"Forbidden"}`.

```
https://12mflx0e8e.execute-api.us-east-1.amazonaws.com/private
```

## Signing up

Now to visit the private route, we need to create an account in our User Pool. Usually, we'll have our users sign up for an account through our app. But for this example, we'll use the AWS CLI to sign up a user and confirm their account.

Use the following command in your terminal. Replace `--client-id` with `UserPoolClientId` from the `sst start` output above.

```bash
$ aws cognito-idp sign-up \
  --region us-east-1 \
  --client-id 4fb69je3470cat29p0nfm3t27k \
  --username admin@example.com \
  --password Passw0rd!
```

Next we'll verify the user. Replace `--user-pool-id` with `UserPoolId` from the `sst start` output above.

```bash
$ aws cognito-idp admin-confirm-sign-up \
  --region us-east-1 \
  --user-pool-id us-east-1_e8u3sktE1 \
  --username admin@example.com
```

Now we'll make a request to our private API. Typically, we'll be using our app to do this. But just to test, we'll use the [AWS API Gateway Test CLI](https://github.com/AnomalyInnovations/aws-api-gateway-cli-test). This makes an authenticated call to our private API using the credentials of the user we just created.

```bash
$ npx aws-api-gateway-cli-test \
  --username='admin@example.com' \
  --password='Passw0rd!' \
  --user-pool-id='us-east-1_e8u3sktE1' \
  --app-client-id='4fb69je3470cat29p0nfm3t27k' \
  --cognito-region='us-east-1' \
  --identity-pool-id='us-east-1:d01df859-f416-4dc2-90ac-0c6fc272d197' \
  --invoke-url='https://12mflx0e8e.execute-api.us-east-1.amazonaws.com' \
  --api-gateway-region='us-east-1' \
  --path-template='/private' \
  --method='GET'
```

Make sure to set the options with the ones in your `sst start` output.

- `--user-pool-id` => `UserPoolId`
- `--app-client-id` => `UserPoolClientId`
- `--identity-pool-id` => `IdentityPoolId`
- `--invoke-url` => `ApiEndpoint`
- `--cognito-region` and `--api-gateway-region`, the region in your `sst.json`

You should now see.

```bash
{
  status: 200,
  statusText: 'OK',
  data: 'Hello user!'
}
```

The above process might seem fairly tedious. But once we integrate it into our frontend app, we'll be able to use something like [AWS Amplify]({% link _chapters/configure-aws-amplify.md %}) to handle these steps for us.

## Making changes

Let's make a quick change to our private route to print out the caller's user id.

{%change%} Replace `services/functions/private.ts` with the following.

```ts
import { APIGatewayProxyHandlerV2 } from "aws-lambda";

export const handler: APIGatewayProxyHandlerV2 = async (event) => {
  return {
    statusCode: 200,
    body: `Hello ${event.requestContext.authorizer.iam.cognitoIdentity.identityId}!`,
  };
};
```

We are getting the user id from the event object.

If you make the same authenticated request to the `/private` endpoint.

```bash
$ npx aws-api-gateway-cli-test \
  --username='admin@example.com' \
  --password='Passw0rd!' \
  --user-pool-id='us-east-1_e8u3sktE1' \
  --app-client-id='4fb69je3470cat29p0nfm3t27k' \
  --cognito-region='us-east-1' \
  --identity-pool-id='us-east-1:d01df859-f416-4dc2-90ac-0c6fc272d197' \
  --invoke-url='https://12mflx0e8e.execute-api.us-east-1.amazonaws.com' \
  --api-gateway-region='us-east-1' \
  --path-template='/private' \
  --method='GET'
```

You should see the user id.

```bash
{
  status: 200,
  statusText: 'OK',
  data: 'Hello us-east-1:6f4e594d-a6ca-4a24-b99b-760913a70a31!'
}
```

## Deploying your API

Now that our API is tested and ready to go. Let's go ahead and deploy it for our users. You'll recall that we were using a `dev` environment, the one specified in your `sst.json`.

However, we are going to deploy your API again. But to a different environment, called `prod`. This allows us to separate our environments, so when we are working in `dev`, it doesn't break the API for our users.

{%change%} Run the following in your terminal.

```bash
$ npx sst deploy --stage prod
```

A note on these environments. SST is simply deploying the same app twice using two different `stage` names. It prefixes the resources with the stage names to ensure that they don't thrash.

## Cleaning up

Finally, you can remove the resources created in this example using the following command.

```bash
$ npx sst remove
```

And to remove the prod environment.

```bash
$ npx sst remove --stage prod
```

## Conclusion

And that's it! You've got a brand new serverless API authenticated with Cognito. A local development environment, to test and make changes. And it's deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!


text:
import os
import unittest
from pyccoon.pyccoon import Pyccoon
from pyccoon.utils import SourceFile

class FileTest(unittest.TestCase):

    """
    Test case that takes care of initializing Pyccoon and cleaning up after it.
    """

    input_name = "tests.py"
    output_name = "tests.py.html"

    def setUp(self):
        """ Initialize Pyccoon in the same folder as `__file__` and force Pyccoon to run only over\
            specified input file."""

        self.folder = os.path.split(__file__)[0]

        self.input_name = os.path.join(self.folder, self.input_name)
        self.output_name = os.path.join(self.folder, self.output_name)

        self.pyccoon = Pyccoon({
            'sourcedir':    self.folder,
            'outdir':       self.folder,
            'verbosity':    0,
        }, process=False)

        source = os.path.split(self.input_name)[1]
        self.pyccoon.sources = {source: SourceFile(source=source,
                                                   destination=self.output_name,
                                                   process=True)}

    def tearDown(self):
        """ Remove created files and verify they do not exist """
        for sf in self.pyccoon.sources.values():
            os.unlink(sf.destination)
        assert not os.path.exists(self.output_name), "Dummy output file exists after test"

    def check(self, output):
        pass

    def test(self):
        """ The test itself. Starts pyccoon processing and invokes the `check` method """
        self.pyccoon.process()
        with open(self.output_name, "r") as temp:
            output = temp.read()
        self.check(output)

    def shortDescription(self):
        return self.check.__doc__

class DummyFileTest(FileTest):

    """
    Test case specially designed for convenient Pyccoon testing. Subclasses of it override `input`\
    param and `check` method, while everything else takes care of creating and removing temp input\
    and output files for Pyccoon.
    """

    input = ""
    input_name = "__test_input__.py"
    output_name = "__test_input__.py.html"

    def setUp(self):
        """ Additionally to `FileTest.setUp`, fill the input file with `input` data """
        super(DummyFileTest, self).setUp()

        with open(self.input_name, "w") as temp:
            temp.write(self.input)

    def tearDown(self):
        """ Remove created temporary files and verify they do not exist """
        super(DummyFileTest, self).tearDown()

        os.unlink(self.input_name)
        assert not os.path.exists(self.input_name), "Dummy input file exists after test"

    def check(self, output):
        """ DummyFileTest: Check that files exist. This method should be overridden """
        assert os.path.exists(self.input_name), "Dummy input file does not exist before test"
        assert os.path.exists(self.output_name), "Dummy output file does not exist before test"

class PyDocSubstitutions(DummyFileTest):
    input = """# :return:
               # :param something:
               # `:pre:`"""

    def check(self, output):
        self.assertTrue("pydoc-return" in repr(output),
                        "Single word PyDoc expression not converted")
        self.assertTrue("pydoc-param" in repr(output),
                        "Multiple words PyDoc expression not converted")
        self.assertTrue(":pre:" in repr(output), "PyDoc expression in `pre` converted")

class TodoSubstitutions(DummyFileTest):
    input = """# TODO: something
               # `FIXME: something`
               \"""`
               FIXME: not converted
               `\"""
            """

    def check(self, output):
        assert "class=todo" in repr(output), "TODO not converted"
        assert "FIXME: something" in repr(output), "FIXME in `pre` converted"
        # TODO: this one is failing. Will fix after migrating to Mistune markdown parser
        # assert "FIXME: not converted" in repr(output),\
        # "FIXME in multiline `pre` converted"

class Crossref(DummyFileTest):
    input = """ # [[1not_existing.py]]
                # [[tests.py]]
                # [[3not_existing.py#anchor]]
                # [[tests.py#anchor]]
                # [[Not existing named|5not_existing.py]]
                # [[Existing named|tests.py]]
                # [[Not existing named with anchor|7not_existing.py#anchor]]
                # [[Existing named with anchor|tests.py#anchor]]
                Malformed links tests:
                # [[multiline
                # link]]
            """

    def check(self, output):
        validation_list = [
            ['1not_existing.py"',                   "Link to not existing file"],
            ['tests.py.html',                       "Link to existing file"],
            ['3not_existing.py#anchor',             "Link to not existing file with anchor"],
            ['tests.py.html#anchor',                "Link to existing file with anchor"],
            ['Not existing named',              "Named link to not existing file"],
            ['Existing named',                  "Named link to existing file"],
            ['7not_existing.py#anchor',             "Named link to not existing file with anchor"],
            ['Not existing named with anchor',  "Named link to not existing file with anchor"],
            ['tests.py.html#anchor',                "Named link to existing file with anchor"],
            ['Existing named with anchor',          "Named link to existing file with anchor"],
            ['[[multiline',                         "Multiline link processed"],
            ['link]]',                              "Multiline link processed"]
        ]
        for item in validation_list:
            self.assertTrue(item[0] in output, item[1])

class PythonLanguage(FileTest):
    input_name = "python_test_sample.py"
    output_name = input_name + ".html"

    def check(self, output):
        sections = self.pyccoon.sections

        self.assertFalse('for Pyccoon' in sections[0]['docs_text'],
                         "Multiline and inline comment were glued")
        self.assertFalse(sections[0]['code_html'], "There should be no code in the section")

        self.assertFalse('indent-based language' in sections[1]['docs_text'],
                         "Inline comments separated by an empty line were glued")
        self.assertFalse(sections[1]['code_html'], "There should be no code in the section")

        self.assertFalse('indent-based language' in sections[3]['docs_text'],
                         "Preceding comment attributed to the following function")
        self.assertTrue('def purpose' in sections[3]['code_text'],
                        "There should be code in the section")

        self.assertTrue('different features' in sections[3]['code_text'],
                        "Multiline string was mistaken for comment")
        self.assertTrue("The purpose of this test" in sections[3]['docs_text'], "Wrong splitting")

        self.assertTrue('@one_of' in sections[4]['code_text'])
        self.assertTrue('def are_decorators' in sections[4]['code_text'],
                        "Decorator separated from function")
        self.assertTrue('and also the convention' in sections[4]['docs_text'], "Lost docs")

        self.assertTrue('class a_useful_heuristic' in sections[5]['code_text'])
        self.assertTrue('for sections splitting' in sections[5]['docs_text'], "Class lost his docs")

        self.assertTrue('def basically' in sections[6]['code_text'])
        self.assertTrue('a documentation block' in sections[6]['docs_text'],
                        "Function lost its docs")

        self.assertTrue('if its_indentation' in sections[7]['code_text'])
        self.assertTrue('belongs to' in sections[7]['docs_text'], "If lost its docs")

        self.assertTrue('correspondence_of_the' in sections[8]['code_text'])
        self.assertTrue('naturally gives' in sections[8]['docs_text'], "If interior lost his docs")
        self.assertFalse('and_documentation' in sections[8]['code_text'], "Indent splitting broken")

        self.assertFalse(sections[9]['docs_text'], "There are no docs in the last section")

class RubyLanguage(FileTest):
    input_name = "ruby_test_sample.rb"
    output_name = input_name + ".html"

    def check(self, output):
        sections = self.pyccoon.sections
        # from subprocess import call
        # call(["open", os.path.join(self.folder, self.output_name)])
        # print(sections)

        for keyword in ["Title:", "Authors:", "Syntax:", "Example:", "See the documentation"]:
            self.assertTrue(keyword in sections[1]['docs_text'], "Inline comments were not glued")

        self.assertFalse('module' in sections[1]['code_text'],
                         "Scope keyword 'module' did not work")

        self.assertTrue('Render any' in sections[4]['docs_text']
                        and 'def render' in sections[4]['code_text']
                        and 'site = ' not in sections[4]['code_text'], "Wrong section splitting")

        self.assertTrue(sections[11]['code_text'].count('end') == 1,
                        "Indentation splitting does not work")

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


text:
@interface DPLinkingTimeoutSchedule : NSObject

@property (nonatomic) BOOL cleanupFlag;

- (instancetype) initWithTimeout:(float)timeout;

- (void) cleanup;

- (void) onCleanup;
- (void) onTimeout;

@end


text:
KERN=backprop
ALG=backprop

CFLAGS?=-O3 -Wall -Wno-unused-label

SRCS=$(KERN).c local_support.c ../../common/support.c
FILES=$(SRCS) $(KERN).h ../../common/support.h

$(KERN): $(FILES) ../../common/harness.c
	$(CC) $(CFLAGS) -I../../common -o $(KERN) $(SRCS) ../../common/harness.c -lm

run: $(KERN) input.data check.data
	./$(KERN) input.data check.data

generate: $(FILES) generate.c
	$(CC) $(CFLAGS) -I../../common -o generate $(SRCS) generate.c -lm
	./generate

hls: $(KERN).c $(KERN).h
	vivado_hls hls.tcl

clean:
	rm -f $(KERN) generate output.data


text:
@interface FUIconController : NSObject {
    NSImageView *dockTileImageView;
}

+ (FUIconController *)instance;

- (void)setCustomAppIconToFileAtPath:(NSString *)path;

- (void)setDockTileLabel:(NSString *)label;

@property (nonatomic, retain) NSImageView *dockTileImageView;
@end


text:
"""Manila OS API WSGI application."""

import sys

from oslo_config import cfg
from oslo_log import log
from oslo_reports import guru_meditation_report as gmr
from oslo_reports import opts as gmr_opts
from oslo_service import wsgi

# Need to register global_opts
from manila.common import config
from manila import rpc
from manila import service
from manila import version

CONF = cfg.CONF

def initialize_application():
    log.register_options(CONF)
    gmr_opts.set_defaults(CONF)
    CONF(sys.argv[1:], project="manila", version=version.version_string())
    config.verify_share_protocols()
    log.setup(CONF, "manila")

    gmr.TextGuruMeditation.setup_autorun(version, conf=CONF)
    rpc.init(CONF)
    service.setup_profiler("manila-api", CONF.host)
    return wsgi.Loader(CONF).load_app(name='osapi_share')


text:
📚 A Reactive web client for [tldr-pages](https://github.com/tldr-pages/tldr). Try it [here](https://tldr.ostera.io).

If you've found this project useful, you can now [support me on Patreon](https://patreon.com/abstractmachines)

## Featuring

* `Unique URIs`, to easily share any `tldr-page`!
* `Mobile-first-ish`, to take with you anywhere!
* Fully Reactive, embracing `ES6`, `RxJS`, `FlowType` and `React` for great win!

![tldr.ostera.io on desktop and mobile views](https://s3.amazonaws.com/tldr.ostera.io/screenshot.jpg)

## Roadmap

As [tldr-pages](https://github.com/tldr-pages/tldr) advances, new features can be planned. Some are:

* `Autocompletion`, freeing you from remembering all those command names
* `Search`, letting you search through all the pages and commands content to find what you want

See the [issues page](https://github.com/ostera/tldr.jsx/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement) for a list of planned enhancements and features.

## Collaboration Setup

It requires a working `node` environment with `npm`, and `make`.

* `make` to prepare the workspace and do the first build from scratch
* `make build`, for a development build
* `make test`, to run the test suite
* `make lint`, to lint the source
* `make check`, to type-check everything
* `make package`, to create a distributable package

Serve locally as you wish, I prefer [static-server](https://www.npmjs.com/package/static-server).

#### But what about Y or X and File Watchers!

File Watchers never really manage to work the way you want them to, so I ended up using [ostera/watch](https://github.com/ostera/watch) for auto-building, auto-testing, auto-anything.

## License

See [LICENSE](https://github.com/ostera/pry/blob/master/LICENSE).


text:
require 'yaml'
require 'koala'

module Facelink
  module Config
    CONFIG_PATH = '~/.facelink-config.yml'.freeze
    API_VERSION = 'v2.8'.freeze

    module_function

    def config
      @config ||= YAML.load_file(File.expand_path(CONFIG_PATH))
    end

    def configure_koala_facebook_client
      Koala.config.api_version = config['facebook']['api_version'] || API_VERSION
    end

    def create_config_file(access_token, api_version = API_VERSION)
      configuration = { 'facebook' => { 'access_token' => access_token, 'api_version' => api_version } }

      File.open(File.expand_path(CONFIG_PATH), 'w') { |f| f.write configuration.to_yaml }
    end

    def access_token
      config['facebook']['access_token']
    end
  end
end


text:
{# -*- coding: utf-8 -*-

  This file is part of Invenio.
  Copyright (C) 2015-2018 CERN.

  Invenio is free software; you can redistribute it and/or modify it
  under the terms of the MIT License; see LICENSE file for more details.
#}
{%- if breadcrumbs|length > 1 %}

      {%- for breadcrumb in breadcrumbs %}
        {%- if loop.last %}

            {{ breadcrumb.text|safe }}

        {%- else %}

            {{ breadcrumb.text|safe }}

        {%- endif %}
      {%- endfor %}

{%- endif %}


text: MathJax.Localization.addTranslation("ce","HelpDialog",{version:"2.7.2-beta.1",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/ce/HelpDialog.js");


text:
CREATE TABLE `tl_page` (
  `faviconPath` varchar(255) NOT NULL default '',
  `faviconExternal` char(100) NOT NULL default '',
  `appleTouchIconPath` varchar(255) NOT NULL default '',
  `appleTouchIconExternal` char(100) NOT NULL default '',
  PRIMARY KEY  (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


text:
'''Moa
=======

Adapter for moa classes.
'''

from cplcom import config_name


text:
import django.forms as forms
from lib.widgets import DateDropDownInput

class CustomForm(forms.Form):
    """
    Base form to be used by all forms
    """
    form_id = 'form'
    form_action = None
    #submit_buttons = [ forms.SubmitButton('Submit', css_class="btn btn-primary") ]

    def __init__(self, request, *args, **kwargs):
        self.request = request
        # call the superclass
        super().__init__(*args, **kwargs)
        # call the init method
        self.init()

    def init(self):
        # define fields here
        pass

    def commit(self):
        pass

    def as_full(self):
        #prints the form
        pass

class DataStoreForm(CustomForm):
    """
    Form for adding a data store
    """
    def init(self):
        # define fields here
        self.fields['data_store_name-%s' % self.request.get_webid()] = forms.CharField(label="Data Store Name:", widget=forms.TextInput(attrs={'class' : 'form-control'}))
        self.fields['data_store_type-%s' % self.request.get_webid()] = forms.ChoiceField(label="Data Store Type:",
                                                                                choices=(('1',1), ('2',2), ('3',3), ('4',4)),
                                                                                widget = forms.RadioSelect(attrs={'class': 'radio-inline'})) # Fix this portion
        self.fields['data_store_endpoint-%s' % self.request.get_webid()] = forms.CharField(label="Data Endpoint:", widget=forms.TextInput(attrs={'class' : 'form-control'}))
        self.fields['data_api_key-%s' % self.request.get_webid()] = forms.CharField(label="Data Store API Key:", widget=forms.TextInput(attrs={'class' : 'form-control'}))
        self.fields['date-%s' % self.request.get_webid()] = forms.DateField(label="Date:", widget = DateDropDownInput())

    def commit(self):
        # does the work of the form
        pass

    def as_full(self):
        # prints the form
        html = []

        # show hidden fields
        for field in self.hidden_fields():
            html.append('
')
            html.append('%s
' % field.label)

        # show non field errors
        if self.errors:
            print(dir(self.non_field_errors))
            for error in self.errors:
                html.append('
')
                html.append('%s
' % error)

        # start of form header
        html.append('<form id="%s">' % self.request.get_webid())

        # displays field erros or help text if there are field errors
        for field in self.visible_fields():
            print(dir(field))
            html.append('
')
            html.append('%s' % (field.id_for_label, field.label))
            html.append(field.as_widget())
            html.append('
')

            # show field errors
            if field.errors:
                for error in field.errors:
                    html.append('
')
                    html.append('%s
' % error)

            # show help text
            if field.help_text:
                for help_text in field.help_text:
                    html.append('
')
                    html.append('%s
' % help_text)

        # show submit button
        html.append('<input type="submit" class="btn btn-primary">')

        # form footer
        html.append('</form>')
        return '\n'.join(html)

    def add_fields_as_table(self, html, show_labels = True):
        """ Adds the html for all fields of a form """
        # hidden fields
        for field in self.hiddden_fields():
            self.add_field_as_table(html, field, False) # need to add this function
        # visible fields
        for field in self.visible_fields():
            self.add_field_as_table(html, field, show_labels)

    def add_field_as_table(self, html, field, show_labels = True):
        #do stuff here
        pass

    def __str__(self):
        return self.as_full()