text:
module Opaleye.Internal.HaskellDB.Sql.Default  where

import Opaleye.Internal.HaskellDB.PrimQuery
import qualified Opaleye.Internal.HaskellDB.PrimQuery as PQ
import Opaleye.Internal.HaskellDB.PrimQuery (Assoc, PrimExpr)
import Opaleye.Internal.HaskellDB.Sql
import Opaleye.Internal.HaskellDB.Sql.Generate
import qualified Opaleye.Internal.HaskellDB.Sql as Sql
import Opaleye.Internal.Tag (tagWith)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Base16 as Base16

mkSqlGenerator :: SqlGenerator -> SqlGenerator
mkSqlGenerator gen = SqlGenerator
    {
     sqlUpdate      = defaultSqlUpdate      gen,
     sqlDelete      = defaultSqlDelete      gen,
     sqlInsert      = defaultSqlInsert      gen,
     sqlExpr        = defaultSqlExpr        gen,
     sqlLiteral     = defaultSqlLiteral     gen,
     sqlQuote       = defaultSqlQuote       gen
    }

defaultSqlGenerator :: SqlGenerator
defaultSqlGenerator = mkSqlGenerator defaultSqlGenerator

toSqlOrder :: SqlGenerator -> OrderExpr -> (SqlExpr,SqlOrder)
toSqlOrder gen (OrderExpr o e) =
  (sqlExpr gen e, Sql.SqlOrder { sqlOrderDirection = o'
                               , sqlOrderNulls     = orderNulls' })
    where o' = case PQ.orderDirection o of
            PQ.OpAsc  -> Sql.SqlAsc
            PQ.OpDesc -> Sql.SqlDesc
          orderNulls' = case PQ.orderNulls o of
            PQ.NullsFirst -> Sql.SqlNullsFirst
            PQ.NullsLast  -> Sql.SqlNullsLast

toSqlAssoc :: SqlGenerator -> Assoc -> [(SqlColumn,SqlExpr)]
toSqlAssoc gen = map (\(attr,expr) -> (SqlColumn attr, sqlExpr gen expr))

defaultSqlUpdate :: SqlGenerator
                 -> TableName  -- ^ Name of the table to update.
	         -> [PrimExpr] -- ^ Conditions which must all be true for a row
                               --   to be updated.
                 -> Assoc -- ^ Update the data with this.
	         -> SqlUpdate
defaultSqlUpdate gen name criteria assigns
        = SqlUpdate name (toSqlAssoc gen assigns) (map (sqlExpr gen) criteria)

defaultSqlInsert :: SqlGenerator
                 -> TableName -- ^ Name of the table
	         -> Assoc -- ^ What to insert.
	         -> SqlInsert
defaultSqlInsert gen table assoc = SqlInsert table cs es
    where (cs,es) = unzip (toSqlAssoc gen assoc)

defaultSqlDelete :: SqlGenerator
                 -> TableName -- ^ Name of the table
	         -> [PrimExpr] -- ^ Criteria which must all be true for a row
                               --   to be deleted.
	         -> SqlDelete
defaultSqlDelete gen name criteria = SqlDelete name (map (sqlExpr gen) criteria)

defaultSqlExpr :: SqlGenerator -> PrimExpr -> SqlExpr
defaultSqlExpr gen expr =
    case expr of
      AttrExpr (Symbol a t) -> ColumnSqlExpr (SqlColumn (tagWith t a))
      BaseTableAttrExpr a -> ColumnSqlExpr (SqlColumn a)
      BinExpr op e1 e2 ->
        let leftE = sqlExpr gen e1
            rightE = sqlExpr gen e2
            paren = ParensSqlExpr
            (expL, expR) = case (op, e1, e2) of
              (OpAnd, BinExpr OpOr _ _, BinExpr OpOr _ _) ->
                (paren leftE, paren rightE)
              (OpOr, BinExpr OpAnd _ _, BinExpr OpAnd _ _) ->
                (paren leftE, paren rightE)
              (OpAnd, BinExpr OpOr _ _, _) ->
                (paren leftE, rightE)
              (OpAnd, _, BinExpr OpOr _ _) ->
                (leftE, paren rightE)
              (OpOr, BinExpr OpAnd _ _, _) ->
                (paren leftE, rightE)
              (OpOr, _, BinExpr OpAnd _ _) ->
                (leftE, paren rightE)
              (_, ConstExpr _, ConstExpr _) ->
                (leftE, rightE)
              (_, _, ConstExpr _) ->
                (paren leftE, rightE)
              (_, ConstExpr _, _) ->
                (leftE, paren rightE)
              _ -> (paren leftE, paren rightE)
        in BinSqlExpr (showBinOp op) expL expR
      UnExpr op e      -> let (op',t) = sqlUnOp op
                              e' = sqlExpr gen e
                           in case t of
                                UnOpFun     -> FunSqlExpr op' [e']
                                UnOpPrefix  -> PrefixSqlExpr op' (ParensSqlExpr e')
                                UnOpPostfix -> PostfixSqlExpr op' e'
      AggrExpr op e ord -> let op' = showAggrOp op
                               e' = (sqlExpr gen) e
                               ord' = toSqlOrder gen <$> ord
                               moreAggrFunParams = case op of
                                 AggrStringAggr primE -> [(sqlExpr gen) primE]
                                 _ -> []
                            in AggrFunSqlExpr op' (e' : moreAggrFunParams) ord'
      ConstExpr l      -> ConstSqlExpr (sqlLiteral gen l)
      CaseExpr cs e    -> let cs' = [(sqlExpr gen c, sqlExpr gen x)| (c,x) <- cs]
                              e'  = sqlExpr gen e
                           in CaseSqlExpr cs' e'
      ListExpr es      -> ListSqlExpr (map (sqlExpr gen) es)
      ParamExpr n _    -> ParamSqlExpr n PlaceHolderSqlExpr
      FunExpr n exprs  -> FunSqlExpr n (map (sqlExpr gen) exprs)
      CastExpr typ e1 -> CastSqlExpr typ (sqlExpr gen e1)

showBinOp :: BinOp -> String
showBinOp  OpEq         = "="
showBinOp  OpLt         = "<"
showBinOp  OpLtEq       = "<="
showBinOp  OpGt         = ">"
showBinOp  OpGtEq       = ">="
showBinOp  OpNotEq      = "<>"
showBinOp  OpAnd        = "AND"
showBinOp  OpOr         = "OR"
showBinOp  OpLike       = "LIKE"
showBinOp  OpIn         = "IN"
showBinOp  (OpOther s)  = s
showBinOp  OpCat        = "||"
showBinOp  OpPlus       = "+"
showBinOp  OpMinus      = "-"
showBinOp  OpMul        = "*"
showBinOp  OpDiv        = "/"
showBinOp  OpMod        = "MOD"
showBinOp  OpBitNot     = "~"
showBinOp  OpBitAnd     = "&"
showBinOp  OpBitOr      = "|"
showBinOp  OpBitXor     = "^"
showBinOp  OpAsg        = "="

data UnOpType = UnOpFun | UnOpPrefix | UnOpPostfix

sqlUnOp :: UnOp -> (String,UnOpType)
sqlUnOp  OpNot         = ("NOT", UnOpPrefix)
sqlUnOp  OpIsNull      = ("IS NULL", UnOpPostfix)
sqlUnOp  OpIsNotNull   = ("IS NOT NULL", UnOpPostfix)
sqlUnOp  OpLength      = ("LENGTH", UnOpFun)
sqlUnOp  OpAbs         = ("@", UnOpFun)
sqlUnOp  OpNegate      = ("-", UnOpFun)
sqlUnOp  OpLower       = ("LOWER", UnOpFun)
sqlUnOp  OpUpper       = ("UPPER", UnOpFun)
sqlUnOp  (UnOpOther s) = (s, UnOpFun)

showAggrOp :: AggrOp -> String
showAggrOp AggrCount          = "COUNT"
showAggrOp AggrSum            = "SUM"
showAggrOp AggrAvg            = "AVG"
showAggrOp AggrMin            = "MIN"
showAggrOp AggrMax            = "MAX"
showAggrOp AggrStdDev         = "StdDev"
showAggrOp AggrStdDevP        = "StdDevP"
showAggrOp AggrVar            = "Var"
showAggrOp AggrVarP           = "VarP"
showAggrOp AggrBoolAnd        = "BOOL_AND"
showAggrOp AggrBoolOr         = "BOOL_OR"
showAggrOp AggrArr            = "ARRAY_AGG"
showAggrOp (AggrStringAggr _) = "STRING_AGG"
showAggrOp (AggrOther s)      = s

defaultSqlLiteral :: SqlGenerator -> Literal -> String
defaultSqlLiteral _ l =
    case l of
      NullLit       -> "NULL"
      DefaultLit    -> "DEFAULT"
      BoolLit True  -> "TRUE"
      BoolLit False -> "FALSE"
      ByteStringLit s
                    -> binQuote s
      StringLit s   -> quote s
      IntegerLit i  -> show i
      DoubleLit d   -> show d
      OtherLit o    -> o

defaultSqlQuote :: SqlGenerator -> String -> String
defaultSqlQuote _ s = quote s

-- | Quote a string and escape characters that need escaping
--   We use Postgres "escape strings", i.e. strings prefixed
--   with E, to ensure that escaping with backslash is valid.
quote :: String -> String
quote s = "E'" ++ concatMap escape s ++ "'"

