text:
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
%    or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
% created on 2011/09/09, including previous works from
%
%         Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
%            created on 2009/11/02
%         François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
%            created on  2009/03/22
%         Joel Feenstra:
%         http://www.mathworks.com/matlabcentral/fileexchange/20565
%            created on 2008/07/03
%
% $Id$
%
% input:
%      fname: input file name, if fname contains "{}" or "[]", fname
%             will be interpreted as a JSON string
%      opt: a struct to store parsing options, opt can be replaced by
%           a list of ('param',value) pairs - the param string is equivallent
%           to a field in opt. opt can have the following
%           fields (first in [.|.] is the default)
%
%           opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
%                         for each element of the JSON data, and group
%                         arrays based on the cell2mat rules.
%           opt.FastArrayParser [1|0 or integer]: if set to 1, use a
%                         speed-optimized array parser when loading an
%                         array object. The fast array parser may
%                         collapse block arrays into a single large
%                         array similar to rules defined in cell2mat; 0 to
%                         use a legacy parser; if set to a larger-than-1
%                         value, this option will specify the minimum
%                         dimension to enable the fast array parser. For
%                         example, if the input is a 3D array, setting
%                         FastArrayParser to 1 will return a 3D array;
%                         setting to 2 will return a cell array of 2D
%                         arrays; setting to 3 will return to a 2D cell
%                         array of 1D vectors; setting to 4 will return a
%                         3D cell array.
%           opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
%      dat: a cell array, where {...} blocks are converted into cell arrays,
%           and [...] are converted to arrays
%
% examples:
%      dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
%      dat=loadjson(['examples' filesep 'example1.json'])
%      dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
%     BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

global pos index_esc isoct arraytoken

if(regexp(fname,'^\s*(?:\[.*\])|(?:\{.*\})\s*$','once'))
   string=fname;
elseif(exist(fname,'file'))
   try
       string = fileread(fname);
   catch
       try
           string = urlread(['file://',fname]);
       catch
           string = urlread(['file://',fullfile(pwd,fname)]);
       end
   end
else
   error('input file does not exist');
end

pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\','  ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);

% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1;

opt=varargin2struct(varargin{:});

if(jsonopt('ShowProgress',0,opt)==1)
    opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
    switch(next_char(inStr))
        case '{'
            data{jsoncount} = parse_object(inStr, esc, opt);
        case '['
            data{jsoncount} = parse_array(inStr, esc, opt);
        otherwise
            error_pos('Outer level structure must be an object or an array',inStr);
    end
    jsoncount=jsoncount+1;
end % while

jsoncount=length(data);
if(jsoncount==1 && iscell(data))
    data=data{1};
end

if(isfield(opt,'progressbar_'))
    close(opt.progressbar_);
end

%%-------------------------------------------------------------------------
function object = parse_object(inStr, esc, varargin)
    parse_char(inStr, '{');
    object = [];
    if next_char(inStr) ~= '}'
        while 1
            str = parseStr(inStr, esc, varargin{:});
            if isempty(str)
                error_pos('Name of value at position %d cannot be empty',inStr);
            end
            parse_char(inStr, ':');
            val = parse_value(inStr, esc, varargin{:});
            object.(valid_field(str))=val;
            if next_char(inStr) == '}'
                break;
            end
            parse_char(inStr, ',');
        end
    end
    parse_char(inStr, '}');
    if(isstruct(object))
        object=struct2jdata(object);
    end

%%-------------------------------------------------------------------------