-- | Escape characters that need escaping
escape :: Char -> String
escape '\NUL' = "\\0"
escape '\'' = "''"
escape '"' = "\\\""
escape '\b' = "\\b"
escape '\n' = "\\n"
escape '\r' = "\\r"
escape '\t' = "\\t"
escape '\\' = "\\\\"
escape c = [c]

-- | Quote binary literals using Postgresql's hex format.
binQuote :: ByteString -> String
binQuote s = "E'\\\\x" ++ BS8.unpack (Base16.encode s) ++ "'"


text:
uchar psw[8];

// Local function definitions
SMALLINT setPassword(int portnum, uchar *SNum, uchar *setpsw, int type);
SMALLINT verifyPassword(int portnum, uchar *SNum, uchar *psw, int type);
SMALLINT setPasswordMode(int portnum, uchar *SNum, int mode);
void setBMPassword(uchar *pw);

redpajama_set_name: RedPajamaGithub


text:
namespace DomainModel.Enum
{
    public enum TaskStatusEnum
    {
        Alive = 1,
        Checking = 2,
        Dead = 3,
        UnableToFetch = 4
    }
}


text:
'use strict';

var app = angular.module('app', ['appControllers', 'appServices', 'appDirectives', 'appFilters']);
var appControllers = angular.module('appControllers', []);
var appServices = angular.module('appServices', []);
var appDirectives = angular.module('appDirectives', []);
var appFilters = angular.module('appFilters', []);


text:
package freemarker.ext.jsp;

import java.beans.IntrospectionException;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TryCatchFinally;

import freemarker.log.Logger;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;

/**
 */
class TagTransformModel extends JspTagModelBase implements TemplateTransformModel {
    private static final Logger LOG = Logger.getLogger("freemarker.jsp");

    private final boolean isBodyTag;
    private final boolean isIterationTag;
    private final boolean isTryCatchFinally;

    public TagTransformModel(String tagName, Class tagClass) throws IntrospectionException {
        super(tagName, tagClass);
        isIterationTag = IterationTag.class.isAssignableFrom(tagClass);
        isBodyTag = isIterationTag && BodyTag.class.isAssignableFrom(tagClass);
        isTryCatchFinally = TryCatchFinally.class.isAssignableFrom(tagClass);
    }

    public Writer getWriter(Writer out, Map args) throws TemplateModelException {
        try {
            Tag tag = (Tag) getTagInstance();
            FreeMarkerPageContext pageContext = PageContextFactory.getCurrentPageContext();
            Tag parentTag = (Tag) pageContext.peekTopTag(Tag.class);
            tag.setParent(parentTag);
            tag.setPageContext(pageContext);
            setupTag(tag, args, pageContext.getObjectWrapper());
            // If the parent of this writer is not a JspWriter itself, use
            // a little Writer-to-JspWriter adapter...
            boolean usesAdapter;
            if (out instanceof JspWriter) {
                // This is just a sanity check. If it were JDK 1.4-only,
                // we'd use an assert.
                if (out != pageContext.getOut()) {
                    throw new TemplateModelException(
                        "out != pageContext.getOut(). Out is " +
                        out + " pageContext.getOut() is " +
                        pageContext.getOut());
                }
                usesAdapter = false;
            } else {
                out = new JspWriterAdapter(out);
                pageContext.pushWriter((JspWriter) out);
                usesAdapter = true;
            }
            JspWriter w = new TagWriter(out, tag, pageContext, usesAdapter);
            pageContext.pushTopTag(tag);
            pageContext.pushWriter(w);
            return w;
        } catch (Exception e) {
            throw toTemplateModelExceptionOrRethrow(e);
        }
    }

    /**
     * An implementation of BodyContent that buffers it's input to a char[].
     */
    static class BodyContentImpl extends BodyContent {
        private CharArrayWriter buf;

        BodyContentImpl(JspWriter out, boolean buffer) {
            super(out);
            if (buffer) initBuffer();
        }

        void initBuffer() {
            buf = new CharArrayWriter();
        }

        @Override
        public void flush() throws IOException {
            if (buf == null) {
                getEnclosingWriter().flush();
            }
        }

        @Override
        public void clear() throws IOException {
            if (buf != null) {
                buf = new CharArrayWriter();
            } else {
                throw new IOException("Can't clear");
            }
        }

        @Override
        public void clearBuffer() throws IOException {
            if (buf != null) {
                buf = new CharArrayWriter();
            } else {
                throw new IOException("Can't clear");
            }
        }

        @Override
        public int getRemaining() {
            return Integer.MAX_VALUE;
        }

        @Override
        public void newLine() throws IOException {
            write(JspWriterAdapter.NEWLINE);
        }

        @Override
        public void close() throws IOException {
        }