function object = parse_array(inStr, esc, varargin) % JSON array is written in row-major order
    global pos isoct
    parse_char(inStr, '[');
    object = cell(0, 1);
    dim2=[];
    arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
    pbar=-1;
    if(isfield(varargin{1},'progressbar_'))
        pbar=varargin{1}.progressbar_;
    end

    if next_char(inStr) ~= ']'
	if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
            [endpos, e1l, e1r]=matching_bracket(inStr,pos);
            arraystr=['[' inStr(pos:endpos)];
            arraystr=regexprep(arraystr,'"_NaN_"','NaN');
            arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
            arraystr(arraystr==sprintf('\n'))=[];
            arraystr(arraystr==sprintf('\r'))=[];
            %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
            if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
        	astr=inStr((e1l+1):(e1r-1));
        	astr=regexprep(astr,'"_NaN_"','NaN');
        	astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
        	astr(astr==sprintf('\n'))=[];
        	astr(astr==sprintf('\r'))=[];
        	astr(astr==' ')='';
        	if(isempty(find(astr=='[', 1))) % array is 2D
                    dim2=length(sscanf(astr,'%f,',[1 inf]));
        	end
            else % array is 1D
        	astr=arraystr(2:end-1);
        	astr(astr==' ')='';
        	[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
        	if(nextidx>=length(astr)-1)
                    object=obj;
                    pos=endpos;
                    parse_char(inStr, ']');
                    return;
        	end
            end

            try
              if(~isempty(dim2))
        	astr=arraystr;
        	astr(astr=='[')='';
        	astr(astr==']')='';
                astr=regexprep(astr,'\s*$','');
        	astr(astr==' ')='';
        	[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
        	if(nextidx>=length(astr)-1)
                    object=reshape(obj,dim2,numel(obj)/dim2)';
                    pos=endpos;
                    parse_char(inStr, ']');
                    if(pbar>0)
                        waitbar(pos/length(inStr),pbar,'loading ...');
                    end
                    return;
        	end
              end
              arraystr=regexprep(arraystr,'\]\s*,','];');
            catch
            end
	else
            arraystr='[';
	end
        try
           arraystr=regexprep(arraystr,'^\s*\[','{','once');
           arraystr=regexprep(arraystr,'\]\s*$','}','once');
           if(isoct && regexp(arraystr,'"','once'))
                error('Octave eval can produce empty cells for JSON-like input');
           end
           object=eval(arraystr);
           pos=endpos;
        catch
         while 1
            newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
            val = parse_value(inStr, esc, newopt);
            object{end+1} = val;
            if next_char(inStr) == ']'
                break;
            end
            parse_char(inStr, ',');
         end
        end
    end
    if(jsonopt('SimplifyCell',0,varargin{:})==1)
      try
        oldobj=object;
        object=cell2mat(object')';
        if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
            object=oldobj;
        elseif(size(object,1)>1 && ismatrix(object))
            object=object';
        end
      catch
      end
    end
    parse_char(inStr, ']');

    if(pbar>0)
        waitbar(pos/length(inStr),pbar,'loading ...');
    end
%%-------------------------------------------------------------------------

function parse_char(inStr, c)
    global pos
    pos=skip_whitespace(pos, inStr);
    if pos > length(inStr) || inStr(pos) ~= c
        error_pos(sprintf('Expected %c at position %%d', c),inStr);
    else
        pos = pos + 1;
        pos=skip_whitespace(pos, inStr);
    end

%%-------------------------------------------------------------------------

function c = next_char(inStr)
    global pos
    pos=skip_whitespace(pos, inStr);
    if pos > length(inStr)
        c = [];
    else
        c = inStr(pos);
    end

%%-------------------------------------------------------------------------

function newpos=skip_whitespace(pos, inStr)
    newpos=pos;
    while newpos <= length(inStr) && isspace(inStr(newpos))
        newpos = newpos + 1;
    end

%%-------------------------------------------------------------------------
function str = parseStr(inStr, esc, varargin)
    global pos index_esc
 % len, ns = length(inStr), keyboard
    if inStr(pos) ~= '"'
        error_pos('String starting with " expected at position %d',inStr);
    else
        pos = pos + 1;
    end
    str = '';
    while pos <= length(inStr)
        while index_esc <= length(esc) && esc(index_esc) < pos
            index_esc = index_esc + 1;
        end
        if index_esc > length(esc)
            str = [str inStr(pos:end)];
            pos = length(inStr) + 1;
            break;
        else
            str = [str inStr(pos:esc(index_esc)-1)];
            pos = esc(index_esc);
        end
        nstr = length(str);
        switch inStr(pos)
            case '"'
                pos = pos + 1;
                if(~isempty(str))
                    if(strcmp(str,'_Inf_'))
                        str=Inf;
                    elseif(strcmp(str,'-_Inf_'))
                        str=-Inf;
                    elseif(strcmp(str,'_NaN_'))
                        str=NaN;
                    end
                end
                return;
            case '\'
                if pos+1 > length(inStr)
                    error_pos('End of file reached right after escape character',inStr);
                end
                pos = pos + 1;
                switch inStr(pos)
                    case {'"' '\' '/'}
                        str(nstr+1) = inStr(pos);
                        pos = pos + 1;
                    case {'b' 'f' 'n' 'r' 't'}
                        str(nstr+1) = sprintf(['\' inStr(pos)]);
                        pos = pos + 1;
                    case 'u'
                        if pos+4 > length(inStr)
                            error_pos('End of file reached in escaped unicode character',inStr);
                        end
                        str(nstr+(1:6)) = inStr(pos-1:pos+4);
                        pos = pos + 5;
                end
            otherwise % should never happen
                str(nstr+1) = inStr(pos);
                keyboard;
                pos = pos + 1;
        end
    end
    error_pos('End of file while expecting end of inStr',inStr);

%%-------------------------------------------------------------------------

function num = parse_number(inStr, varargin)
    global pos isoct
    currstr=inStr(pos:min(pos+30,end));
    if(isoct~=0)
        numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
        [num] = sscanf(currstr, '%f', 1);
        delta=numstr+1;
    else
        [num, one, err, delta] = sscanf(currstr, '%f', 1);
        if ~isempty(err)
            error_pos('Error reading number at position %d',inStr);
        end
    end
    pos = pos + delta-1;

%%-------------------------------------------------------------------------

function val = parse_value(inStr, esc, varargin)
    global pos
    len=length(inStr);
    if(isfield(varargin{1},'progressbar_'))
        waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
    end

    switch(inStr(pos))
        case '"'
            val = parseStr(inStr, esc, varargin{:});
            return;
        case '['
            val = parse_array(inStr, esc, varargin{:});
            return;
        case '{'
            val = parse_object(inStr, esc, varargin{:});
            return;
        case {'-','0','1','2','3','4','5','6','7','8','9'}
            val = parse_number(inStr, varargin{:});
            return;
        case 't'
            if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
                val = true;
                pos = pos + 4;
                return;
            end
        case 'f'
            if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
                val = false;
                pos = pos + 5;
                return;
            end
        case 'n'
            if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
                val = [];
                pos = pos + 4;
                return;
            end
    end
    error_pos('Value expected at position %d',inStr);
%%-------------------------------------------------------------------------

function error_pos(msg, inStr)
    global pos len
    poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
    if poShow(3) == poShow(2)
        poShow(3:4) = poShow(2)+[0 -1];  % display nothing after
    end
    msg = [sprintf(msg, pos) ': ' ...
    inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
    error( ['JSONparser:invalidFormat: ' msg] );

%%-------------------------------------------------------------------------

function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
    pos=regexp(str,'^[^A-Za-z]','once');
    if(~isempty(pos))
        if(~isoct && str(1)+0 > 255)
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
        end
    end
    if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
        return;
    end
    if(~isoct)
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        pos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(pos))
            return;
        end
        str0=str;
        pos0=[0 pos(:)' length(str)];
        str='';
        for i=1:length(pos)
            str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
        end
        if(pos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end
    %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';

%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
    if(str(pos)=='"')
        if(~(pos>1 && str(pos-1)=='\'))
            endpos=pos;
            return;
        end
    end
    pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
    c=tokens(pos);
    if(c==']')
        level=level-1;
        if(isempty(e1r))
            e1r=bpos(pos);
        end
        if(level==0)
            endpos=bpos(pos);
            return
        end
    end
    if(c=='[')
        if(isempty(e1l))
            e1l=bpos(pos);
        end
        level=level+1;
        maxlevel=max(maxlevel,level);
    end
    if(c=='"')
        pos=matching_quote(tokens,pos+1);
    end
    pos=pos+1;
end
if(endpos==0)
    error('unmatched "]"');
end


text:
package com.hardik.javase;

/**
 * Java String length() Method
 *
 * The java string length() method returns length of the string. It returns
 * count of total number of characters. The length of java string is same as the
 * unicode code units of the string.
 *
 * @author HARDIK HIRAPARA
 *
 */
public class Length {
	public static void main(String[] args) {

		String s1 = "Java Programming";
		String s2 = "C++";

		System.out.println("String length is: " + s1.length());
		System.out.println("String length is: " + s2.length());
	}
}

redpajama_set_name: RedPajamaGithub


text:
package _10July2016.models.hardware;

import _10July2016.models.Component;
import _10July2016.models.software.SoftwareComponent;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class HardwareComponent extends Component {
    private Map<String,SoftwareComponent> software;

    protected HardwareComponent(String name, int capacity, int memory) {
        super(name, "HardwareComponent");

        this.setCapacity(capacity);
        this.setMemory(memory);
        this.software = new LinkedHashMap<>();
    }

    public Map<String, SoftwareComponent> getSoftware() {
        return Collections.unmodifiableMap(this.software);
    }

    @Override
    public int getCapacity() {
        return super.getCapacity();
    }

    @Override
    public int getMemory() {
        return super.getMemory();
    }

    public long getFreeCapacity() {
        return (super.getCapacity() - this.software.values().stream().mapToLong(SoftwareComponent::getCapacityConsumption).sum());
    }

    public long getFreeMemory() {
        return (super.getMemory() - this.software.values().stream().mapToLong(SoftwareComponent::getMemoryConsumption).sum());
    }

    public void registerSoftwareComponent(SoftwareComponent softwareComponent) {
        this.software.put(softwareComponent.getName(), softwareComponent);
    }

    public boolean isPresent(String softwareName){
        if(this.software.containsKey(softwareName)){
            return true;
        }
        return false;
    }

    public void releaseSoftware(String softwareName){
        this.software.remove(softwareName);
    }

    public long getExpressSoftwareCount(){
        return this.software.values().stream().filter(s->s.getType().equalsIgnoreCase("express")).count();
    }

    public long getLightSoftwareCount(){
        return this.software.values().stream().filter(s->s.getType().equalsIgnoreCase("light")).count();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("Hardware Component - %s\n", super.getName()));
        sb.append(String.format("Express Software Components - %d\n", this.getExpressSoftwareCount()));
        sb.append(String.format("Light Software Components - %d\n", this.getLightSoftwareCount()));
        sb.append(String.format("Memory Usage: %d / %d\n",
                this.getMemory() - this.getFreeMemory(), this.getMemory()));
        sb.append(String.format("Capacity Usage: %d / %d\n",
                this.getCapacity() - this.getFreeCapacity(), this.getCapacity()));
        sb.append(String.format("Type: %s\n", this.getType()));
        sb.append(String.format("Software Components: %s\n",
                this.software.size()>0?
                this.software.values().stream().map(SoftwareComponent::getName).collect(Collectors.joining(", ")):
                        "None"));

        return sb.toString();

    }
}


text:
package com.epimorphics.registry.message;

import java.io.IOException;
import java.io.InputStream;

import com.epimorphics.registry.core.Command;
import com.epimorphics.registry.core.Registry;

/**
 * Support for logging update requests to allow replay and replication.
 * The configured instance will define where logs go and any actions to trigger.
 *
 * @author Dave Reynolds
 */
public interface RequestLogger {

    public void setRegistry(Registry registry);

    /**
     * Log the command to a configured log directory.
     * Returns the name of the created log file
     */
    public String writeLog(Command command) throws IOException;

    /**
     * Reconstruct a command from the a log entry originally created with writeLog
     */
    public Command getLog(InputStream in) throws IOException;

}


text:
/**
 * Provides classes for the conversion of conll file to and from Brat response formats
 */
package de.tudarmstadt.ukp.clarin.webanno.tsv;


text:
CASE("Header::Header() constructs an empty header with capacity 25")
{
  http::Header header;
  EXPECT(header.is_empty() == true);
  EXPECT(header.size() == 0u);
  // try to add more than capacity
  for (int i = 1; i < 30; ++i) {
    header.add_field("X-Something-Something_" + std::to_string(i), "foo");
  }
  EXPECT(header.is_empty() == false);
  EXPECT(header.size() == 25u);
}

CASE("Header::add_field() adds a header field")
{
  http::Header header;
  EXPECT(header.is_empty() == true);
  auto ok = header.add_field("Accept-Charset", "utf-8");
  EXPECT(ok == true);
  EXPECT(header.is_empty() == false);
  EXPECT(header.size() == 1u);
  ok = header.has_field("Accept-Charset");
  EXPECT(ok == true);
}

CASE("Header::has_field() checks if header has a specific field")
{
  http::Header header;
  EXPECT(header.is_empty() == true);
  auto ok = header.add_field("Accept-Charset", "iso-8859-1");
  EXPECT(ok == true);
  ok = header.has_field("Accept");
  EXPECT(ok == false);
  ok = header.has_field("Accept-Charset");
  EXPECT(ok == true);
}

CASE("Header::value() returns value of specific field")
{
  http::Header header;
  EXPECT(header.is_empty() == true);
  auto ok = header.add_field("Accept-Encoding", "gzip");
  EXPECT(ok == true);
  auto val = header.value("Accept-Encoding");
  EXPECT(val == "gzip");
  val = header.value("Accept");
  EXPECT(val == "");
}

CASE("Header::clear() removes all fields")
{
  http::Header header;
  auto ok = header.add_field("Connection", "keep-alive");
  EXPECT(ok == true);
  EXPECT(header.size() == 1u);
  header.clear();
  EXPECT(header.size() == 0u);
}

CASE("Header::erase() removes specified field")
{
  http::Header header;
  header.add_field("Connection", "keep-alive");
  header.add_field("Accept-Encoding", "gzip");
  header.add_field("Accept-Charset", "iso-8859-1");
  EXPECT(header.size() == 3u);
  header.erase("X-Something-Something");
  EXPECT(header.size() == 3u);
  header.erase("Accept-Encoding");
  EXPECT(header.size() == 2u);
  EXPECT(header.has_field("Accept-Encoding") == false);
}

CASE("Header::set_field() sets specified field ")
{
  http::Header header;
  header.set_field("Connection", "keep-alive");
  EXPECT(header.size() == 1);
  EXPECT(header.has_field("Connection") == true);
  auto val = header.value("Connection");
  EXPECT(val == "keep-alive");
  bool res = header.set_field("Connection", "close");
  EXPECT(res == true);
  val = header.value("Connection");
  EXPECT(val == "close");
}

CASE("Headers can be streamed")
{
  http::Header header;
  bool res = header.set_field("Connection", "close");
  std::stringstream ss;
  ss << header;
  EXPECT(ss.str().size() > 15);
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';
import Forms from 'furnace-forms';
import wait from 'ember-test-helpers/wait';

var person1;
var person2;
var company1;
var company2;
var friends1=[];
var friends2=[];
var MultipleStaticOptionsForm=Forms.Form.extend({
	friends:Forms.input('checklist').options(Forms.option('a','a'),Forms.option('b','b'),Forms.option('c','c')).multiple(),

	validator:null
}).model('person');

function getTestOptions(model,options) {
	var friends;
	switch(model) {
		case person1:
		case company1:
			friends=friends1;
			break;
		case person2:
		case company2:
			friends=friends2;
			break;
		default:
			friends=[];
			break;
	}
	friends.forEach((friend)=>{
		options.push(Forms.option(friend,friend.get('firstName')));
	});
	return options;
}

function getAttributeTestOptions(model,options) {
	var friends;
	switch(model.get('optionsToggle')) {
		case false:
			friends=friends1;
			break;
		case true:
			friends=friends2;
			break;
		default:
			friends=[];
			break;
	}
	friends.forEach((friend)=>{
		options.push(Forms.option(friend,friend.get('firstName')));
	});
	return options;
}

var MultipleDynamicOptionsForm=Forms.Form.extend({
	friends:Forms.input('checklist').options(function(options){
		return getTestOptions(this.getModel(),options);
	}).multiple(),

	validator:null
}).model('person');

var MultiplePromiseOptionsForm=Forms.Form.extend({
	friends:Forms.input('checklist').options(function(options) {
		return new Ember.RSVP.Promise((resolve)=>{
			resolve(getTestOptions(this.getModel(),options));
		});
	}).multiple(),
	validator:null
}).model('person');

var MultipleAttributeDynamicOptionsForm=Forms.Form.extend({
	friends:Forms.input('checklist').options(function(options){
		return getAttributeTestOptions(this.getModel(),options);
	}).multiple().on('optionsToggle'),
	optionsToggle:Forms.attr('optionsToggle'),
	validator:null
}).model('person');

var MultipleAttributePromiseOptionsForm=Forms.Form.extend({
	friends:Forms.input('checklist').options(function(options) {
		return new Ember.RSVP.Promise((resolve)=>{
			resolve(getAttributeTestOptions(this.getModel(),options));
		});
	}).multiple().on('optionsToggle'),
	optionsToggle:Forms.attr('optionsToggle'),
	validator:null
}).model('person');

moduleForComponent('furnace-form', 'Integration | Options | Multiple', {
	integration: true,
	beforeEach() {
		var owner=Ember.getOwner(this);
		owner.lookup('application:main').set('defaultLocale','en');
		owner.factoryFor('initializer:furnace-forms').class.initialize(owner);
		owner.factoryFor('initializer:furnace-i18n').class.initialize(owner);
		owner.factoryFor('initializer:furnace-validation').class.initialize(owner);
		this.register('form:multiple-static-options',MultipleStaticOptionsForm)
		this.register('form:multiple-dynamic-options',MultipleDynamicOptionsForm)
		this.register('form:multiple-promise-options',MultiplePromiseOptionsForm)
		this.inject.service('store');
		friends1=[];
		friends2=[];
		friends1.push(this.get('store').createRecord('person',{
			firstName:'Chris',
		}));
		friends1.push(this.get('store').createRecord('person',{
			firstName:'David',
		}));
		friends1.push(this.get('store').createRecord('person',{
			firstName:'Eddy',
		}));
		friends2.push(this.get('store').createRecord('person',{
			firstName:'Garry',
		}));
		friends2.push(this.get('store').createRecord('person',{
			firstName:'Harry',
		}));
		friends2.push(this.get('store').createRecord('person',{
			firstName:'Ian',
		}));
		friends2.push(this.get('store').createRecord('employee',{
			firstName:'John',
		}));
		person1=this.get('store').createRecord('person',{
			firstName:'Adrian',
			optionsToggle:false,
			friends:friends1.slice(0,1)
		});
		person2=this.get('store').createRecord('person',{
			firstName:'Brian',
			optionsToggle:false,
			friends:friends2.slice(0,2)
		});
		company1=this.get('store').createRecord('company',{
			firstName:'TestCorp Inc',
			optionsToggle:false,
			friends:friends1.slice(0,1)
		});
		company2=this.get('store').createRecord('company',{
			firstName:'Testing Ltd',
			optionsToggle:false,
			friends:friends2.slice(0,2)
		});
	},
	testModel() {
		return person1;
	}
});

test('MultipleStaticOptionsForm renders', function(assert) {

	this.set('model',this.testModel());

	this.render(hbs`{{furnace-form 'multiple-static-options' for=model}}`);

	assert.ok(this.$('form[type=MultipleStaticOptions]').length===1,'Form renders');

	assert.ok(this.$('form[type=MultipleStaticOptions] > controls > control.friends').length===1,'List renders');

	assert.ok(this.$('form[type=MultipleStaticOptions] > controls > control.friends > options > control').length===3,'List contains 3 controls');

});

test('MultipleDynamicOptionsForm renders', function(assert) {

	this.set('model',this.testModel());

	this.render(hbs`{{furnace-form 'multiple-dynamic-options' for=model}}`);

	assert.ok(this.$('form[type=MultipleDynamicOptions]').length===1,'Form renders');

	assert.ok(this.$('form[type=MultipleDynamicOptions] > controls > control.friends').length===1,'List renders');

	return wait().then(()=>{
		assert.ok(this.$('form[type=MultipleDynamicOptions] > controls > control.friends > options > control').length===3,'List contains 3 controls');
	});
});

test('MultiplePromiseOptionsForm renders', function(assert) {

	this.set('model',this.testModel());

	this.render(hbs`{{furnace-form 'multiple-promise-options' for=model}}`);

	assert.ok(this.$('form[type=MultiplePromiseOptions]').length===1,'Form renders');

	assert.ok(this.$('form[type=MultiplePromiseOptions] > controls > control.friends').length===1,'List renders');

	return wait().then(()=>{
		Ember.run(() => {
			assert.ok(this.$('form[type=MultiplePromiseOptions] > controls > control.friends > options > control').length===3,'List contains 3 controls');
		});
		return wait().then(()=>{
			Ember.run(() => {
				assert.ok(this.$('form[type=MultiplePromiseOptions] > controls > control.friends > options > control').length===3,'List contains 3 controls');
			});
		});
	});
});

test('Model update - Async attribute - Model based promise options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultiplePromiseOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		// Trigger control load, don't get the option controls yet
		// Options won't be ready and the reload occurs in the computed property
		formControl.get('friends');
	});

	return wait().then(()=> {
		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');

			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});

		Ember.run(()=>{
			formControl.set('for',person2);
		});

		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');
		});

		Ember.run(()=>{
			assert.equal(optionControls.length,4,'4 optionControls');

			assert.equal(Ember.compare(person2.get('friends').toArray(),friends2.slice(0,2)),0,'Person 2 friends');

			assert.notEqual(Ember.compare(person2.get('friends').toArray(),friends1.slice(0,1)),0,'Not person 1 friends');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

			assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
		});
	});
});

test('Model update - Synced attribute - Model based promise options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultiplePromiseOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': company1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		// Trigger control load, don't get the option controls yet
		// Options won't be ready and the reload occurs in the computed property
		formControl.get('friends');
	});

	return wait().then(()=> {
		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');

			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});

		Ember.run(()=>{
			formControl.set('for',company2);
		});

		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');
		});

		Ember.run(()=>{
			assert.equal(optionControls.length,4,'4 optionControls');

			assert.equal(Ember.compare(company2.get('friends').toArray(),friends2.slice(0,2)),0,'Person 2 friends');

			assert.notEqual(Ember.compare(company2.get('friends').toArray(),friends1.slice(0,1)),0,'Not person 1 friends');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

			assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
		});
	});
});