        @Override
        public void print(boolean arg0) throws IOException {
            write(arg0 ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
        }

        @Override
        public void print(char arg0) throws IOException {
            write(arg0);
        }

        @Override
        public void print(char[] arg0) throws IOException {
            write(arg0);
        }

        @Override
        public void print(double arg0) throws IOException {
            write(Double.toString(arg0));
        }

        @Override
        public void print(float arg0) throws IOException {
            write(Float.toString(arg0));
        }

        @Override
        public void print(int arg0) throws IOException {
            write(Integer.toString(arg0));
        }

        @Override
        public void print(long arg0) throws IOException {
            write(Long.toString(arg0));
        }

        @Override
        public void print(Object arg0) throws IOException {
            write(arg0 == null ? "null" : arg0.toString());
        }

        @Override
        public void print(String arg0) throws IOException {
            write(arg0);
        }

        @Override
        public void println() throws IOException {
            newLine();
        }

        @Override
        public void println(boolean arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(char arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(char[] arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(double arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(float arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(int arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(long arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(Object arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void println(String arg0) throws IOException {
            print(arg0);
            newLine();
        }

        @Override
        public void write(int c) throws IOException {
            if (buf != null) {
                buf.write(c);
            } else {
                getEnclosingWriter().write(c);
            }
        }

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            if (buf != null) {
                buf.write(cbuf, off, len);
            } else {
                getEnclosingWriter().write(cbuf, off, len);
            }
        }

        @Override
        public String getString() {
            return buf.toString();
        }

        @Override
        public Reader getReader() {
            return new CharArrayReader(buf.toCharArray());
        }

        @Override
        public void writeOut(Writer out) throws IOException {
            buf.writeTo(out);
        }

    }

    class TagWriter extends BodyContentImpl implements TransformControl {
        private final Tag tag;
        private final FreeMarkerPageContext pageContext;
        private boolean needPop = true;
        private final boolean needDoublePop;

        TagWriter(Writer out, Tag tag, FreeMarkerPageContext pageContext, boolean needDoublePop) {
            super((JspWriter) out, false);
            this.needDoublePop = needDoublePop;
            this.tag = tag;
            this.pageContext = pageContext;
        }

        @Override
        public String toString() {
            return "TagWriter for " + tag.getClass().getName() + " wrapping a " + getEnclosingWriter().toString();
        }

        Tag getTag() {
            return tag;
        }

        FreeMarkerPageContext getPageContext() {
            return pageContext;
        }

        public int onStart()
        throws TemplateModelException {
            try {
                int dst = tag.doStartTag();
                switch(dst) {
                    case Tag.SKIP_BODY:
                    // EVAL_PAGE is illegal actually, but some taglibs out there
                    // use it, and it seems most JSP compilers allow them to and
                    // treat it identically to SKIP_BODY, so we're going with
                    // the flow and we allow it too, altough strictly speaking
                    // it's in violation of the spec.
                    case Tag.EVAL_PAGE: {
                        endEvaluation();
                        return TransformControl.SKIP_BODY;
                    }
                    case BodyTag.EVAL_BODY_BUFFERED: {
                        if (isBodyTag) {
                            initBuffer();
                            BodyTag btag = (BodyTag) tag;
                            btag.setBodyContent(this);
                            btag.doInitBody();
                        } else {
                            throw new TemplateModelException("Can't buffer body since " + tag.getClass().getName() + " does not implement BodyTag.");
                        }
                        // Intentional fall-through
                    }
                    case Tag.EVAL_BODY_INCLUDE: {
                        return TransformControl.EVALUATE_BODY;
                    }
                    default: {
                        throw new RuntimeException("Illegal return value " + dst + " from " + tag.getClass().getName() + ".doStartTag()");
                    }
                }
            } catch (Exception e) {
                throw toTemplateModelExceptionOrRethrow(e);
            }
        }

        public int afterBody()
        throws TemplateModelException {
            try {
                if (isIterationTag) {
                    int dab = ((IterationTag) tag).doAfterBody();
                    switch(dab) {
                        case Tag.SKIP_BODY:
                            endEvaluation();
                            return END_EVALUATION;
                        case IterationTag.EVAL_BODY_AGAIN:
                            return REPEAT_EVALUATION;
                        default:
                            throw new TemplateModelException("Unexpected return value " + dab + "from " + tag.getClass().getName() + ".doAfterBody()");
                    }
                }
                endEvaluation();
                return END_EVALUATION;
            } catch (Exception e) {
                throw toTemplateModelExceptionOrRethrow(e);
            }
        }

        private void endEvaluation() throws JspException {
            if (needPop) {
                pageContext.popWriter();
                needPop = false;
            }
            if (tag.doEndTag() == Tag.SKIP_PAGE) {
                LOG.warn("Tag.SKIP_PAGE was ignored from a " + tag.getClass().getName() + " tag.");
            }
        }

        public void onError(Throwable t) throws Throwable {
            if (isTryCatchFinally) {
                ((TryCatchFinally) tag).doCatch(t);
            } else {
                throw t;
            }
        }

        @Override
        public void close() {
            if (needPop) {
                pageContext.popWriter();
            }
            pageContext.popTopTag();
            try {
                if (isTryCatchFinally) {
                    ((TryCatchFinally) tag).doFinally();
                }
                // No pooling yet
                tag.release();
            } finally {
                if (needDoublePop) {
                    pageContext.popWriter();
                }
            }
        }

    }
}


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

using LibNLPCSharp.util;
using LibNLPCSharp.simpletokenizing;

using LibHTreeProcessing.src.simplexml;
using LibHTreeProcessing.src.treesearch;
using LibHTreeProcessing.src.transformation2.impl;

namespace LibHTreeProcessing.src.transformation2.selectors
{

	public class SelectSingleText_ParserComponent : AbstractSelectorParserComponent
	{

		////////////////////////////////////////////////////////////////
		// Constants
		////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////
		// Variables
		////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////
		// Constructors
		////////////////////////////////////////////////////////////////

		public SelectSingleText_ParserComponent()
		{
		}

		////////////////////////////////////////////////////////////////
		// Properties
		////////////////////////////////////////////////////////////////

		public override string[] ShortHelp
		{
			get {
				return new string[] {
					"select single text chunk \"/pathexpr\""
				};
			}
		}

		public override string[] LongHelpText
		{
			get {
				return new string[] {
					"This selector will select a single text chunk according to the path specified."
				};
			}
		}

		public override EnumDataType[] OutputDataTypes
		{
			get {
				return new EnumDataType[] {
					EnumDataType.SingleText
				};
			}
		}

		////////////////////////////////////////////////////////////////
		// Methods
		////////////////////////////////////////////////////////////////

		public override AbstractSelector TryParse(IParsingContext ctx, TokenStream tokens)
		{
			int lineNo = tokens.LineNumber;

			Token[] tokensMatched;

			if ((tokensMatched = tokens.TryEatSequence(
				TokenPattern.MatchWord("select"),
				TokenPattern.MatchWord("single"),
				TokenPattern.MatchWord("text"),
				TokenPattern.MatchWord("chunk"),
				TokenPattern.MatchAnyStringDQ()
				)) == null)
				return null;

			return new SelectSingleText_Selector(
				lineNo,
				ParsingUtils.ParseExpression(tokensMatched[4].Text, tokensMatched[4].LineNumber, false)
				);
		}

	}

}


text:
using System;
using JetBrains.Annotations;

namespace JetBrains.Annotations {
    public class ThreadSafeAttribute : Attribute {}
    public class ReadOnlyAttribute   : Attribute {}
}

[ThreadSafe] public class Safe     {}
[ReadOnly]   public class ReadOnly {}
             public class NonSafe  {}

[ThreadSafe]
public class Fields {
    private Safe mutable1;

    private readonly Safe readonly1;
    private readonly ReadOnly readonly2;
    private readonly NonSafe readonly3;

    private static Safe staticMutable1;

    private readonly static Safe staticReadOnly1;
    private readonly static ReadOnly staticReadOnly2;
    private readonly static NonSafe staticReadOnly3;
}


text:
package ec.app.edge.func;
import ec.*;
import ec.app.edge.*;
import ec.gp.*;
import ec.util.*;

/*
 * Split.java
 *
 * Created: Wed Nov  3 18:26:37 1999
 * By: Sean Luke
 */

/**
 * @author Sean Luke
 * @version 1.0
 */

public class Split extends GPNode
    {
    public String toString() { return "split"; }

    /*
      public void checkConstraints(final EvolutionState state,
      final int tree,
      final GPIndividual typicalIndividual,
      final Parameter individualBase)
      {
      super.checkConstraints(state,tree,typicalIndividual,individualBase);
      if (children.length!=2)
      state.output.error("Incorrect number of children for node " +
      toStringForError() + " at " +
      individualBase);
      }
    */
    public int expectedChildren() { return 2; }

    public void eval(final EvolutionState state,
        final int thread,
        final GPData input,
        final ADFStack stack,
        final GPIndividual individual,
        final Problem problem)
        {
        int edge = ((EdgeData)(input)).edge;
        Edge prob = (Edge)problem;

        if (prob.from.length==prob.numEdges)  // we're full, need to expand
            {
            int[] from_ = new int[prob.numEdges*2];
            int[] to_ = new int[prob.numEdges*2];
            int[] reading_ = new int[prob.numEdges*2];
            System.arraycopy(prob.from,0,from_,0,prob.from.length);
            System.arraycopy(prob.to,0,to_,0,prob.to.length);
            System.arraycopy(prob.reading,0,reading_,0,prob.reading.length);
            prob.from = from_;
            prob.to = to_;
            prob.reading = reading_;
            }

        if (prob.start.length==prob.numNodes)  // we're full, need to expand
            {
            boolean[] start_ = new boolean[prob.numNodes*2];
            boolean[] accept_ = new boolean[prob.numNodes*2];
            System.arraycopy(prob.start,0,start_,0,prob.start.length);
            System.arraycopy(prob.accept,0,accept_,0,prob.accept.length);
            prob.start = start_;
            prob.accept = accept_;
            }

        int newedge = prob.numEdges;
        prob.numEdges++;
        int newnode = prob.numNodes;
        prob.numNodes++;

        // set up new node
        prob.accept[newnode] = false;
        prob.start[newnode] = false;

        // set up new edge
        prob.from[newedge] = newnode;
        prob.to[newedge] = prob.to[edge];
        prob.reading[newedge] = prob.reading[edge];
        // modify old edge
        prob.to[edge] = newnode;

        // pass the original edge down the left child

        children[0].eval(state,thread,input,stack,individual,problem);

        // reset input for right child
        ((EdgeData)(input)).edge = newedge;

        // pass the new edge down the right child

        children[1].eval(state,thread,input,stack,individual,problem);
        }
    }


text:
<?php
class block_chemaxonblock extends block_base {
  public function init() {
    $this->title = get_string('chemaxonblock', 'block_chemaxonblock');
    }
  public function get_content() {
    if ($this->content !== null) {
      return $this->content;
    }

    $this->content       = new stdClass;
    $this->content->text = 'The content goes here';
    $this->content->footer = 'Footer goes here';

    return $this->content;
  }
}


text:
using System.Drawing;

namespace Gwen.Skin.Texturing
{
    public struct SubRect
    {
        public float[] uv;
    }

    /// <summary>
    /// 3x3 texture grid.
    /// </summary>
    public struct Bordered
    {
        private Texture texture;

        private readonly SubRect[] rects;

        private Margin margin;

        private float width;
        private float height;

        public Bordered(Texture texture, float x, float y, float w, float h, Margin inMargin, float drawMarginScale = 1.0f)
            : this()
        {
            rects = new SubRect[9];
            for (int i = 0; i < rects.Length; i++)
            {
                rects[i].uv = new float[4];
            }

            init(texture, x, y, w, h, inMargin, drawMarginScale);
        }

        private void drawRect(Renderer.RendererBase render, int i, int x, int y, int w, int h)
        {
            render.DrawTexturedRect(texture,
                                    new Rectangle(x, y, w, h),
                                    rects[i].uv[0], rects[i].uv[1], rects[i].uv[2], rects[i].uv[3]);
        }

        private void setRect(int num, float x, float y, float w, float h)
        {
            float texw = texture.Width;
            float texh = texture.Height;

            //x -= 1.0f;
            //y -= 1.0f;

            rects[num].uv[0] = x / texw;
            rects[num].uv[1] = y / texh;

            rects[num].uv[2] = (x + w) / texw;
            rects[num].uv[3] = (y + h) / texh;

            //	rects[num].uv[0] += 1.0f / m_Texture->width;
            //	rects[num].uv[1] += 1.0f / m_Texture->width;
        }

        private void init(Texture texture, float x, float y, float w, float h, Margin inMargin, float drawMarginScale = 1.0f)
        {
            this.texture = texture;

            margin = inMargin;

            setRect(0, x, y, margin.Left, margin.Top);
            setRect(1, x + margin.Left, y, w - margin.Left - margin.Right, margin.Top);
            setRect(2, (x + w) - margin.Right, y, margin.Right, margin.Top);

            setRect(3, x, y + margin.Top, margin.Left, h - margin.Top - margin.Bottom);
            setRect(4, x + margin.Left, y + margin.Top, w - margin.Left - margin.Right,
                    h - margin.Top - margin.Bottom);
            setRect(5, (x + w) - margin.Right, y + margin.Top, margin.Right, h - margin.Top - margin.Bottom - 1);

            setRect(6, x, (y + h) - margin.Bottom, margin.Left, margin.Bottom);
            setRect(7, x + margin.Left, (y + h) - margin.Bottom, w - margin.Left - margin.Right, margin.Bottom);
            setRect(8, (x + w) - margin.Right, (y + h) - margin.Bottom, margin.Right, margin.Bottom);

            margin.Left = (int)(margin.Left * drawMarginScale);
            margin.Right = (int)(margin.Right * drawMarginScale);
            margin.Top = (int)(margin.Top * drawMarginScale);
            margin.Bottom = (int)(margin.Bottom * drawMarginScale);

            width = w - x;
            height = h - y;
        }

        // can't have this as default param
        public void Draw(Renderer.RendererBase render, Rectangle r)
        {
            Draw(render, r, Color.White);
        }

        public void Draw(Renderer.RendererBase render, Rectangle r, Color col)
        {
            if (texture == null)
                return;

            render.DrawColor = col;

            if (r.Width < width && r.Height < height)
            {
                render.DrawTexturedRect(texture, r, rects[0].uv[0], rects[0].uv[1], rects[8].uv[2], rects[8].uv[3]);
                return;
            }

            drawRect(render, 0, r.X, r.Y, margin.Left, margin.Top);
            drawRect(render, 1, r.X + margin.Left, r.Y, r.Width - margin.Left - margin.Right, margin.Top);
            drawRect(render, 2, (r.X + r.Width) - margin.Right, r.Y, margin.Right, margin.Top);

            drawRect(render, 3, r.X, r.Y + margin.Top, margin.Left, r.Height - margin.Top - margin.Bottom);
            drawRect(render, 4, r.X + margin.Left, r.Y + margin.Top, r.Width - margin.Left - margin.Right,
                     r.Height - margin.Top - margin.Bottom);
            drawRect(render, 5, (r.X + r.Width) - margin.Right, r.Y + margin.Top, margin.Right,
                     r.Height - margin.Top - margin.Bottom);

            drawRect(render, 6, r.X, (r.Y + r.Height) - margin.Bottom, margin.Left, margin.Bottom);
            drawRect(render, 7, r.X + margin.Left, (r.Y + r.Height) - margin.Bottom,
                     r.Width - margin.Left - margin.Right, margin.Bottom);
            drawRect(render, 8, (r.X + r.Width) - margin.Right, (r.Y + r.Height) - margin.Bottom, margin.Right,
                     margin.Bottom);
        }
    }
}


text:
package org.apache.airavata.gfac.core;

public interface SecurityContext {

}


text:
{-# LANGUAGE TemplateHaskell #-}

module Console.AppState
  ( Name
  , AsyncEvent (..)
  , Phase (..)
  , AppState (..)
  , GameOptions (..)
  , PlayerType (..)
  , gameState
  , phase
  , logMessages
  , startState
  , gameOptions
  , blackPlayer
  , whitePlayer
  , chan
  , selectionStatus
  , humanCounter
  ) where

import           GameState (GameState)
import           Moves (SimpleMoves, startMovesBlack, exportMoves)
import           Board (Coord)
import           Engine (startGame)
import           AI.Dispatch

import           Brick.BChan (BChan)

import           Control.Lens (makeLenses)
import Control.Concurrent.Async

-------------------------------------------------------------------------------

data PlayerType = Human | AI AIType
  deriving Show

data GameOptions = GameOptions
  { _blackPlayer :: PlayerType
  , _whitePlayer :: PlayerType
  , _recordGame :: Bool
  } deriving Show
makeLenses ''GameOptions

type Name = ()

data AsyncEvent
  = SelectionStatus String
  | Log String

data Phase
  = View SimpleMoves
  | ChoosePiece SimpleMoves
  | ChooseMove Coord [Coord]
  | GameOver String
  | Wait
  | End
  deriving (Show)

data AppState = AppState
  { _gameState :: GameState
  , _gameOptions :: GameOptions
  , _phase :: Phase
  , _logMessages :: [String]
  , _chan :: BChan AsyncEvent
  , _selectionStatus :: String
  , _humanCounter :: Maybe (Async ())
  }
makeLenses ''AppState

startState :: GameOptions -> BChan AsyncEvent -> AppState
startState o c = AppState startGame o (ChoosePiece $ exportMoves startMovesBlack) ["The game is afoot!"] c "" Nothing

-------------------------------------------------------------------------------
-- Options


text:
import unittest
import datetime
import recurly
from six import iterkeys
from six.moves import filter
from dateutil.relativedelta import relativedelta
from recurly.errors import BadRequestError

recurly.API_KEY = 'blah'

import mocurly.core
import mocurly.endpoints
import mocurly.backend

class TestSubscriptions(unittest.TestCase):
    def setUp(self):
        self.mocurly_ = mocurly.core.mocurly()
        self.mocurly_.start()

        self.base_address_data = {
                'address1': '123 Jackson St.',
                'address2': 'Data City',
                'state': 'CA',
                'zip': '94105'
            }
        self.base_billing_info_data = {
                'uuid': 'blah',
                'first_name': 'Foo',
                'last_name': 'Bar'
            }
        self.base_account_data = {
                'uuid': 'blah',
                'account_code': 'blah',
                'email': 'foo@bar.com',
                'first_name': 'Foo',
                'last_name': 'Bar',
                'address': self.base_address_data,
                'hosted_login_token': 'abcd1234',
                'created_at': '2014-08-11'
            }
        mocurly.backend.accounts_backend.add_object(self.base_account_data['uuid'], self.base_account_data)
        mocurly.backend.billing_info_backend.add_object(self.base_billing_info_data['uuid'], self.base_billing_info_data)

        self.base_plan_data = {
                'plan_code': 'gold',
                'name': 'Gold Plan',
                'unit_amount_in_cents': recurly.Money(USD=1000, EUR=800)
            }
        self.base_backed_plan_data = self.base_plan_data.copy()
        self.base_backed_plan_data['uuid'] = self.base_plan_data['plan_code']
        self.base_backed_plan_data['unit_amount_in_cents'] = {u'USD': u'1000', u'EUR': u'800'}
        self.base_backed_plan_data['display_quantity'] = False
        self.base_backed_plan_data['trial_interval_length'] = 0
        self.base_backed_plan_data['plan_interval_unit'] = 'months'
        self.base_backed_plan_data['created_at'] = '2014-08-20'
        self.base_backed_plan_data['tax_exempt'] = False
        self.base_backed_plan_data['trial_interval_unit'] = 'months'
        self.base_backed_plan_data['plan_interval_length'] = 1

        self.base_subscription_data = {
                'plan_code': 'gold',
                'account': recurly.Account(account_code=self.base_account_data['account_code']),
                'currency': 'USD'
            }

        self.base_add_on_backed_data = [
                {
                    'add_on_code': 'foo',
                    'name': 'Foo',
                    'plan': self.base_backed_plan_data['plan_code'],
                    'accounting_code': 'foo',
                    'unit_amount_in_cents': {'USD': 1000},
                    'created_at': '2014-08-20',
                },
                {
                    'add_on_code': 'bar',
                    'name': 'Bar',
                    'plan': self.base_backed_plan_data['plan_code'],
                    'accounting_code': 'bar',
                    'unit_amount_in_cents': {'USD': 80},
                    'created_at': '2014-08-20',
                }
            ]
        self.base_add_on_data = [
                {
                    'add_on_code': 'foo',
                    'unit_amount_in_cents': {'USD': 1000}
                },
                {
                    'add_on_code': 'bar',
                    'unit_amount_in_cents': {'USD': 80}
                }
            ]

    def tearDown(self):
        self.mocurly_.stop()

    def test_simple_plan_add_on_creation(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)

        self.assertEqual(len(mocurly.backend.plan_add_ons_backend.datastore), 0)

        # now create some addons
        plan = recurly.Plan.get(self.base_backed_plan_data['plan_code'])
        for add_on in self.base_add_on_data:
            add_on['name'] = add_on['add_on_code'].upper()
            add_on['unit_amount_in_cents'] = recurly.Money(**add_on['unit_amount_in_cents'])
            plan.create_add_on(recurly.AddOn(**add_on))

        self.assertEqual(len(mocurly.backend.plan_add_ons_backend.datastore), 2)
        foo_add_on_backed = mocurly.backend.plan_add_ons_backend.get_object(self.base_backed_plan_data['plan_code'] + '__foo')
        add_ons = filter(lambda add_on: add_on['add_on_code'] == 'foo', self.base_add_on_data)
        foo_add_on = next(add_ons)
        for k, v in foo_add_on.items():
            if k == 'unit_amount_in_cents':
                self.assertEqual(foo_add_on_backed[k], dict((curr, str(amt)) for curr, amt in v.currencies.items()))
            else:
                self.assertEqual(foo_add_on_backed[k], v)

        bar_add_on_backed = mocurly.backend.plan_add_ons_backend.get_object(self.base_backed_plan_data['plan_code'] + '__bar')
        add_ons = filter(lambda add_on: add_on['add_on_code'] == 'bar', self.base_add_on_data)
        bar_add_on = next(add_ons)
        for k, v in bar_add_on.items():
            if k == 'unit_amount_in_cents':
                self.assertEqual(bar_add_on_backed[k], dict((curr, str(amt)) for curr, amt in v.currencies.items()))
            else:
                self.assertEqual(bar_add_on_backed[k], v)

        # make sure foreign keys are linked properly
        self.assertEqual(len(plan.add_ons()), 2)

    def test_simple_plan_creation(self):
        self.assertEqual(len(mocurly.backend.plans_backend.datastore), 0)

        new_plan = recurly.Plan(**self.base_plan_data)
        new_plan.save()

        self.assertEqual(len(mocurly.backend.plans_backend.datastore), 1)
        new_plan_backed = mocurly.backend.plans_backend.get_object(new_plan.plan_code)
        for k, v in self.base_plan_data.items():
            if k == 'unit_amount_in_cents':
                self.assertEqual(new_plan_backed[k], dict((curr, str(amt)) for curr, amt in v.currencies.items()))
            else:
                self.assertEqual(new_plan_backed[k], v)

    def test_plan_deletion(self):
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        self.assertEqual(len(mocurly.backend.plans_backend.datastore), 1)
        recurly.Plan.get(self.base_backed_plan_data['plan_code']).delete()
        self.assertEqual(len(mocurly.backend.plans_backend.datastore), 0)

    def test_simple_subscription_creation(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 0)

        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 1)

        # Make sure a new transaction and invoice was created with it
        invoice = new_subscription.invoice()
        self.assertEqual(
            invoice.line_items[0].start_date.date(),
            datetime.datetime.utcnow().date())
        self.assertEqual(
            invoice.line_items[0].end_date.date(),
            (datetime.datetime.utcnow() + relativedelta(months=1)).date())
        transactions = invoice.transactions
        self.assertEqual(len(transactions), 1)
        self.assertEqual(transactions[0].subscription().uuid, new_subscription.uuid)

        # Make sure we can reference the subscription from the account
        account = new_subscription.account()
        account_subscriptions = account.subscriptions()
        self.assertEqual(len(account_subscriptions), 1)
        self.assertEqual(account_subscriptions[0].uuid, new_subscription.uuid)

    def test_trial_subscription_creation(self):
        # add a sample plan to the plans backend
        self.base_backed_plan_data['trial_interval_length'] = 1
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 0)

        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 1)

        # Make sure a new transaction and invoice was created with it
        invoice = new_subscription.invoice()
        self.assertEqual(
            invoice.line_items[0].start_date.date(),
            datetime.datetime.utcnow().date())
        self.assertEqual(
            invoice.line_items[0].end_date.date(),
            (datetime.datetime.utcnow() + relativedelta(months=1)).date())
        transactions = invoice.transactions
        self.assertEqual(len(transactions), 1)
        self.assertEqual(transactions[0].subscription().uuid, new_subscription.uuid)

        # Make sure we can reference the subscription from the account
        account = new_subscription.account()
        account_subscriptions = account.subscriptions()
        self.assertEqual(len(account_subscriptions), 1)
        self.assertEqual(account_subscriptions[0].uuid, new_subscription.uuid)
        self.assertEqual(account_subscriptions[0].state, 'active')

    def test_trial_override_subscription_creation(self):
        # add a sample plan to the plans backend
        self.base_backed_plan_data['trial_interval_length'] = 1
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 0)

        # Make the trial immediately expire
        self.base_subscription_data['trial_ends_at'] = datetime.datetime.utcnow()
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 1)

        # Make sure a new transaction and invoice was created with it
        invoice = new_subscription.invoice()
        # The invoice should not contain 0 (trial cost) but the actual cost of the subscription since the trial has expired immediately
        self.assertNotEqual(invoice.total_in_cents, 0)

        transactions = invoice.transactions
        self.assertEqual(len(transactions), 1)
        self.assertEqual(transactions[0].subscription().uuid, new_subscription.uuid)

        # Make sure we can reference the subscription from the account
        account = new_subscription.account()
        account_subscriptions = account.subscriptions()
        self.assertEqual(len(account_subscriptions), 1)
        self.assertEqual(account_subscriptions[0].uuid, new_subscription.uuid)
        self.assertEqual(account_subscriptions[0].state, 'active')

    def test_subscriptions_with_addons(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add some add ons to the backend
        for add_on in self.base_add_on_backed_data:
            uuid = mocurly.endpoints.PlansEndpoint().generate_plan_add_on_uuid(self.base_backed_plan_data['plan_code'], add_on['add_on_code'])
            mocurly.backend.plan_add_ons_backend.add_object(uuid, add_on)

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 0)

        self.base_subscription_data['subscription_add_ons'] = [recurly.SubscriptionAddOn(add_on_code=addon['add_on_code'], quantity=1) for addon in self.base_add_on_data]
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()

        self.assertEqual(len(mocurly.backend.subscriptions_backend.datastore), 1)

    def test_subscription_filtering(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add multiple subscriptions in different states
        self.base_subscription_data['uuid'] = 'foo'
        self.base_subscription_data['account'] = self.base_account_data['account_code']
        self.base_subscription_data['state'] = 'active'
        mocurly.backend.subscriptions_backend.add_object('foo', self.base_subscription_data)
        self.base_subscription_data['uuid'] = 'bar'
        self.base_subscription_data['state'] = 'future'
        mocurly.backend.subscriptions_backend.add_object('bar', self.base_subscription_data)
        for i in range(5):
            self.base_subscription_data['uuid'] = str(i)
            self.base_subscription_data['state'] = 'expired'
            mocurly.backend.subscriptions_backend.add_object(str(i), self.base_subscription_data)

        account = recurly.Account.get(self.base_account_data['account_code'])
        active_subscriptions = account.subscriptions(state='active')
        self.assertEqual(len(active_subscriptions), 1)
        self.assertEqual(active_subscriptions[0].uuid, 'foo')

        future_subscriptions = account.subscriptions(state='future')
        self.assertEqual(len(future_subscriptions), 1)
        self.assertEqual(future_subscriptions[0].uuid, 'bar')

        live_subscriptions = account.subscriptions(state='live')
        self.assertEqual(len(live_subscriptions), 2)
        self.assertEqual(set(['foo', 'bar']), set([sub.uuid for sub in live_subscriptions]))

        expired_subscriptions = account.subscriptions(state='expired')
        self.assertEqual(len(expired_subscriptions), 5)
        self.assertEqual(set(range(5)), set([int(sub.uuid) for sub in expired_subscriptions]))

    def test_subscription_termination_full_refund(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add an active subscription
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()
        self.assertEqual(new_subscription.state, 'active')

        # Now terminate it with a full refund
        new_subscription.terminate(refund='full')

        self.assertEqual(new_subscription.state, 'expired')
        invoice = new_subscription.invoice()
        transactions = invoice.transactions
        self.assertEqual(len(transactions), 1)
        self.assertEqual(transactions[0].status, 'void')

    def test_subscription_termination_partial_refund(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add an active subscription
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()
        self.assertEqual(new_subscription.state, 'active')

        # modify start time so a partial refund will refund half the cost
        start = new_subscription.current_period_started_at
        end = new_subscription.current_period_ends_at
        new_start = start - (end-start)
        mocurly.backend.subscriptions_backend.update_object(new_subscription.uuid, {'current_period_started_at': new_start.isoformat()})

        # get the original transaction and invoice objects for use later
        self.assertEqual(len(mocurly.backend.transactions_backend.datastore), 1)
        self.assertEqual(len(mocurly.backend.invoices_backend.datastore), 1)
        transaction_keys = iterkeys(mocurly.backend.transactions_backend.datastore)
        invoice_keys = iterkeys(mocurly.backend.invoices_backend.datastore)
        original_transaction_id = next(transaction_keys)
        original_invoice_id = next(invoice_keys)

        # Now terminate it with a partial refund
        new_subscription.terminate(refund='partial')

        self.assertEqual(new_subscription.state, 'expired')
        self.assertEqual(len(mocurly.backend.transactions_backend.datastore), 2)
        self.assertEqual(len(mocurly.backend.invoices_backend.datastore), 2)
        for invoice_id, invoice in mocurly.backend.invoices_backend.datastore.items():
            if invoice_id == original_invoice_id:
                original_invoice = invoice
            else:
                refund_invoice = invoice
        # The following two lines reference the objects to make sure they exist
        original_invoice
        refund_invoice

        original_transaction_ids = original_invoice['transactions']
        self.assertEqual(len(original_transaction_ids), 1)
        self.assertEqual(original_transaction_ids[0], original_transaction_id)
        original_transaction = mocurly.backend.transactions_backend.get_object(original_transaction_id)
        self.assertEqual(original_transaction['status'], 'success')  # not voided

        refund_transaction_ids = refund_invoice['transactions']
        self.assertEqual(len(refund_transaction_ids), 1)
        self.assertNotEqual(refund_transaction_ids[0], original_transaction_id)
        refund_transaction = mocurly.backend.transactions_backend.get_object(refund_transaction_ids[0])
        self.assertEqual(refund_transaction['status'], 'success')
        self.assertEqual(refund_transaction['action'], 'refund')
        # 29 / 60, because today doesn't count
        self.assertEqual(refund_transaction['amount_in_cents'], -int(original_transaction['amount_in_cents'] * (29.0 / 60)))

    def test_subscription_cancel_reactivate(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add an active subscription
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()
        self.assertEqual(new_subscription.state, 'active')

        # trying to reactivate an active subscription should fail
        with self.assertRaises(BadRequestError):
           new_subscription.reactivate()

        # now cancel it and verify it was canceled
        new_subscription.cancel()
        self.assertEqual(new_subscription.state, 'canceled')

        # now reactivate it and verify it was reactivated
        new_subscription.reactivate()
        self.assertEqual(new_subscription.state, 'active')
        self.assertEqual(new_subscription.canceled_at, None)
        self.assertEqual(new_subscription.expires_at, None)

    def test_coupon_redemption_percent_discount(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add a sample coupon to the coupons backend
        base_coupon_data = {
                'coupon_code': 'special',
                'name': 'Special 10% off',
                'discount_type': 'percent',
                'discount_percent': 10
            }
        mocurly.backend.coupons_backend.add_object(base_coupon_data['coupon_code'], base_coupon_data)
        # ... and redeem the coupon
        base_redemption_data = {
                'account_code': self.base_account_data['account_code'],
                'currency': 'USD',
                'coupon': base_coupon_data['coupon_code']
            }
        mocurly.backend.coupon_redemptions_backend.add_object(base_redemption_data['coupon'] + '__' + self.base_account_data['account_code'], base_redemption_data)

        # Now add an active subscription and verify the transactions are discounted properly
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()
        invoice = new_subscription.invoice()
        self.assertEqual(invoice.total_in_cents, 900)
        line_items = invoice.line_items
        self.assertEqual(len(line_items), 1)
        line_item = line_items[0]
        self.assertEqual(line_item.unit_amount_in_cents, 1000)
        self.assertEqual(line_item.discount_in_cents, 100)
        self.assertEqual(line_item.total_in_cents, 900)

    def test_coupon_redemption_direct_discount(self):
        # add a sample plan to the plans backend
        mocurly.backend.plans_backend.add_object(self.base_backed_plan_data['plan_code'], self.base_backed_plan_data)
        # add a sample coupon to the coupons backend
        base_coupon_data = {
                'coupon_code': 'special',
                'name': 'Special $1.00 off',
                'discount_type': 'dollars',
                'discount_in_cents': 100
            }
        mocurly.backend.coupons_backend.add_object(base_coupon_data['coupon_code'], base_coupon_data)
        # ... and redeem the coupon
        base_redemption_data = {
                'account_code': self.base_account_data['account_code'],
                'currency': 'USD',
                'coupon': base_coupon_data['coupon_code']
            }
        mocurly.backend.coupon_redemptions_backend.add_object(base_redemption_data['coupon'] + '__' + self.base_account_data['account_code'], base_redemption_data)

        # Now add an active subscription and verify the transactions are discounted properly
        new_subscription = recurly.Subscription(**self.base_subscription_data)
        new_subscription.save()
        invoice = new_subscription.invoice()
        self.assertEqual(invoice.total_in_cents, 900)
        line_items = invoice.line_items
        self.assertEqual(len(line_items), 1)
        line_item = line_items[0]
        self.assertEqual(line_item.unit_amount_in_cents, 1000)
        self.assertEqual(line_item.discount_in_cents, 100)
        self.assertEqual(line_item.total_in_cents, 900)


text:
@class NSString;

@interface ContactTagItem : NSObject <NSCoding>
{
    unsigned int m_uiID;
    NSString *m_nsName;
}

@property(retain, nonatomic) NSString *m_nsName; // @synthesize m_nsName;
@property(nonatomic) unsigned int m_uiID; // @synthesize m_uiID;
- (void).cxx_destruct;
- (id)init;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;

@end


text:
.. _installing:

**********
Installing
**********

.. highlight:: bash

.. note::

    Using :term:`Virtualenv` is recommended when evaluating or running locally.

Installation is simple with `pip <http://www.pip-installer.org/>`_::

    pip install champollion

Installing from source
======================

You can also install manually from the source for more control. First obtain a
copy of the source by either downloading the
`zipball <https://github.com/buddly27/champollion/archive/master.zip>`_ or
cloning the public repository::

    git clone github.com:buddly27/champollion.git

Then you can build and install the package into your current Python
environment::

    pip install .

If actively developing, you can perform an editable install that will link to
the project source and reflect any local changes made instantly::

    pip install -e .

.. note::

    If you plan on building documentation and running tests, run the following
    command instead to install required extra packages for development::

        pip install -e .[dev]

Alternatively, just build locally and manage yourself::

    python setup.py build

Building documentation from source
----------------------------------

Ensure you have installed the 'extra' packages required for building the
documentation::

    pip install -e .[doc]

Then you can build the documentation with the command::

    python setup.py build_sphinx

View the result in your browser at::

    file:///path/to/champollion/build/doc/html/index.html

Running tests against the source
--------------------------------

Ensure you have installed the 'extra' packages required for running the tests::

    pip install .[test]

Then run the tests as follows::

    python setup.py -q test

You can also generate a coverage report when running tests::

    python setup.py -q test --addopts "--cov --cov-report=html"

View the generated report at::

    file:///path/to/champollion/htmlcov/index.html


text:
<formulate-validation-picker-dialog model="model">
</formulate-validation-picker-dialog>


text:
export type LiteralValue =
    string|number|boolean|RegExp|undefined|LiteralArray|LiteralObj|null;
export interface LiteralArray extends Array<LiteralValue> {}
export interface LiteralObj {
  [key: string]: LiteralValue;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>me.jervyshi</groupId>
    <artifactId>demo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>springmvc mybatis demo</name>

    <description>SpringMVC 3.1.x, MyBatis, jQuery and Log4j configuration.</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.6</java.version>
        <junit.version>4.9</junit.version>
        <slf4j.version>1.6.4</slf4j.version>
        <logback.version>1.0.1</logback.version>
        <log4j.version>1.2.14</log4j.version>

        <spring.version>3.1.0.RELEASE</spring.version>

        <mybatis.version>3.1.1</mybatis.version>
        <mybatis-spring.version>1.1.1</mybatis-spring.version>

        <aspectj.version>1.6.8</aspectj.version>
        <cglib.version>2.2</cglib.version>
        <mysql.version>5.1.19</mysql.version>

        <commons.dbcp.version>1.4</commons.dbcp.version>
        <commons.pool.version>1.6</commons.pool.version>
        <commons.lang.version>2.5</commons.lang.version>

        <servlet.version>2.5</servlet.version>
        <jsp.version>2.1</jsp.version>
        <jstl.version>1.2</jstl.version>
        <taglibs-standard.version>1.1.2</taglibs-standard.version>

        <maven.compiler.plugin>2.3.2</maven.compiler.plugin>
        <maven.failsafe.plugin>2.4.3-alpha-1</maven.failsafe.plugin>

        <velocity.version>1.7</velocity.version>
        <velocity-tools.version>2.0</velocity-tools.version>
        <hibernate-validator.version>4.2.0.Final</hibernate-validator.version>
        <validation-api.version>1.1.0.Final</validation-api.version>
        <mockito-core.version>1.9.5</mockito-core.version>
    </properties>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>failsafe-maven-plugin</artifactId>
                <version>${maven.failsafe.plugin}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>ch.qos.logback</groupId>-->
            <!--<artifactId>logback-classic</artifactId>-->
            <!--<version>${logback.version}</version>-->
        <!--</dependency>-->

        <!--<dependency>-->
            <!--<groupId>ch.qos.logback</groupId>-->
            <!--<artifactId>logback-core</artifactId>-->
            <!--<version>${logback.version}</version>-->
        <!--</dependency>-->

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--  Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>${velocity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>${velocity-tools.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib.version}</version>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons.dbcp.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons.lang.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>${commons.pool.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${validation-api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate-validator.version}</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${taglibs-standard.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${mockito-core.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
'use strict';

var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var mongoose = require('mongoose');
process.env.MONGOLAB_URI = 'mongodb://localhost/auth_test';

require(__dirname + '/../../server.js');
var httpBasic = require(__dirname + '/../../lib/http_basic');
var eatAuth = require(__dirname + '/../../lib/eat_auth');

var User = require(__dirname + '/../../models/public_user');

var url = 'localhost:3000/api';

describe('http_basic', function() {
	it('should be able to parse http basic auth', function() {
		var req = {
			headers: {
				authorization: 'Basic ' + (new Buffer('tester:foobar123')).toString('base64')
			}
		};

		httpBasic(req, {}, function() {
			expect(typeof req.auth).to.eql('object');
			expect(req.auth.userName).to.eql('tester');
			expect(req.auth.password).to.eql('foobar123');
		});
	});
});

describe('auth', function() {
	after(function(done) {
		mongoose.connection.db.dropDatabase(function() {
			done();
		});
	});

	it('should be able to create a user', function(done) {
		chai.request(url)
			.post('/signup')
			.send({userName: 'tester2', password: 'foobar123'})
			.end(function(err, res) {
				expect(err).to.eql(null);
				expect(res.body.token).to.have.length.above(0);
				done();
			});
	});

	describe('user already in database', function() {
		before(function(done) {
			var user = new User();
			user.userName = 'tester3';
			user.generateHash('foobar123', function(err, res) {
				if(err) {throw err;}
				user.save(function(err) {
					if(err) {throw err;}
					user.generateToken(function(err, token) {
						if(err) {throw err;}
						this.token = token;
						done();
					}.bind(this));
				}.bind(this));
			}.bind(this));
		});

		it('should be able to sign in', function(done) {
			chai.request(url)
				.get('/signin')
				.auth('tester3', 'foobar123')
				.end(function(err, res) {
					expect(err).to.eql(null);
					expect(res.body.token).to.have.length.above(0);
					done();
				});
		});

		it('should be able to authenticate with eatAuth', function(done) {
			var token = this.token;
			var req = {
				headers: {
					token: token
				}
			};

			eatAuth(req, {}, function() {
				expect(req.user.userName).to.eql('tester3');
				done();
			});
		});

		it('should respond accordingly if username already exists', function(done) {
			chai.request(url)
				.post('/signup')
				.send({userName: 'tester3', password: 'fooey123'})
				.end(function(err, res) {
					expect(err).to.eql(null);
					expect(res.status).to.eql(200);
					expect(res.body.msg).to.eql('A user has already signed up with that username.');
					done();
				});
		});
	});
});


text:
package main

import (
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestMain(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	w := httptest.NewRecorder()

	indexHandler(w, req)
	res := w.Result()
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	require.NoError(t, err)

	var unmarshalled map[string]string
	err = json.Unmarshal(data, &unmarshalled)

	require.NoError(t, err)
	require.Equal(t, unmarshalled["Tag"], "Value")
	require.Equal(t, unmarshalled["Tag2"], "Value2")
	require.Equal(t, unmarshalled["Tag3"], "https://storageaccount.table.core.windows.net/")
}


text:
/**
 * \ingroup type-erasure
 * \defgroup concepts
 * \brief Family of concepts defining possible features of types.
 *
 * This submodule defines trait classes that check for different features
 * that may be available in a given type. All trait classes are defined
 * in the `cpp::concepts` namespace and have a PascalCase name that *tries* to
 * describe the concept the trait represents.
 */


text:
from mock import Mock, sentinel
from nose.tools import raises
from stevedore import (ExtensionManager, NamedExtensionManager, HookManager,
                       DriverManager, EnabledExtensionManager)
from stevedore.dispatch import (DispatchExtensionManager,
                                NameDispatchExtensionManager)
from stevedore.extension import Extension

test_extension = Extension('test_extension', None, None, None)
test_extension2 = Extension('another_one', None, None, None)

mock_entry_point = Mock(module_name='test.extension', attrs=['obj'])
a_driver = Extension('test_driver', mock_entry_point, sentinel.driver_plugin,
                     sentinel.driver_obj)

# base ExtensionManager

def test_instance_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = ExtensionManager.make_test_instance(extensions)

    assert extensions == em.extensions

def test_instance_should_have_default_namespace():
    em = ExtensionManager.make_test_instance([])

    assert em.namespace

def test_instance_should_use_supplied_namespace():
    namespace = 'testing.1.2.3'
    em = ExtensionManager.make_test_instance([], namespace=namespace)

    assert namespace == em.namespace

def test_extension_name_should_be_listed():
    em = ExtensionManager.make_test_instance([test_extension])

    assert test_extension.name in em.names()

def test_iterator_should_yield_extension():
    em = ExtensionManager.make_test_instance([test_extension])

    assert test_extension == next(iter(em))

def test_manager_should_allow_name_access():
    em = ExtensionManager.make_test_instance([test_extension])

    assert test_extension == em[test_extension.name]

def test_manager_should_call():
    em = ExtensionManager.make_test_instance([test_extension])
    func = Mock()

    em.map(func)

    func.assert_called_once_with(test_extension)

def test_manager_should_call_all():
    em = ExtensionManager.make_test_instance([test_extension2,
                                              test_extension])
    func = Mock()

    em.map(func)

    func.assert_any_call(test_extension2)
    func.assert_any_call(test_extension)

def test_manager_return_values():
    def mapped(ext, *args, **kwds):
        return ext.name

    em = ExtensionManager.make_test_instance([test_extension2,
                                              test_extension])
    results = em.map(mapped)
    assert sorted(results) == ['another_one', 'test_extension']

def test_manager_should_eat_exceptions():
    em = ExtensionManager.make_test_instance([test_extension])

    func = Mock(side_effect=RuntimeError('hard coded error'))

    results = em.map(func, 1, 2, a='A', b='B')
    assert results == []

@raises(RuntimeError)
def test_manager_should_propagate_exceptions():
    em = ExtensionManager.make_test_instance([test_extension],
                                             propagate_map_exceptions=True)
    func = Mock(side_effect=RuntimeError('hard coded error'))

    em.map(func, 1, 2, a='A', b='B')

# NamedExtensionManager

def test_named_manager_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = NamedExtensionManager.make_test_instance(extensions)

    assert extensions == em.extensions

def test_named_manager_should_have_default_namespace():
    em = NamedExtensionManager.make_test_instance([])

    assert em.namespace

def test_named_manager_should_use_supplied_namespace():
    namespace = 'testing.1.2.3'
    em = NamedExtensionManager.make_test_instance([], namespace=namespace)

    assert namespace == em.namespace

def test_named_manager_should_populate_names():
    extensions = [test_extension, test_extension2]
    em = NamedExtensionManager.make_test_instance(extensions)

    assert ['test_extension', 'another_one'] == em.names()

# HookManager

def test_hook_manager_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = HookManager.make_test_instance(extensions)

    assert extensions == em.extensions

def test_hook_manager_should_be_first_extension_name():
    extensions = [test_extension, test_extension2]
    em = HookManager.make_test_instance(extensions)

    # This will raise KeyError if the names don't match
    assert em[test_extension.name]

def test_hook_manager_should_have_default_namespace():
    em = HookManager.make_test_instance([test_extension])

    assert em.namespace

def test_hook_manager_should_use_supplied_namespace():
    namespace = 'testing.1.2.3'
    em = HookManager.make_test_instance([test_extension], namespace=namespace)

    assert namespace == em.namespace

def test_hook_manager_should_return_named_extensions():
    hook1 = Extension('captain', None, None, None)
    hook2 = Extension('captain', None, None, None)

    em = HookManager.make_test_instance([hook1, hook2])

    assert [hook1, hook2] == em['captain']

# DriverManager

def test_driver_manager_should_use_supplied_extension():
    em = DriverManager.make_test_instance(a_driver)

    assert [a_driver] == em.extensions

def test_driver_manager_should_have_default_namespace():
    em = DriverManager.make_test_instance(a_driver)

    assert em.namespace

def test_driver_manager_should_use_supplied_namespace():
    namespace = 'testing.1.2.3'
    em = DriverManager.make_test_instance(a_driver, namespace=namespace)

    assert namespace == em.namespace

def test_instance_should_use_driver_name():
    em = DriverManager.make_test_instance(a_driver)

    assert ['test_driver'] == em.names()

def test_instance_call():
    def invoke(ext, *args, **kwds):
        return ext.name, args, kwds

    em = DriverManager.make_test_instance(a_driver)
    result = em(invoke, 'a', b='C')

    assert result == ('test_driver', ('a',), {'b': 'C'})

def test_instance_driver_property():
    em = DriverManager.make_test_instance(a_driver)

    assert sentinel.driver_obj == em.driver

# EnabledExtensionManager

def test_enabled_instance_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = EnabledExtensionManager.make_test_instance(extensions)

    assert extensions == em.extensions

# DispatchExtensionManager

def test_dispatch_instance_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = DispatchExtensionManager.make_test_instance(extensions)

    assert extensions == em.extensions

def test_dispatch_map_should_invoke_filter_for_extensions():
    em = DispatchExtensionManager.make_test_instance([test_extension,
                                                      test_extension2])

    filter_func = Mock(return_value=False)

    args = ('A',)
    kw = {'big': 'Cheese'}

    em.map(filter_func, None, *args, **kw)

    filter_func.assert_any_call(test_extension, *args, **kw)
    filter_func.assert_any_call(test_extension2, *args, **kw)

# NameDispatchExtensionManager

def test_name_dispatch_instance_should_use_supplied_extensions():
    extensions = [test_extension, test_extension2]
    em = NameDispatchExtensionManager.make_test_instance(extensions)

    assert extensions == em.extensions

def test_name_dispatch_instance_should_build_extension_name_map():
    extensions = [test_extension, test_extension2]
    em = NameDispatchExtensionManager.make_test_instance(extensions)

    assert test_extension == em.by_name[test_extension.name]
    assert test_extension2 == em.by_name[test_extension2.name]

def test_named_dispatch_map_should_invoke_filter_for_extensions():
    em = NameDispatchExtensionManager.make_test_instance([test_extension,
                                                          test_extension2])

    func = Mock()

    args = ('A',)
    kw = {'BIGGER': 'Cheese'}

    em.map(['test_extension'], func, *args, **kw)

    func.assert_called_once_with(test_extension, *args, **kw)


text:
#pragma once

#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include <GL/glew.h>

#include <SDL_image.h>
#include <SDL_ttf.h>

#if defined (__linux__) && defined (__INSTALL)
#define PATH std::string("/usr/share/labirintus/")
#else
#define PATH
#endif

/*

According to http://www.opengl-tutorial.org/

*/
GLuint loadShader(GLenum _shaderType, const char* _fileName)
{
	GLuint loadedShader = glCreateShader( _shaderType );

	if ( loadedShader == 0 )
	{
		fprintf(stderr, "Error while initalizing %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string shaderCode = "";

	std::ifstream shaderStream(_fileName);

	if ( !shaderStream.is_open() )
	{
		fprintf(stderr, "Error while loading %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string line = "";
	while ( std::getline(shaderStream, line) )
	{
		shaderCode += line + "\n";
	}

	shaderStream.close();

	const char* sourcePointer = shaderCode.c_str();
	glShaderSource( loadedShader, 1, &sourcePointer, NULL );

	glCompileShader( loadedShader );

	GLint result = GL_FALSE;
    int infoLogLength;

	glGetShaderiv(loadedShader, GL_COMPILE_STATUS, &result);
	glGetShaderiv(loadedShader, GL_INFO_LOG_LENGTH, &infoLogLength);

	if ( GL_FALSE == result )
	{
		std::vector<char> VertexShaderErrorMessage(infoLogLength);
		glGetShaderInfoLog(loadedShader, infoLogLength, NULL, &VertexShaderErrorMessage[0]);

		fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
	}

	return loadedShader;
}

GLuint loadProgramVSGSFS(const char* _fileNameVS, const char* _fileNameGS, const char* _fileNameFS)
{
	GLuint vs_ID = loadShader(GL_VERTEX_SHADER,		_fileNameVS);
	GLuint gs_ID = loadShader(GL_GEOMETRY_SHADER,	_fileNameGS);
	GLuint fs_ID = loadShader(GL_FRAGMENT_SHADER,	_fileNameFS);

	if ( vs_ID == 0 || gs_ID == 0 || fs_ID == 0 )
	{
		return 0;
	}

	GLuint program_ID = glCreateProgram();

	fprintf(stdout, "Linking program\n");
	glAttachShader(program_ID, vs_ID);
	glAttachShader(program_ID, gs_ID);
	glAttachShader(program_ID, fs_ID);

	glLinkProgram(program_ID);

	GLint infoLogLength = 0, result = 0;

	glGetProgramiv(program_ID, GL_LINK_STATUS, &result);
	glGetProgramiv(program_ID, GL_INFO_LOG_LENGTH, &infoLogLength);
	if ( GL_FALSE == result)
	{
		std::vector<char> ProgramErrorMessage( infoLogLength );
		glGetProgramInfoLog(program_ID, infoLogLength, NULL, &ProgramErrorMessage[0]);
		fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
	}

	glDeleteShader( vs_ID );
	glDeleteShader( gs_ID );
	glDeleteShader( fs_ID );

	return program_ID;
}

GLuint TextureFromFile(const std::string& filename)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}
	// TODO: fix this (can't be determined compile time)
	#if SDL_BYTEORDER == SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}

GLuint PointtableFromFile(const std::string& filename, int coins, int diamonds)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}

	#if SDL_BYTEORDER != SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

	std::string fontfile = PATH+"textures/font.ttf";
	TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 50);
	SDL_Surface* text1 = TTF_RenderText_Solid(font, std::to_string(coins).c_str(), {0,0,0});
	SDL_Surface* text2 = TTF_RenderText_Solid(font, std::to_string(diamonds).c_str(), {0,0,0});

	SDL_Rect renderQuad = { 100, 17, 40, 40 };
	SDL_BlitSurface(text1, 0, loaded_img, &renderQuad);
	renderQuad = { 100, 77, 40, 40 };
	SDL_BlitSurface(text2, 0, loaded_img, &renderQuad);

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}


text:
'use strict';

var ElementKit = require('element-kit');

module.exports = {
    /**
     * Triggers a method on an html collection.
     * @param {HTMLCollection} els - A collection of elements
     * @param {string} method - The method to call on each of the elements
     * @param {Array} [params] - An array of parameters in which the pass to the method
     */
    triggerHtmlCollectionMethod: function (els, method, params) {
        var count = els.length,
            i, el;
        for (i = 0; i < count; i++) {
            el = els[i];
            el.kit[method].apply(el.kit, params);
        }
    },

    /**
     * Merges the contents of two or more objects.
     * @param {object} obj - The target object
     * @param {...object} - Additional objects who's properties will be merged in
     */
    extend: function (target) {
        var merged = target,
            source, i;
        for (i = 1; i < arguments.length; i++) {
            source = arguments[i];
            for (var prop in source) {
                if (source.hasOwnProperty(prop)) {
                    merged[prop] = source[prop];
                }
            }
        }
        return merged;
    },

    /**
     * Gets a deeply nested property of an object.
     * @param {object} obj - The object to evaluate
     * @param {string} map - A string denoting where the property that should be extracted exists
     * @param {object} [fallback] - The fallback if the property does not exist
     */
    getNested: function (obj, map, fallback) {
        var mapFragments = map.split('.'),
            val = obj;
        for (var i = 0; i < mapFragments.length; i++) {
            if (val[mapFragments[i]]) {
                val = val[mapFragments[i]];
            } else {
                val = fallback;
                break;
            }
        }
        return val;
    },

    /**
     * Sets a nested property on an object, creating empty objects as needed to avoid undefined errors.
     * @param {object} obj - The initial object
     * @param {string} map - A string denoting where the property that should be set exists
     * @param {*} value - New value to set
     * @example utils.setNested(obj, 'path.to.value.to.set', 'newValue');
     */
    setNested: function (obj, map, value) {
        var mapFragments = map.split('.'),
            val = obj;
        for (var i = 0; i < mapFragments.length; i++) {
            var isLast = i === (mapFragments.length - 1);
            if (!isLast) {
                val[mapFragments[i]] = val[mapFragments[i]] || {};
                val = val[mapFragments[i]];
            } else {
                val[mapFragments[i]] = value;
            }
        }
        return value;
    }
};


text:
Squad no {{ squad.no }}

        {{ participant.gender === 'M' ? 'Mr' : 'Mme' }}
        {{ participant.firstName }}
        {{ participant.lastName }}


text:
layout: post
typo_id: 65
title: MCB Open house at UIUC
---

Last post for today: it was MCB open house today. That is all. Ok almost all. The official web site for it sucks really bad. It seems to be some template from Dreamweaver MX 2004 but it is done really bad. They should have asked a real web master to do it. Embarrassing.


text:
module PatronusFati
  module MessageProcessor
    extend FactoryBase

    def self.cleanup_models
      @next_cleanup ||= Time.now.to_i + 60

      if @next_cleanup <= Time.now.to_i
        @next_cleanup = Time.now.to_i + 60

        close_inactive_connections

        offline_access_points
        offline_clients
      end
    end

    def self.close_inactive_connections
      DataModels::Connection.instances.each do |_, connection|
        connection.announce_changes
      end

      DataModels::Connection.instances.reject! { |_, conn| conn.presence.dead? }
    end

    def self.offline_access_points
      DataModels::AccessPoint.instances.each do |bssid, access_point|
        access_point.cleanup_ssids
        access_point.announce_changes
      end

      DataModels::AccessPoint.instances.reject! { |_, ap| ap.presence.dead? }
    end

    def self.offline_clients
      DataModels::Client.instances.each do |_, client|
        client.cleanup_probes
        client.announce_changes
      end

      DataModels::Client.instances.reject! { |_, ap| ap.presence.dead? }
    end

    def self.handle(message_obj)
      if !PatronusFati.past_initial_flood? && @last_msg_received && (Time.now.to_f - @last_msg_received) >= 0.8
        PatronusFati.past_initial_flood!
      end
      @last_msg_received = Time.now.to_f

      periodic_flush
      result = factory(class_to_name(message_obj), message_obj)
      cleanup_models
      result
    rescue => e
      PatronusFati.logger.error('Error processing the following message object:')
      PatronusFati.logger.error(message_obj.inspect)
      PatronusFati.logger.error('%s: %s' % [e.class, e.message])
      e.backtrace.each do |l|
        PatronusFati.logger.error(l)
      end

      # Need to ensure our backtrace doesn't get sent to kismet
      nil
    end

    def self.ignored_types
      [:ack, :battery, :bssidsrc, :channel, :clisrc, :gps, :info, :kismet,
       :plugin, :source, :status, :time]
    end

    def self.periodic_flush
      @next_sync ||= Time.now.to_i + 300

      if @next_sync <= Time.now.to_i
        # Add a variability of +/- half an hour within a day
        @next_sync = Time.now.to_i + 84600 + rand(3600)

        access_points = []
        clients = []

        PatronusFati::DataModels::AccessPoint.instances.each do |bssid, access_point|
          next unless access_point.sync_flag?(:syncedOnline)
          PatronusFati.event_handler.event(:access_point, :sync, access_point.full_state, access_point.diagnostic_data)
          access_points << bssid
        end

        PatronusFati::DataModels::Client.instances.each do |mac, client|
          next unless client.sync_flag?(:syncedOnline)
          PatronusFati.event_handler.event(:client, :sync, client.full_state, client.diagnostic_data)
          clients << mac
        end

        all_online = { access_points: access_points, clients: clients }
        PatronusFati.event_handler.event(:both, :sync, all_online)
      end
    end
  end
end

require 'patronus_fati/message_processor/alert'
require 'patronus_fati/message_processor/bssid'
require 'patronus_fati/message_processor/capability'
require 'patronus_fati/message_processor/client'
require 'patronus_fati/message_processor/critfail'
require 'patronus_fati/message_processor/error'
require 'patronus_fati/message_processor/protocols'
require 'patronus_fati/message_processor/ssid'
require 'patronus_fati/message_processor/terminate'


text:
namespace content {
class RendererPpapiHost;
}

class XWalkRendererPepperHostFactory : public ppapi::host::HostFactory {
 public:
  explicit XWalkRendererPepperHostFactory(content::RendererPpapiHost* host);
  virtual ~XWalkRendererPepperHostFactory();

  // HostFactory.
  virtual scoped_ptr<ppapi::host::ResourceHost> CreateResourceHost(
      ppapi::host::PpapiHost* host,
      const ppapi::proxy::ResourceMessageCallParams& params,
      PP_Instance instance,
      const IPC::Message& message) OVERRIDE;

 private:
  // Not owned by this object.
  content::RendererPpapiHost* host_;

  DISALLOW_COPY_AND_ASSIGN(XWalkRendererPepperHostFactory);
};

#endif  // XWALK_RUNTIME_RENDERER_PEPPER_XWALK_RENDERER_PEPPER_HOST_FACTORY_H_