test('Attribute update - Async attribute - Model based promise options',function(assert){
	var formControl,optionControls;
	Ember.run(() => {
		formControl=MultiplePromiseOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		// Trigger control load, don't get the option controls yet
		// Options won't be ready and the reload occurs in the computed property
		formControl.get('friends');
	});

	return wait().then(()=> {
		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');
			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});

		Ember.run(()=>{
			person1.get('friends').pushObject(friends1.objectAt(1));
		});

		Ember.run(()=>{
			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,2)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});
	});
});

test('Attribute update - Synced attribute - Model based promise options',function(assert){
	var formControl,optionControls;
	Ember.run(() => {
		formControl=MultiplePromiseOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': company1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		// Trigger control load, don't get the option controls yet
		// Options won't be ready and the reload occurs in the computed property
		formControl.get('friends');
	});

	return wait().then(()=> {
		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');
			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(company1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});

		Ember.run(()=>{
			company1.get('friends').pushObject(friends1.objectAt(1));
		});

		Ember.run(()=>{
			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(company1.get('friends').toArray(),friends1.slice(0,2)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});
	});
});

test('Attribute update - Attribute based promise options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultipleAttributePromiseOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		// Trigger control load, don't get the option controls yet
		// Options won't be ready and the reload occurs in the computed property
		formControl.get('friends');
	});

	return wait().then(()=> {
		Ember.run(()=>{
			optionControls=formControl.get('friends.optionControls');

			assert.equal(optionControls.length,3,'3 optionControls');

			assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

			assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

			assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

			assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
		});

		Ember.run(()=>{
			formControl.set('for.optionsToggle',true);
		});
		return wait().then(()=> {

			Ember.run(()=>{
				optionControls=formControl.get('friends.optionControls');
			});

			Ember.run(()=>{
				assert.equal(optionControls.length,4,'4 optionControls');

				assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person 1 friends');

				assert.equal(optionControls[0].get('selected'),false,'OptionControl0 not selected');

				assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

				assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

				assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
			});
		});
	});
});

test('Model update - Async attribute - Model based options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultipleDynamicOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});

	Ember.run(()=>{
		formControl.set('for',person2);
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,4,'4 optionControls');

		assert.equal(Ember.compare(person2.get('friends').toArray(),friends2.slice(0,2)),0,'Person 2 friends');

		assert.notEqual(Ember.compare(person2.get('friends').toArray(),friends1.slice(0,1)),0,'Not person 1 friends');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

		assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
	});

});

test('Model update - Synced attribute - Model based options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultipleDynamicOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': company1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(company1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});

	Ember.run(()=>{
		formControl.set('for',company2);
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,4,'4 optionControls');

		assert.equal(Ember.compare(company2.get('friends').toArray(),friends2.slice(0,2)),0,'Person 2 friends');

		assert.notEqual(Ember.compare(company2.get('friends').toArray(),friends1.slice(0,1)),0,'Not person 1 friends');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

		assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
	});
});

test('Attribute update - Async attribute - Model based options',function(assert){
	var formControl,optionControls;
	Ember.run(() => {
		formControl=MultipleDynamicOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});

	Ember.run(()=>{
		person1.get('friends').pushObject(friends1.objectAt(1));
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,2)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});
});

test('Attribute update - Synced attribute - Model based options',function(assert){
	var formControl,optionControls;
	Ember.run(() => {
		formControl=MultipleDynamicOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': company1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(company1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});

	Ember.run(()=>{
		company1.get('friends').pushObject(friends1.objectAt(1));
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(company1.get('friends').toArray(),friends1.slice(0,2)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),true,'OptionControl1 selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});
});

test('Attribute update - Attribute based options',function(assert){
	var formControl,optionControls;

	Ember.run(() => {
		formControl=MultipleAttributeDynamicOptionsForm.create(Ember.getOwner(this).ownerInjection(),{
			'for': person1,
			target: this,
			_rootControl:true
		});
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,3,'3 optionControls');

		assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person1 friend');

		assert.equal(optionControls[0].get('selected'),true,'OptionControl0 selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');
	});

	Ember.run(()=>{
		formControl.set('for.optionsToggle',true);
	});

	Ember.run(()=>{
		optionControls=formControl.get('friends.optionControls');
	});

	Ember.run(()=>{
		assert.equal(optionControls.length,4,'4 optionControls');

		assert.equal(Ember.compare(person1.get('friends').toArray(),friends1.slice(0,1)),0,'Person 1 friends');

		assert.equal(optionControls[0].get('selected'),false,'OptionControl0 not selected');

		assert.equal(optionControls[1].get('selected'),false,'OptionControl1 not selected');

		assert.equal(optionControls[2].get('selected'),false,'OptionControl2 not selected');

		assert.equal(optionControls[3].get('selected'),false,'OptionControl3 not selected');
	});
});

test('Model updates - Control retention',function(assert){
	assert.expect(0);
});

test('Model updates - Dirty state',function(assert){
	assert.expect(0);
});

test('Relation updates - Control retention',function(assert){
	assert.expect(0);
});

test('Relation updates - Dirty state',function(assert){
	assert.expect(0);
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronText.Extensibility;
using IronText.Logging;
using IronText.Reflection.Reporting;

namespace IronText.Reflection.Managed
{
    class CilGrammar
    {
        private readonly List<ICilMetadata>                 metadata;
        private readonly List<CilProduction>                productions;
        private readonly List<CilCondition>                 conditions;
        private readonly CilMerger[]                        mergers;
        private readonly List<CilSymbolFeature<Precedence>> precedence;

        public CilGrammar(CilGrammarSource source, ILogging logging)
        {
            Type definitionType = source.DefinitionType;

            GlobalContextProvider = new CilContextProvider(definitionType);

            this.IsValid = true;

            var startMeta = MetadataParser.EnumerateAndBind(definitionType);
            if (startMeta.Count() == 0)
            {
                throw new InvalidOperationException(
                    string.Format(
                        "No metadata found in language definition '{0}'",
                        definitionType.FullName));
            }

            this.SymbolResolver = new CilSymbolRefResolver();

            this.Start = CilSymbolRef.Create(typeof(void));

            var collector = new MetadataCollector(logging);
            collector.AddSymbol(Start);
            foreach (var meta in startMeta)
            {
                collector.AddMeta(meta);
            }

            if (collector.HasInvalidData)
            {
                this.IsValid = false;
            }

            this.metadata = collector.Metadata;
            this.productions = collector.Productions;

            foreach (var tid in collector.Symbols)
            {
                SymbolResolver.Link(tid);
            }

            var categories = new [] { SymbolCategory.Beacon, SymbolCategory.DoNotInsert, SymbolCategory.DoNotDelete, SymbolCategory.ExplicitlyUsed };

            foreach (var category in categories)
            {
                foreach (var symbol in metadata.SelectMany(m => m.GetSymbolsInCategory(category)))
                {
                    var def = SymbolResolver.Resolve(symbol);
                    def.Categories |= category;
                }
            }

            if (productions.Count == 0)
            {
                throw new InvalidOperationException(
                    string.Format(
                        "Language definition '{0}' should have at least one parse production",
                        definitionType.FullName));
            }

            this.mergers
                = metadata
                    .SelectMany(meta => meta.GetMergers(collector.Symbols))
                    .ToArray();

            var terminals = collector.Symbols.Except(productions.Select(r => r.Outcome).Distinct()).ToArray();

            var scanDataCollector = new ScanDataCollector(terminals, logging);
            scanDataCollector.AddCondition(definitionType);
            if (scanDataCollector.HasInvalidData)
            {
                this.IsValid = false;
            }

            conditions = scanDataCollector.Conditions;
            LinkRelatedTokens(conditions);

            var allTerms = (from t in scanDataCollector.Terminals
                           let def = SymbolResolver.Resolve(t)
                           where def != null
                           select def)
                           .Distinct();
            var termsProducedByScanner =
                            (from cond in scanDataCollector.Conditions
                             from prod in cond.Matchers
                             from outcome in prod.AllOutcomes
                             let def = SymbolResolver.Resolve(outcome)
                             where def != null
                             select def)
                            .Distinct();
            var undefinedTerminals = allTerms
                .Where(symbol => !IsSpecialSymbol(symbol))
                .Except(termsProducedByScanner);

            CheckAllScanRulesDefined(undefinedTerminals, source.Origin, logging);

            precedence = metadata.SelectMany(m => m.GetSymbolPrecedence()).ToList();

            LocalContextProviders = metadata.SelectMany((m, index) => m.GetLocalContextProviders());

            this.Reports = metadata.SelectMany(m => m.GetReports()).ToArray();
        }

        public bool IsValid { get; private set; }

        public CilContextProvider      GlobalContextProvider { get; private set; }

        public CilSymbolRef            Start          { get; private set; }

        public IReport[]               Reports        { get; private set; }

        public ICilSymbolResolver      SymbolResolver { get; private set; }

        public IList<CilProduction>    Productions    { get { return productions; } }

        public IList<CilMerger>        Mergers        { get { return mergers; } }

        public IList<CilCondition>     Conditions     { get { return conditions; } }

        public IEnumerable<CilSymbolFeature<Precedence>> Precedence { get { return precedence; } }

        public IEnumerable<CilSymbolFeature<CilContextProvider>> LocalContextProviders { get; private set; }

        private static bool IsSpecialSymbol(CilSymbol symbol)
        {
            return symbol.Type == typeof(Exception);
        }

        private void LinkRelatedTokens(List<CilCondition> conditions)
        {
            foreach (var condition in conditions)
            {
                foreach (var matcher in condition.Matchers)
                {
                    foreach (CilSymbolRef symbol in matcher.AllOutcomes)
                    {
                        if (SymbolResolver.Contains(symbol))
                        {
                            SymbolResolver.Link(symbol);
                        }
                    }
                }
            }
        }

        private void CheckAllScanRulesDefined(
            IEnumerable<CilSymbol> undefinedTerminals,
            string                 origin,
            ILogging               logging)
        {
            if (undefinedTerminals.Count() == 0)
            {
                return;
            }

            var message = new StringBuilder("Undefined scan or parse productions for tokens: ");
            bool first = true;
            foreach (var term in undefinedTerminals)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    message.Append(", ");
                }

                message.Append(term.ToString());
            }

            logging.Write(
                new LogEntry
                {
                    Severity = Severity.Warning,
                    Message  = message.ToString(),
                    Origin   = origin,
                });
        }
    }
}


text:
import Ember from 'ember';

export default Ember.Route.extend({
	model() {
		var _this = this;
		var data = [];
		//Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/git/trees/master?recursive=1', function(response) {
		Ember.$.getJSON('', function(response) {
			//var response = data;
			var files = response.tree;
			//var data = [];
			var uid = 1;
			var i = 0;
			var filesLength = files.length;

			//for (var possible_font in files)
			for (; i < filesLength; i++) {
				var possible_font = files[i];
				//debugger;
				if (possible_font.type === "blob" && possible_font.path.includes("patched-fonts") && (possible_font.path.includes(".otf") || possible_font.path.includes(".ttf"))) {
					data.push({
						id: uid,
						type: 'font',
						attributes: {
							uri: possible_font.url,
							size: possible_font.size,
							name: possible_font.path.substring(possible_font.path.lastIndexOf("/") + 1, possible_font.path.length)
						}
					});
					uid++;
				}
			}
			var data = [{
				id: 1,
				type: 'font',
				attributes: {
					uri: 'asdf',
					name: 'asdf name',
					size: 999
				},
				relationships: {}
			}, {
				id: 2,
				type: 'font',
				attributes: {
					uri: 'asdf',
					name: 'asdf name',
					size: 999
				},
				relationships: {}
			}];
			//console.log(data);
			_this.store.push({
				data: data
			});
			/*return Ember.RSVP.hash({
				release: Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest'),
				fonts: [1,2,3] //data
			});*/
		}).then(function(d) {
			//return 'hi';
			/*return Ember.RSVP.hash({
				release: Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest'),
				//fonts: data
				fonts: [1, 2, 3]
			});*/
		});

		//debugger;
		//console.log(this);

		//return "test data from ember index route";
		/*return Ember.RSVP.hash({
			release: Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest'),
			//fonts: [1,2,3]
			fonts: this.store.findAll('font')
			//fonts: Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/git/trees/master?recursive=1')
		});*/
		/*return Ember.RSVP.hash({
			release: Ember.$.getJSON('https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest'),
			fonts: data
		});*/
		return this.store.findAll('font');
	}
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.securityinsights.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** ies for the solution content item. */
@Fluent
public final class MetadataCategories {
    /*
     * domain for the solution content item
     */
    @JsonProperty(value = "domains")
    private List<String> domains;

    /*
     * Industry verticals for the solution content item
     */
    @JsonProperty(value = "verticals")
    private List<String> verticals;

    /**
     * Get the domains property: domain for the solution content item.
     *
     * @return the domains value.
     */
    public List<String> domains() {
        return this.domains;
    }

    /**
     * Set the domains property: domain for the solution content item.
     *
     * @param domains the domains value to set.
     * @return the MetadataCategories object itself.
     */
    public MetadataCategories withDomains(List<String> domains) {
        this.domains = domains;
        return this;
    }

    /**
     * Get the verticals property: Industry verticals for the solution content item.
     *
     * @return the verticals value.
     */
    public List<String> verticals() {
        return this.verticals;
    }

    /**
     * Set the verticals property: Industry verticals for the solution content item.
     *
     * @param verticals the verticals value to set.
     * @return the MetadataCategories object itself.
     */
    public MetadataCategories withVerticals(List<String> verticals) {
        this.verticals = verticals;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
namespace SoftUniCoursesRecommendation
{
    public class UserInCourseScore
    {
        public float Score { get; set; }

        // public float Label { get; set; }
    }
}


text:
--SELECT * FROM LOGs
SELECT * FROM LogDetails


text:
package alraune.back;

import kotlin.text.StringsKt;
import vgrechka.Shared_jvmKt;

import java.util.Arrays;
import java.util.stream.Collectors;

import static alraune.back.Al.rctx;

@SuppressWarnings("unused")
public class ServeDebug_DumpStackByID implements Servant {
    @Override
    public void checkPermissions() {
        AlCheck.isDebug.elseBitch();
    }

    @Override
    public void ignite() {
        String debugTagID = rctx().getFTB().stackID; // TODO:vgrechka Rename
        AlTag tag = AlGlobal.debugTagIDToTag.getIfPresent(debugTagID);
        if (tag == null) throw new IllegalStateException("No tag with debugTagID " + debugTagID);

        String stack = Shared_jvmKt.getStackTraceString(tag.creationStackCapture);
        System.out.println(
            StringsKt.lines(stack).stream()
                .filter(line ->
                            !Arrays.asList(
                                "Tag.<init>",
                                "TagCtor.invoke").stream()
                                .anyMatch(it -> line.contains(it)))
                .collect(Collectors.joining("\n")));
    }
}


text:
; Allows projects to target Windows 2000 and XP
; https://stackoverflow.com/questions/2484511/can-i-use-visual-studio-2010s-c-compiler-with-visual-studio-2008s-c-runtim
; https://stackoverflow.com/questions/19516796/visual-studio-2012-win32-project-targeting-windows-2000/53548116#53548116
; https://social.msdn.microsoft.com/Forums/vstudio/de-DE/30eb0b9e-a905-4be3-ac33-3376766c4500/dll-mit-vs2010-fr-win2000-kompilieren
; https://tedwvc.wordpress.com/2010/11/07/how-to-get-visual-c-2010-mfc-applications-to-run-on-windows-2000/
; http://sharpsetup.eu/documentation/html/003ab441-765b-4eb6-80bd-33ab3aa8c3db.htm
; https://autohotkey.com/board/topic/65431-remove-kb816542-dependency-on-windows-2000/
; https://gist.github.com/xyzzy-17-638/2354412
; https://blog.csdn.net/muy/article/details/51072311
.model flat

.data
__imp__EncodePointer@4 dd dummy
__imp__DecodePointer@4 dd dummy
EXTERNDEF __imp__EncodePointer@4 : DWORD
EXTERNDEF __imp__DecodePointer@4 : DWORD

.code
dummy proc
mov eax, [esp+4]
ret 4
dummy endp

end


text:
class Pos07 {
    static class Foo<X extends Number & Comparable<Number>> {}
    static class DoubleFoo<X extends Number & Comparable<Number>,
                           Y extends Number & Comparable<Number>> {}
    static class TripleFoo<X extends Number & Comparable<Number>,
                           Y extends Number & Comparable<Number>,
                           Z> {}

    Foo<?> fw = new Foo<>();
    DoubleFoo<?,?> dw = new DoubleFoo<>();
    TripleFoo<?,?,?> tw = new TripleFoo<>();
}


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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-smoke-tests</artifactId>
		<version>${revision}</version>
	</parent>
	<artifactId>spring-boot-smoke-test-jooq</artifactId>
	<name>Spring Boot jOOQ Smoke Test</name>
	<description>Spring Boot jOOQ Smoke Test</description>
	<properties>
		<main.basedir>${basedir}/../../..</main.basedir>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jooq</artifactId>
		</dependency>
		<!-- Runtime -->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- Provided -->
		<dependency>
			<groupId>org.jooq</groupId>
			<artifactId>jooq-codegen</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<executions>
					<execution>
						<phase>generate-sources</phase>
						<goals>
							<goal>add-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>gensrc/main/java</source>
							</sources>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>generate</id>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-compiler-plugin</artifactId>
						<executions>
							<execution>
								<id>generate-jooq-utils</id>
								<phase>generate-sources</phase>
								<goals>
									<goal>compile</goal>
								</goals>
								<inherited>false</inherited>
								<configuration>
									<includes>
										<include>smoketest/jooq/util/**</include>
									</includes>
								</configuration>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.codehaus.mojo</groupId>
						<artifactId>sql-maven-plugin</artifactId>
						<version>1.5</version>
						<executions>
							<execution>
								<phase>generate-sources</phase>
								<goals>
									<goal>execute</goal>
								</goals>
							</execution>
						</executions>
						<dependencies>
							<dependency>
								<groupId>com.h2database</groupId>
								<artifactId>h2</artifactId>
								<version>${h2.version}</version>
							</dependency>
						</dependencies>
						<configuration>
							<driver>org.h2.Driver</driver>
							<url>jdbc:h2:~/springbootjooq</url>
							<srcFiles>
								<srcFile>${basedir}/src/main/resources/reset.sql</srcFile>
								<srcFile>${basedir}/src/main/resources/schema.sql</srcFile>
							</srcFiles>
						</configuration>
					</plugin>
					<plugin>
						<groupId>org.jooq</groupId>
						<artifactId>jooq-codegen-maven</artifactId>
						<executions>
							<execution>
								<goals>
									<goal>generate</goal>
								</goals>
							</execution>
						</executions>
						<dependencies>
							<dependency>
								<groupId>com.h2database</groupId>
								<artifactId>h2</artifactId>
								<version>${h2.version}</version>
							</dependency>
						</dependencies>
						<configuration>
							<jdbc>
								<driver>org.h2.Driver</driver>
								<url>jdbc:h2:~/springbootjooq</url>
							</jdbc>
							<generator>
								<name>org.jooq.util.DefaultGenerator</name>
								<database>
									<name>org.jooq.util.h2.H2Database</name>
									<includes>.*</includes>
									<excludes />
									<inputSchema>PUBLIC</inputSchema>
								</database>
								<strategy>
									<name>smoketest.jooq.util.TangleFreeGeneratorStrategy</name>
								</strategy>
								<target>
									<packageName>smoketest.jooq.domain</packageName>
									<directory>${basedir}/gensrc/main/java</directory>
								</target>
								<generate>
									<records>false</records>
								</generate>
							</generator>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
var gulp = require('gulp'),
	npmDist = require('gulp-npm-dist');

gulp.task('copy:img', function() {
	var stream = gulp.src('src/img/**/*')
		.pipe(gulp.dest('dist/img'));
	return stream;
});

gulp.task('copy:js', function() {
	var stream = gulp.src('src/*.js')
		.pipe(gulp.dest('dist'));
	return stream;
});

// copy package.json dependencies to .tmp
gulp.task('copy:libs', function() {
  gulp.src(npmDist({
		"copyUnminified": true
  }), {base:'./node_modules'})
    .pipe(gulp.dest('./demo/vendor'));
});


text:
/**
 * Provide the information needed to insert recommendations into the stored_story table in the database
 *
 * @author Audun Sæther
 * @author Kjersti Fagerholt
 * @author Eivind Halmøy Wolden
 * @author Hanne Marie Trelease
 */

public class DatabaseInsertObject {

	/** The user the recommendations is made for */
	private int userId;
	/** The story that is recommended */
	private String storyId;
	/** The explanation why this story is recommended to this user */
	private String explanation;
	/** Describes if this is a genuine recommendation, or the least recommended story */
	private int false_recommend;
	/** Describe if the recommendation was done by content-based filtering or collaborative filtering */
	private int type_of_recommendation;
	/** The ranking this recommendation has for this user */
	private int ranking;
	/** The value Mahout estimated for this recommendation */
	private double estimatedValue;

	/**
	 * Constructor
	 *
	 * @param userId					the user the recommendations is made for
	 * @param storyId					the story that is recommended
	 * @param explanation				the explanation why this story is recommended to this user
	 * @param false_recommend			describes if this is a genuine recommendation, or the least recommended story
	 * @param type_of_recommendation	describe if the recommendation was done by content-based filtering or collaborative filtering
	 * @param ranking					the ranking this recommendation has for this user
	 * @param estimatedValue			the value Mahout estimated for this recommendation
	 */
	public DatabaseInsertObject(int userId, String storyId, String explanation,
			int false_recommend, int type_of_recommendation, int ranking, double estimatedValue) {
		super();
		this.userId = userId;
		this.storyId = storyId;
		this.explanation = explanation;
		this.false_recommend = false_recommend;
		this.type_of_recommendation = type_of_recommendation;
		this.ranking = ranking;
		this.estimatedValue = estimatedValue;
	}

	/**
	 * Returns the userId
	 * @return	the userId
	 */
	public int getUserId() {
		return userId;
	}

	/**
	 * Returns the storyId
	 * @return	the storyId
	 */
	public String getStoryId() {
		return storyId;
	}

	/**
	 * Returns the explanation
	 * @return	the explanation
	 */
	public String getExplanation() {
		return explanation;
	}

	/**
	 * Returns the false_recommend
	 * @return	the false_recommend
	 */
	public int getFalse_recommend() {
		return false_recommend;
	}

	/**
	 * Returns the type of recommendation
	 * @return	the type recommendation
	 */
	public int getType_of_recommendation() {
		return type_of_recommendation;
	}

	/**
	 * Returns the ranking of this recommendation
	 * @return	the ranking
	 */
	public int getRanking() {
		return ranking;
	}

	/**
	 * Returns the estimated value
	 * @return	the estimated value
	 */
	public double getEstimatedValue() {
		return estimatedValue;
	}

}


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

namespace NAME.Core.Utils
{
    /// <summary>
    /// Represents a <see cref="BinaryWriter"/> that is aware to the Endianess of the Operating System. Performing bytes reversion on numeric values if needed.
    /// </summary>
    /// <seealso cref="System.IO.BinaryWriter" />
    internal class EndianAwareBinaryWriter : BinaryWriter
    {

        private bool isStreamLittleEndian;

        /// <summary>
        /// Initializes a new instance of the <see cref="EndianAwareBinaryWriter"/> class.
        /// </summary>
        /// <param name="s">The stream.</param>
        /// <param name="isStreamLittleEndian">if set to <c>true</c> the stream is ordered in little endian byte order.</param>
        public EndianAwareBinaryWriter(Stream s, bool isStreamLittleEndian)
            : this(s, new UTF8Encoding(false, true), isStreamLittleEndian)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EndianAwareBinaryWriter"/> class.
        /// </summary>
        /// <param name="s">The stream.</param>
        /// <param name="e">The encoding.</param>
        /// <param name="isStreamLittleEndian">if set to <c>true</c> the stream is ordered in little endian byte order.</param>
        public EndianAwareBinaryWriter(Stream s, Encoding e, bool isStreamLittleEndian)
            : this(s, e, false, isStreamLittleEndian)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EndianAwareBinaryWriter"/> class.
        /// </summary>
        /// <param name="s">The stream.</param>
        /// <param name="e">The encoding.</param>
        /// <param name="leaveOpen">true to leave the stream open after the System.IO.BinaryReader object is disposed; otherwise, false.</param>
        /// <param name="isStreamLittleEndian">if set to <c>true</c> the stream is ordered in little endian byte order.</param>
        public EndianAwareBinaryWriter(Stream s, Encoding e, bool leaveOpen, bool isStreamLittleEndian)
            : base(s, e, leaveOpen)
        {
            this.isStreamLittleEndian = isStreamLittleEndian;
        }

        /// <summary>
        /// Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
        /// </summary>
        /// <param name="value">The four-byte signed integer to write.</param>
        public override void Write(int value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        public override void Write(long value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        /// <summary>
        /// Writes a two-byte signed integer to the current stream and advances the stream position by two bytes.
        /// </summary>
        /// <param name="value">The two-byte signed integer to write.</param>
        public override void Write(short value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        /// <summary>
        /// Writes a four-byte unsigned integer to the current stream and advances the stream position by four bytes.
        /// </summary>
        /// <param name="value">The four-byte unsigned integer to write.</param>
        public override void Write(uint value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        /// <summary>
        /// Writes an eight-byte unsigned integer to the current stream and advances the stream position by eight bytes.
        /// </summary>
        /// <param name="value">The eight-byte unsigned integer to write.</param>
        public override void Write(ulong value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        /// <summary>
        /// Writes a two-byte unsigned integer to the current stream and advances the stream position by two bytes.
        /// </summary>
        /// <param name="value">The two-byte unsigned integer to write.</param>
        public override void Write(ushort value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            this.ReverseIfNeededAndWrite(bytes);
        }

        private void ReverseIfNeededAndWrite(byte[] bytes)
        {
            if (this.isStreamLittleEndian != BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            this.OutStream.Write(bytes, 0, bytes.Length);
        }

    }
}


text:
using System.Collections.Generic;

namespace RGiesecke.PlainCsv.Core
{
  public class CsvDictionary<TValue> : OrderedDictionary<string, TValue>
  {
#if DynamicObject
private readonly DynamicDictionaryView<TValue> _DynamicView;

    public dynamic DynamicView
    {
      get { return _DynamicView; }
    }
#endif
    public CsvDictionary()
    {
#if DynamicObject
      _DynamicView = new DynamicDictionaryView<TValue>(this);
#endif
    }

    public CsvDictionary(IEqualityComparer<string> keyComparer)
      : base(keyComparer)
    {
#if DynamicObject
      _DynamicView = new DynamicDictionaryView<TValue>(this);
#endif
    }

    public CsvDictionary(IEnumerable<string> keys, IDictionary<string, TValue> dictionary)
      : base(keys, dictionary)
    {
#if DynamicObject
      _DynamicView = new DynamicDictionaryView<TValue>(this);
#endif
    }

    public CsvDictionary(IEnumerable<string> keys, IDictionary<string, TValue> dictionary, IEqualityComparer<string> keyComparer)
      : base(keys, dictionary, keyComparer)
    {
#if DynamicObject
      _DynamicView = new DynamicDictionaryView<TValue>(this);
#endif
    }
  }

  public class CsvDictionary : CsvDictionary<string>
  {
    public CsvDictionary()
    {
    }

    public CsvDictionary(IEqualityComparer<string> keyComparer) : base(keyComparer)
    {
    }

    public CsvDictionary(IEnumerable<string> keys, IDictionary<string, string> dictionary) : base(keys, dictionary)
    {
    }

    public CsvDictionary(IEnumerable<string> keys, IDictionary<string, string> dictionary, IEqualityComparer<string> keyComparer) : base(keys, dictionary, keyComparer)
    {
    }
  }
}


text:
package seedu.task.logic.parser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Logger;

import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;

import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;

import seedu.task.commons.core.LogsCenter;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.tag.Tag;
import seedu.task.model.tag.UniqueTagList.DuplicateTagException;
import seedu.task.model.task.DateTime;
import seedu.task.model.task.Name;
import seedu.task.model.task.PinTask;
import seedu.task.model.task.TaskPriority;
import seedu.task.model.task.Task;
import seedu.task.model.task.Venue;

//@@author A0139958H

public class TaskParser {

	public static final String SPLIT_STRING_BY_WHITESPACE = "\\s+";
	public static final String REGEX_CASE_INSENSITIVE = "(?i)";
	public static final String WHITE_SPACE = " ";
	public static final String PREFIX_HASHTAG = "#";
	public static final String PREFIX_AT = "@";
	public static final String AT = "at ";
	public static final String FROM = "from ";
	public static final String BY = "by ";
	public static final String NULL = "NULL";

	protected static final Logger logger = LogsCenter.getLogger(TaskParser.class);
	private Task task;
	private String input;

	/**
	 * @param: input arguments from User
	 */
	public TaskParser(String input) {
		this(new Task(), input);
	};

	/**
	 * @param: Task object and input arguments from User
	 */
	public TaskParser(Task task, String input) {
		this.task = task;
		this.input = input;
	};

	/**
	 * Parses the user input with various input validations
	 * @throws IllegalValueException if user input contains invalid arguments
	 * @return: Task object
	 */
	public Task parseInput() throws IllegalValueException {
		input = tagIdentification(input);
		input = dateIdentification(input, FROM, FROM.trim().length());
		input = dateIdentification(input, BY, BY.trim().length());
		validateStartDate();
		processTaskName(input);
		return task;
	}

	/**
	 * Parses the user input to identify tags and venues
	 * @param input arguments from user
	 * @throws IllegalValueException if user input contains invalid arguments
	 * @throws DuplicateTagException if duplicate tag is found
	 * @return: parsed argument
	 */
	protected String tagIdentification(String str) throws DuplicateTagException, IllegalValueException {
		String[] parts = str.split(SPLIT_STRING_BY_WHITESPACE);
		String strWithNoTags = "";
		for (String part : parts) {
			if (part.startsWith(PREFIX_HASHTAG))
				strWithNoTags = matchTag(strWithNoTags, part.substring(1).trim());
			else if (part.startsWith(PREFIX_AT)) {
				if (parseVenue(part.substring(1).trim()))
					task.setVenue(new Venue(String.join(WHITE_SPACE, task.getVenue().toString(), part.substring(1))));
			} else
				strWithNoTags = String.join(WHITE_SPACE, strWithNoTags, part.trim());
		}
		return strWithNoTags;
	}

	/**
	 * Parses the user input to check if its a valid venue
	 * @param input arguments from user
	 * @throws IllegalValueException if venue is empty
	 * @return: true if valid venue or else false
	 */
	protected boolean parseVenue(String str) throws IllegalValueException {
		if (str.isEmpty())
			throw new IllegalValueException(Venue.MESSAGE_VENUE_CONSTRAINTS);
		else if (str.equalsIgnoreCase(NULL)) {
			task.setVenue(new Venue(""));
			return false;
		}
		return true;
	}

	/**
	 * Parses the tags to priority/pin/date or tags
	 * @param input arguments from user, potential tags
	 * @throws IllegalValueException if user input contains invalid arguments
	 * @throws DuplicateTagException if duplicate tag is found
	 * @return: parsed argument
	 */
	protected String matchTag(String str, String tag) throws DuplicateTagException, IllegalValueException {
		if (tag.equalsIgnoreCase(NULL))
			str = dateMatch(str);
		else if (EnumUtils.isValidEnum(TaskPriority.class, tag.toUpperCase()))
			task.setPriority(TaskPriority.valueOf(tag.toUpperCase()));
		else if (EnumUtils.isValidEnum(PinTask.class, tag.toUpperCase()))
			task.setPinTask(PinTask.valueOf(tag.toUpperCase()));
		else
			task.addTag(new Tag(tag));
		return str;
	}

	/**
	 * extracts date type from user input based on matching keywords ('FROM' for start date, 'BY' for end date)
	 * @param input arguments from user, date type (start/end), length of 'FROM' or 'BY' depending on date type
	 * @throws IllegalValueException if start/end date is found to be invalid, multiple start/end dates are found in the user input
	 * @return: parsed argument
	 */
	protected String dateIdentification(String str, String dateType, int strLength) throws IllegalValueException {
		String[] parts = str.split("(?=" + REGEX_CASE_INSENSITIVE + dateType + ")");
		StringJoiner processedString = new StringJoiner(WHITE_SPACE);

		for (int i = 0; i < parts.length; i++) {
			if (startsWithIgnoreCase(parts[i], dateType)) {
				String result = processDateNLP(parts[i], dateType);
				if (!result.equals(parts[i]))
					parts[i] = result.substring(strLength);
			}

			processedString.add(parts[i].trim());
			logger.info("dateIdentification length: " + parts.length + " strWithNoDates:" + processedString.toString() + " part: " + parts[i]);
		}
		return processedString.toString();
	}

	/**
	 * For Update task, removes start/end date from the task
	 * @param input arguments from user
	 * @throws IllegalValueException if 'NULL' is entered to be inserted as a tag. Keyword 'NULL' is reserved and cannot be inserted as a tag
	 * @return: parsed argument
	 */
	protected String dateMatch(String str) throws IllegalValueException {
		String lastWord = StringUtils.stripEnd(str, WHITE_SPACE).substring(str.lastIndexOf(WHITE_SPACE) + 1);

		if (StringUtils.containsIgnoreCase(lastWord, FROM.trim()))
			task.setStartDate(new DateTime(""));
		else if (StringUtils.containsIgnoreCase(lastWord, BY.trim()))
			task.setEndDate(new DateTime(""));
		else
			throw new IllegalValueException(Tag.MESSAGE_HASHTAG_NULL_CONSTRAINTS);
		logger.info("dateMatch Str:" + str);
		return replaceLast(str, lastWord, "");
	}

	/**
	 * Uses Natty Date Natural Language Processing to identify potential start and end dates
	 * @param input arguments from user, date type (start/end)
	 * @throws IllegalValueException if start date/end date is empty or both start date and end dates are same
	 * @return: parsed argument
	 */
	protected String processDateNLP(String str, String dateType) throws IllegalValueException {
		Parser parser = new Parser();
		List<DateGroup> groups = parser.parse(str);
		List<Date> dates = new ArrayList<>();

		if (!groups.isEmpty()) {
			dates.addAll(groups.get(0).getDates());
			Collections.sort(dates);
			String matchingValue = groups.get(0).getText();
			str = str.replace(matchingValue, WHITE_SPACE);
			logger.info("groups size:  " + groups.size() + " Str: " + str + " dates " + Arrays.toString(dates.toArray())
			        + " matchingValue: " + matchingValue);
		}

		if (!dates.isEmpty()) {
			if (dateType.equalsIgnoreCase(FROM))
				setStartDate(dates);
			else if (dateType.equalsIgnoreCase(BY))
				setEndDate(dates);
		}
		return str;
	}

	/**
	 * Sets the start date to the task
	 * @param list of dates
	 * @throws IllegalValueException if start date is empty or both start date and end dates are same
	 */
	protected void setStartDate(List<Date> dates) throws IllegalValueException {
		if (!task.getStartDate().value.isEmpty())
			throw new IllegalValueException(DateTime.MESSAGE_MULTIPLE_START_DATE);

		if (dates.size() == 1) {
			task.setStartDate(new DateTime(dates.get(0)));
		} else if (dates.size() >= 2) {
			if (dates.get(0).compareTo(dates.get(1)) == 0)
				throw new IllegalValueException(DateTime.MESSAGE_DATE_SAME);
			task.setStartDate(new DateTime(dates.get(0)));
			task.setEndDate(new DateTime(dates.get(1)));
		}
	}

	/**
	 * Sets the end date to the task
	 * @param list of dates
	 * @throws IllegalValueException if end date is empty
	 */
	protected void setEndDate(List<Date> dates) throws IllegalValueException {
		if (!task.getEndDate().value.isEmpty())
			throw new IllegalValueException(DateTime.MESSAGE_MULTIPLE_END_DATE);
		task.setEndDate(new DateTime(dates.get(dates.size()-1)));
	}

	/**
	 * checks if the entered start date is valid (falls before end date)
	 * @throws IllegalValueException if start date is found to be invalid
	 */
	protected void validateStartDate() throws IllegalValueException {
		if (!task.getStartDate().value.isEmpty() && !task.getEndDate().value.isEmpty()) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM d HH:mm:ss zzz yyyy");

			LocalDateTime startDate = LocalDateTime.parse(task.getStartDate().value, formatter);
			LocalDateTime endDate = LocalDateTime.parse(task.getEndDate().value, formatter);
			if (!startDate.isBefore(endDate))
				throw new IllegalValueException(DateTime.MESSAGE_INVALID_START_DATE);
		}
	}

	/**
	 * Sets task name for the task
	 * @param input arguments from user
	 * @throws IllegalValueException if name is empty or invalid (contains anything other than alphanumeric values)
	 */
	protected void processTaskName(String str) throws IllegalValueException {
		task.setName(new Name(str));
	}

	/**
	 * checks if string starts with the specified prefix (case insensitive)
	 * @param string to be checked and prefix
	 * @return true if matches otherwise false
	 */
	protected boolean startsWithIgnoreCase(String str, String prefix) {
		return startsWith(str, prefix, true);
	}

	/**
	 * checks if string starts with the specified prefix (case insensitive)
	 * @param string to be checked, prefix, to be case insensitive or not
	 * @return true if matches otherwise false
	 */
	protected boolean startsWith(String str, String prefix, boolean ignoreCase) {
		if (str == null || prefix == null) {
			return (str == null && prefix == null);
		}
		if (prefix.length() > str.length()) {
			return false;
		}
		return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
	}

	/**
	 * replaces last matching word in a string with a replacement
	 * @param original string, match string, replacement string
	 * @return modified string
	 */
	protected String replaceLast(String string, String toReplace, String replacement) {
	    int pos = string.lastIndexOf(toReplace);
	    if (pos > -1) {
	        return string.substring(0, pos)
	             + replacement
	             + string.substring(pos + toReplace.length(), string.length());
	    } else {
	        return string;
	    }
	}
}


text:
from asposepdf import Settings
from com.aspose.pdf import Document
from java.util import Date

class InsertEmptyPageAtEndOfFile:

    def __init__(self):

        dataDir = Settings.dataDir + 'WorkingWithPages/InsertEmptyPageAtEndOfFile/'

        # Open the target document
        pdf = Document(dataDir + 'input1.pdf')

        # insert a empty page in a PDF
        pdf.getPages().add()

        # Save the concatenated output file (the target document)
        pdf.save(dataDir + "output.pdf")

        print "Empty page added successfully!"

if __name__ == '__main__':
    InsertEmptyPageAtEndOfFile()


text:
<?php

namespace App\Providers;

use App\Models\Church;
use App\Models\Group;
use App\Models\User;
use App\Policies\ChurchPolicy;
use App\Policies\GroupPolicy;
use App\Policies\UserPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
//        'App\Model' => 'App\Policies\ModelPolicy',
        Church::class => ChurchPolicy::class,
        User::class => UserPolicy::class,
        Group::class => GroupPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}


text:
package org.apache.cassandra.metrics;

import java.io.IOException;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.service.EmbeddedCassandraService;

import static com.datastax.driver.core.Cluster.*;
import static org.junit.Assert.assertEquals;

public class ClientRequestMetricsTest extends SchemaLoader
{
    private static Cluster cluster;
    private static Session session;

    private static final String KEYSPACE = "junit";
    private static final String TABLE = "clientrequestsmetricstest";

    private static PreparedStatement writePS;
    private static PreparedStatement paxosPS;
    private static PreparedStatement readPS;
    private static PreparedStatement readRangePS;

    private static final ClientRequestMetrics readMetrics = ClientRequestsMetricsHolder.readMetrics;
    private static final ClientWriteRequestMetrics writeMetrics = ClientRequestsMetricsHolder.writeMetrics;

    @BeforeClass
    public static void setup() throws ConfigurationException, IOException
    {
        Schema.instance.clear();

        EmbeddedCassandraService cassandra = new EmbeddedCassandraService();
        cassandra.start();

        cluster = builder().addContactPoint("127.0.0.1").withPort(DatabaseDescriptor.getNativeTransportPort()).build();
        session = cluster.connect();

        session.execute("CREATE KEYSPACE IF NOT EXISTS " + KEYSPACE + " WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
        session.execute("USE " + KEYSPACE);
        session.execute("CREATE TABLE IF NOT EXISTS " + TABLE + " (id int, ord int, val text, PRIMARY KEY (id, ord));");

        writePS = session.prepare("INSERT INTO " + KEYSPACE + '.' + TABLE + " (id, ord, val) VALUES (?, ?, ?);");
        paxosPS = session.prepare("INSERT INTO " + KEYSPACE + '.' + TABLE + " (id, ord, val) VALUES (?, ?, ?) IF NOT EXISTS;");
        readPS = session.prepare("SELECT * FROM " + KEYSPACE + '.' + TABLE + " WHERE id=?;");
        readRangePS = session.prepare("SELECT * FROM " + KEYSPACE + '.' + TABLE + " WHERE id=? AND ord>=? AND ord <= ?;");
    }

    @AfterClass
    public static void teardown()
    {
        cluster.close();
    }

    @Test
    public void testWriteStatement()
    {
        ClientRequestMetricsContainer writeMetricsContainer = new ClientRequestMetricsContainer(writeMetrics);
        ClientRequestMetricsContainer readMetricsContainer = new ClientRequestMetricsContainer(readMetrics);

        executeWrite(1, 1, "aaaa");

        assertEquals(1, writeMetricsContainer.compareLocalRequest());
        assertEquals(0, writeMetricsContainer.compareRemoteRequest());

        assertEquals(0, readMetricsContainer.compareLocalRequest());
        assertEquals(0, readMetricsContainer.compareRemoteRequest());
    }

    @Test
    public void testPaxosStatement()
    {
        ClientRequestMetricsContainer writeMetricsContainer = new ClientRequestMetricsContainer(writeMetrics);
        ClientRequestMetricsContainer readMetricsContainer = new ClientRequestMetricsContainer(readMetrics);

        executePAXOS(2, 2, "aaaa");

        assertEquals(1, readMetricsContainer.compareLocalRequest());
        assertEquals(0, readMetricsContainer.compareRemoteRequest());

        assertEquals(1, writeMetricsContainer.compareLocalRequest());
        assertEquals(0, writeMetricsContainer.compareRemoteRequest());
    }

    @Test
    public void testBatchStatement()
    {
        ClientRequestMetricsContainer writeMetricsContainer = new ClientRequestMetricsContainer(writeMetrics);
        ClientRequestMetricsContainer readMetricsContainer = new ClientRequestMetricsContainer(readMetrics);

        executeBatch(10, 10);

        assertEquals(0, readMetricsContainer.compareLocalRequest());
        assertEquals(0, readMetricsContainer.compareRemoteRequest());

        assertEquals(10, writeMetricsContainer.compareLocalRequest());
        assertEquals(0, writeMetricsContainer.compareRemoteRequest());
    }

    @Test
    public void testReadStatement()
    {
        executeWrite(1, 1, "aaaa");

        ClientRequestMetricsContainer writeMetricsContainer = new ClientRequestMetricsContainer(writeMetrics);
        ClientRequestMetricsContainer readMetricsContainer = new ClientRequestMetricsContainer(readMetrics);

        executeRead(1);

        assertEquals(1, readMetricsContainer.compareLocalRequest());
        assertEquals(0, readMetricsContainer.compareRemoteRequest());

        assertEquals(0, writeMetricsContainer.compareLocalRequest());
        assertEquals(0, writeMetricsContainer.compareRemoteRequest());
    }

    @Test
    public void testRangeStatement()
    {
        executeBatch(1, 100);

        ClientRequestMetricsContainer writeMetricsContainer = new ClientRequestMetricsContainer(writeMetrics);
        ClientRequestMetricsContainer readMetricsContainer = new ClientRequestMetricsContainer(readMetrics);

        executeSlice(1, 0, 99);

        assertEquals(1, readMetricsContainer.compareLocalRequest());
        assertEquals(0, readMetricsContainer.compareRemoteRequest());

        assertEquals(0, writeMetricsContainer.compareLocalRequest());
        assertEquals(0, writeMetricsContainer.compareRemoteRequest());
    }

    private static class ClientRequestMetricsContainer
    {
        private final ClientRequestMetrics metrics;

        private final long localRequests;
        private final long remoteRequests;

        public ClientRequestMetricsContainer(ClientRequestMetrics clientRequestMetrics)
        {
            metrics = clientRequestMetrics;
            localRequests = metrics.localRequests.getCount();
            remoteRequests = metrics.remoteRequests.getCount();
        }

        public long compareLocalRequest()
        {
            return metrics.localRequests.getCount() - localRequests;
        }

        public long compareRemoteRequest()
        {
            return metrics.remoteRequests.getCount() - remoteRequests;
        }
    }

    private void executeWrite(int id, int ord, String val)
    {
        BoundStatement bs = writePS.bind(id, ord, val);
        session.execute(bs);
    }

    private void executePAXOS(int id, int ord, String val)
    {
        BoundStatement bs = paxosPS.bind(id, ord, val);
        session.execute(bs);
    }

    private void executeBatch(int distinctPartitions, int numClusteringKeys)
    {
        BatchStatement batch = new BatchStatement();

        for (int i = 0; i < distinctPartitions; i++)
        {
            for (int y = 0; y < numClusteringKeys; y++)
            {
                batch.add(writePS.bind(i, y, "aaaaaaaa"));
            }
        }
        session.execute(batch);
    }

    private void executeRead(int id)
    {
        BoundStatement bs = readPS.bind(id);
        session.execute(bs);
    }

    private void executeSlice(int id, int start_range, int end_range)
    {
        BoundStatement bs = readRangePS.bind(id, start_range, end_range);
        session.execute(bs);
    }
}


text:
#pragma once
#include "oxygine_include.h"
#include "Actor.h"
#include "core/Mem2Native.h"
#include "res/Resource.h"
#include "pthread.h"

namespace oxygine
{
	DECLARE_SMART(ThreadLoading, spThreadLoading);
	class Resources;
	class Resource;
	class LoadResourcesContextMT;

	class ThreadLoading: public Actor
	{
	public:
		DECLARE_COPYCLONE_NEW(ThreadLoading);

		enum
		{
			COMPLETE = _et_Complete,
		};

		ThreadLoading();
		~ThreadLoading();

		//float getProgress() const;

		bool isCompleted();
		virtual void add(Resources *res);
		virtual void add(Resource *res);

		/**Adds self to 'parent' actor as child and starts loading thread. Removes self automatically from 'parent' when loading is completed*/
		void start(spActor parent);
		//void stop();

		/**Loads resources from current thread WITHOUT creating new (for debug)*/
		void load();
		void unload();

		/**Changes size of updated Texture rectangle each frame. Use it only for tests*/
		void setUpdateSize(int s);

	private:
		static void* _staticThreadFunc(void* t);
		virtual void _threadFunc(LoadResourcesContextMT *ctx);
		void doUpdate(const UpdateState &us);

		Mem2Native _m2n;
		Mutex _m;

		pthread_t _thread;
		//void *_thread;
		volatile bool _threadDone;

		typedef list<Resources*> resources;
		resources _resources;

		typedef list<Resource*> ress;
		ress _ress;
	};
}