text:
'''
MIT License

Copyright (c) 2016 Sebastian Antonsen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''

import argparse
import os
import re
import warnings
import subprocess
import tempfile
import xmltodict
from fdfgen import forge_fdf

# tell user where to get pdftk
# TODO - package this in a sensible way

class Monster():

    def __init__(self, xml, monster_name, position):
        try:
            with open(xml) as xml:
                monsters = xmltodict.parse(xml.read())
            for m in monsters['compendium']['monster']:
                if m['name'] == monster_name:
                    monster = m
                    break
                else:
                    monster = None
        except:
            raise Exception(ValueError, "Could not parse " + xml.name)

        self.monster = monster
        if monster != None:
            self.fields = self._getFields(position)
        else:
            print "{0} is not a recognized monster.".format(monster_name)
            self.fields = [(' '.join(['Monster Name', str(position)]), monster_name)]

    def _getFields(self, position):

        fields = []

        stats = [('STR', self.monster['str']),
                 ('DEX', self.monster['dex']),
                 ('CON', self.monster['con']),
                 ('INT', self.monster['int']),
                 ('WIS', self.monster['wis']),
                 ('CHA', self.monster['cha'])]

        def _statMod(stat):
            stat = int(stat)
            stat_modifier = int((stat - 10) / 2)
            if stat_modifier >= 0:
                stat_modifier = '+' + str(stat_modifier)
            else:
                stat_modifier = str(stat_modifier)

            return stat_modifier

        stat_modifiers = [('STR Modifier', _statMod(self.monster['str'])),
                          ('DEX Modifier', _statMod(self.monster['dex'])),
                          ('CON Modifier', _statMod(self.monster['con'])),
                          ('INT Modifier', _statMod(self.monster['int'])),
                          ('WIS Modifier', _statMod(self.monster['wis'])),
                          ('CHA Modifier', _statMod(self.monster['cha']))]

        def _getXpValue(cr):
            xp_by_cr = [('0',10), ('1/8',25),
                        ('1/4',50), ('1/2',100),
                        ('1',200), ('2',450),
                        ('3',700), ('4',1100),
                        ('5',1800), ('6',2300),
                        ('7',2900), ('8',3900),
                        ('9',5000), ('10',5900),
                        ('11',7200), ('12',8400),
                        ('13',10000), ('14',11500),
                        ('15',13000), ('16',15000),
                        ('17',18000), ('18',20000),
                        ('19',22000), ('20',25000),
                        ('21',33000), ('22',41000),
                        ('23',50000), ('24',62000),
                        ('25',75000), ('26',90000),
                        ('27',105000), ('28',12000),
                        ('29',135000), ('30',155000)]
            for i in xp_by_cr:
                if cr == i[0]:
                    xp_value = "{:,}".format(i[1])
                    break
                else:
                    xp_value = None

            return xp_value

        def _getTypeRace(monster_type):
            if '(' in monster_type:
                m_type, race = monster_type.split('(')
                race = race[:-1]
            else:
                m_type = monster_type
                race = monster_type

            m_type = m_type.capitalize()
            race = race.capitalize()
            return m_type, race

        def _getSpeed():
            speed = self.monster['speed']
            # get the first the highest
            numbers = re.compile('\d+(?:\d+)?')
            speed =  numbers.findall(speed)
            speed = '/'.join([speed[0], max(speed)])

            return speed

        def _getHP():
            hp = self.monster['hp'].split(' ')[0]
            return hp

        def _getAC():
            ac = self.monster['ac'][:2]
            return ac

        info = [('Monster Name', self.monster['name']),
                ('Challenge', self.monster['cr']),
                ('XP', _getXpValue(self.monster['cr'])),
                ('Type', _getTypeRace(self.monster['type'])[0]),
                ('Race', _getTypeRace(self.monster['type'])[1]),
                ('Size', self.monster['size']),
                ('AC', _getAC()),
                ('Speed', _getSpeed()),
                ('Initiative', _statMod(self.monster['dex'])),
                ('HP A', _getHP())]

        def getAttacks():
            # get a list from actions containing only attacks
            attacks_list = []
            # create a string to hold all the attack notes
            attack_notes_strings = []

            actions = self.monster['action']

            # populate the list of all 'attacks'
            # and populate the list of all non 'attacks'
            if isinstance(actions, list):
                for action in actions:
                    if not action['name'] == 'Multiattack':
                        if 'attack' in action:
                            attacks_list.append(action)
                        else:
                            attack_notes_strings.append(action['name'])
            else:
                if 'attack' in actions:
                    attacks_list.append(actions)
                else:
                    attack_notes_strings.append(action['name'])

            # create a list for the attack formatting
            attacks = []
            # populate the list containing the attack formatting
            i = 0
            for idx in range(len(attacks_list)):
                attack = attacks_list[i]
                if idx > 2 :
                    # throw the 4th or higher attack into attack notes
                    # titles only
                    attack_notes_strings.append(attack['name'])

                if attack['name'] == 'Multiattack':
                    continue
                first = 'Attack ' + chr((i) + ord('A'))
                second = 'Attack Bonus ' + chr((i) + ord('A'))
                third = 'Damage/Type ' + chr((i) + ord('A'))

                i+=1

                attacks.append([first, attack['name']])
                #if weapon is versatile (one or two handed) attack['attack']
                #returns a list.
                if not isinstance(attack['attack'], list):
                    attacks.append([second, '+' + attack['attack'].split('|')[1]])
                    attacks.append([third, attack['attack'].split('|')[2]])
                else:
                    one_handed, two_handed = attack['attack']
                    attack_bonus = one_handed.split('|')[1]
                    damage = one_handed.split('|')[2] + '/' + two_handed.split('|')[2]
                    attacks.append([second, '+' + attack_bonus])
                    attacks.append([third, damage])

            # crate a list for all spells

            # find spells
            m = self.monster
            spells = self.monster['spells']
            if spells:
                attack_notes_strings.append(spells)

            # consolidate all the attack notes
            attack_notes_string = ', '.join(attack_notes_strings)
            # add the attack notes to the output of the function
            attacks.extend([('Attack Notes', attack_notes_string)])

            return attacks

        def getTraitsSkills():
            traitsSkills = []
            ts_strings = []
            m = self.monster
            # get save
            if m['save']:
                save = 'Saves: ' + m['save']
                ts_strings.append(save)
            # get skill
            if m['skill']:
                skills = 'Skills: ' + m['skill']
                ts_strings.append(skills)
            # get resist
            if m['resist']:
                resist = 'Resists: ' + m['resist']
                ts_strings.append(resist)
            # get vulnerable
            if m['vulnerable']:
                vulnerable = 'Vulnerable: ' + m['vulnerable']
                ts_strings.append(vulnerable)
            # get immune
            if m['immune']:
                immune = 'Immune: ' + m['immune']
                ts_strings.append(immune)
            # get conditionImmune
            if m['conditionImmune']:
                conditionImmune = 'conditionImmune: ' + m['conditionImmune']
                ts_strings.append(conditionImmune)
            # get senses
            if m['senses']:
                senses = 'Senses: ' + m['senses']
                ts_strings.append(senses)
            # get passive
            if m['passive']:
                passive = 'Passive: ' + m['passive']
                ts_strings.append(passive)

            # get trait headings only
            # apparently some creatures are missing the <trait> tag
            # catch the exception here
            try:
                if m['trait']:
                    traits = m['trait']
                    if isinstance(traits, list):
                        for t in traits:
                            trait = t['name']
                            ts_strings.append(trait)
                    else:
                        trait = m['trait']['name']
                        ts_strings.append(trait)
            except:
                error_string = '{0} does not have a <trait> tag!'.format(m['name'])
                warnings.warn(error_string)
            # get if multiattack
            multiattack = ''
            if isinstance(m['action'], list):
                for action in m['action']:
                    if action['name'] == 'Multiattack':
                        multiattack = 'Multiattack: ' + action['text']

            ts_strings.append(multiattack)

            # check for legendary actions - get titles only
            if 'legendary' in self.monster:
                legendary =  self.monster['legendary']

                if isinstance (legendary, list):
                    for action in legendary:
                        ts_strings.append('(legendary)' + action['name'])
                else:
                    ts_strings.append('(legendary)' + legendary['name'])

            # get spells
            # spells is so big and massive that it is way beyond the scope of
            # this simple encounter sheet

            # get a refernce to what page the monster is listed at in mm
            page = self.monster['page']
            ts_strings.append('Page: ' + page)

            ts_string = ', '.join(ts_strings)
            traitsSkills.extend([('Features/Skills', ts_string)])

            return traitsSkills

        fields.extend(stats)
        fields.extend(stat_modifiers)
        fields.extend(info)
        fields.extend(getAttacks())
        fields.extend(getTraitsSkills())
        # add positional value to field data
        for idx,f in enumerate(fields):
            lst = list(f)
            lst[0] =' '.join([lst[0],str(position)])
            fields[idx] = tuple(lst)

        return fields

class EncounterData():

    def __init__(self, fields):
        '''
        # example of valid fields structure
        fields = [('Encounter Name','DRAGONS DRAGONS DRAGONS'),
                  ('Difficulty','Hard'),
                  ('XP Value',25),
                  ('Location','n/a'),
                  ('Monster Name 0','555-1234')]
        '''

        self.fdf_file = self._createFDF(fields)

    def _createFDF(self, fields):
        fdf = forge_fdf("",fields,[],[],[])
        fdf_file = tempfile.NamedTemporaryFile()
        fdf_file.write(fdf)
        fdf_file.seek(0) # need to rewind the file handle in order to read form it
        # remember to fdf_file.close() at the end of the program

        return fdf_file

    def getData(self):
        return self.fdf_file.name

    def close(self):
        self.fdf_file.close()

def runBashCommand(bashCommand):
    process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()

def getArgs():

    def required_length(nmin,nmax):
        class RequiredLength(argparse.Action):
            def __call__(self, parser, args, values, option_string=None):
                if not nmin<=len(values)<=nmax:
                    msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(f=self.dest,nmin=nmin,nmax=nmax)
                    raise argparse.ArgumentTypeError(msg)
                setattr(args, self.dest, values)
        return RequiredLength

    description = 'Fill out Encounter Sheet with monster data'
    parser = argparse.ArgumentParser(description=description)
    here = os.path.dirname(os.path.realpath(__file__))
    parser.add_argument('monsters', nargs='+', action=required_length(1,3),
                        help='Provide 1 to 3 monster names from the monster manual')
    parser.add_argument('--pdf', type=file,
                        help='A pdf template file to fill out',
                        default = os.path.join(here,'combat_encounter_sheet.pdf'))
    parser.add_argument('--xml', type=file,
                        help='Xml file containing the monster data',
                        default= os.path.join(here, 'monsters.xml'))
    parser.add_argument('--open', action='store_true',
                        help='Opens the file when the program completes')
    parser.add_argument('-o', '--output',
                        help='The output filename',
                        default = os.path.join(os.getcwd(), 'output.pdf'))
    parser.add_argument('-v', '--verbose', action="store_true")
    parser.add_argument('--name', help='Name of the encounter',
                        default=None)
    parser.add_argument('--difficulty', help='Difficulty of the encounter',
                        default='Hard')
    parser.add_argument('--xp', help='xp value of the encounter',
                        default='')
    parser.add_argument('-loc', '--location', help='Location of the encounter',
                        default='')

    args = parser.parse_args()

    return args

def fillOutPdf(data_file, args):
    # define command for running pdftk

    commandString = 'pdftk {0} fill_form {1} output {2} flatten' # && open {2}'
    pdftkCommand = commandString.format(os.path.realpath(args.pdf.name),
                                        data_file,
                                        args.output)

    # define command for opening the created pdf
    openCommand = 'open ' + args.output

    # run the commands
    try:
        runBashCommand(pdftkCommand)
    except:
        raise Exception(NameError, 'pdftk is not installed on this system.' \
                        '\nSee: https://www.pdflabs.com/tools/pdftk-server/ ' \
                        'for instructions on how to install.')
    print "Writing {0}".format(args.output)
    if args.open:
        runBashCommand(openCommand)


text:
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

/**
 * The Enum Teams Async Operation Status.
*/
public enum TeamsAsyncOperationStatus
{
    /**
    * invalid
    */
    INVALID,
    /**
    * not Started
    */
    NOT_STARTED,
    /**
    * in Progress
    */
    IN_PROGRESS,
    /**
    * succeeded
    */
    SUCCEEDED,
    /**
    * failed
    */
    FAILED,
    /**
    * unknown Future Value
    */
    UNKNOWN_FUTURE_VALUE,
    /**
    * For TeamsAsyncOperationStatus values that were not expected from the service
    */
    UNEXPECTED_VALUE
}

redpajama_set_name: RedPajamaGithub


text:
var http=require('http');
var phantom=require('../node-phantom');

var server=http.createServer(function(request,response){
	response.writeHead(200,{"Content-Type": "text/html"});
	response.end('<button onclick="document.getElementsByTagName(\'h1\')[0].innerText=\'Hello Test\';">Test</button>
Hello World
');
}).listen();

exports.testPhantomPageSendEvent=function(beforeExit,assert){
	phantom.create(function(error,ph){
		assert.ifError(error);
		ph.createPage(function(err,page){
			assert.ifError(err);
			page.open('http://localhost:'+server.address().port,function(err,status){
				assert.ifError(err);
				assert.equal(status,'success');
				page.sendEvent('click',30,20,function(err){
					assert.ifError(err);
					page.evaluate(function(){
						return document.getElementsByTagName('h1')[0].innerText;
					},function(err,result){
						assert.ifError(err);
						assert.equal(result,'Hello Test');
						server.close();
						ph.exit();
					});
				});
			});
		});
	});
};


text:
"use strict";
var Layout;
(function (Layout) {

    Layout.contentHost = function (inheritor) {
        var self = Layout.uiElement(inheritor || this, 1);
        self.type = 'contentHost';
        self.addCssProperty('background', false, undefined);
        self.createHtml = function () {
            if (!self.html) {
                self.html = document.createElement('div');
                self.htmlHost = self.html;
                return true
            }
            return false;
        };
        self.measureSelf = function (availableSize) {
            if (self.child) {
                self.child.measure(self.protected.subtractPadding(availableSize));
                return self.protected.addPadding(self.child.desiredSize);
            } else {
                return { width: self.padding.totalWidth, height: self.padding.totalHeight };
            }
        }
        self.arrangeSelf = function (finalSize) {
            if (self.child) {
                var childSize = self.protected.subtractPadding(finalSize);
                childSize.x = self.padding.left;
                childSize.y = self.padding.top;
                self.child.arrange(childSize);
                //var selfSize = self.protected.addBorder(self.padding, self.child.actualSize);
                return finalSize;
            } else {
                return finalSize;// { x: 0, y: 0, width: Math.min(self.padding.totalWidth, finalSize.width), height: Math.min(self.padding.totalHeight, finalSize.height) };
            }
        }
        return self;
    }
})(Layout || (Layout = {}));


text:
import { MutationTree } from 'vuex';

import State from './state';

// Map entity keys generated by normalizr to our state keys.
const entityMapping = {
  categories: 'category',
  comments: 'comment',
  items: 'confession',
  metas: 'facebookInformation',
  tags: 'tag',
};

interface ParamsPayload {
  id: string;
  list: string[];
}

const concat = (type: string) => (state: State, list: string[]) => state[type] = state[type].concat(list);

const updateListsByParam = (type: string) => (state: State, payload: ParamsPayload) =>
  state[type][payload.id] = (state[type][payload.id] || []).concat(payload.list);

const updateEntities = (state: State, entities: any) => {
  Object
    .keys(entityMapping)
    .map((key) => {
      state[key] = { ...state[key], ...entities[entityMapping[key]] };
    });
};

export default {
  updateEntities,
  updateFeatured: concat('featured'),
  updateLatest: concat('latest'),
  updateListsByCategory: updateListsByParam('listsByCategory'),
  updateListsByKeyword: updateListsByParam('listsByKeyword'),
  updateListsByTag: updateListsByParam('listsByTag'),
  updatePopular: concat('popular'),
};


text:
package org.onosproject.store.device.impl;

import org.onosproject.net.DeviceId;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.store.impl.Timestamped;

import com.google.common.base.MoreObjects;

/**
 * Information published by GossipDeviceStore to notify peers of a port
 * status change event.
 */
public class InternalPortStatusEvent {

    private final ProviderId providerId;
    private final DeviceId deviceId;
    private final Timestamped<PortDescription> portDescription;

    protected InternalPortStatusEvent(
            ProviderId providerId,
            DeviceId deviceId,
            Timestamped<PortDescription> portDescription) {
        this.providerId = providerId;
        this.deviceId = deviceId;
        this.portDescription = portDescription;
    }

    public DeviceId deviceId() {
        return deviceId;
    }

    public ProviderId providerId() {
        return providerId;
    }

    public Timestamped<PortDescription> portDescription() {
        return portDescription;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .add("providerId", providerId)
                .add("deviceId", deviceId)
                .add("portDescription", portDescription)
                .toString();
    }

    // for serializer
    protected InternalPortStatusEvent() {
        this.providerId = null;
        this.deviceId = null;
        this.portDescription = null;
    }
}


text:
package iso20022

// Choice of reference.
type References51Choice struct {

	// Unambiguous identification of the transaction as known by the account owner (or the instructing party managing the account).
	AccountOwnerTransactionIdentification *RestrictedFINXMax16Text `xml:"AcctOwnrTxId"`

	// Unambiguous identification of the transaction as known by the account servicer.
	AccountServicerTransactionIdentification *RestrictedFINXMax16Text `xml:"AcctSvcrTxId"`

	// Collective reference identifying a set of messages.
	PoolIdentification *RestrictedFINXMax16Text `xml:"PoolId"`

	// Identification of a transaction assigned by a market infrastructure other than a central securities depository, for example, Target2-Securities.
	MarketInfrastructureTransactionIdentification *RestrictedFINXMax16Text `xml:"MktInfrstrctrTxId"`

	// Identification of the transaction assigned by the processor of the instruction other than the account owner, the account servicer and the market infrastructure.
	ProcessorTransactionIdentification *RestrictedFINXMax16Text `xml:"PrcrTxId"`
}

func (r *References51Choice) SetAccountOwnerTransactionIdentification(value string) {
	r.AccountOwnerTransactionIdentification = (*RestrictedFINXMax16Text)(&value)
}

func (r *References51Choice) SetAccountServicerTransactionIdentification(value string) {
	r.AccountServicerTransactionIdentification = (*RestrictedFINXMax16Text)(&value)
}

func (r *References51Choice) SetPoolIdentification(value string) {
	r.PoolIdentification = (*RestrictedFINXMax16Text)(&value)
}

func (r *References51Choice) SetMarketInfrastructureTransactionIdentification(value string) {
	r.MarketInfrastructureTransactionIdentification = (*RestrictedFINXMax16Text)(&value)
}

func (r *References51Choice) SetProcessorTransactionIdentification(value string) {
	r.ProcessorTransactionIdentification = (*RestrictedFINXMax16Text)(&value)
}


text:
<ion-header>
    <ion-navbar>
        <ion-title>รายละเอียดสินค้า</ion-title>
    </ion-navbar>
</ion-header>

<ion-content class="contact-card-content">

    <ion-slides class="contact-slides" pager="true" autoplay="5000" loop="false">
        <ion-slide class="contact-slide" *ngFor="let image of product.images">
            <background-image class="slide-image" [src]="image"></background-image>
        </ion-slide>
    </ion-slides>
    <ion-row class="contact-details-row" wrap>
        <ion-col no-padding width-65>

{{ product.productdetail.name }}

        </ion-col>
        <ion-col no-padding width-35 class="rating-col">

        </ion-col>
        <ion-col no-padding width-100>

                {{ product.productdetail.detail }}

        </ion-col>
    </ion-row>

    <ion-list class="details-list">

        <ion-item class="detail-item">
            <ion-avatar item-left>
                <ion-icon name="ios-cash-outline"></ion-icon>
            </ion-avatar>
            {{ product.productdetail.price }} ฿

        </ion-item>
        <ion-item class="detail-item" *ngFor="let delivery of product.productdetail.deliverytype">
            <ion-avatar item-left>
                <ion-icon name="ios-cube-outline"></ion-icon>
            </ion-avatar>
            {{ delivery.name }}
            {{ delivery.desc }}
        </ion-item>
        <ion-item class="detail-item">

                <ion-icon name="md-pricetags"></ion-icon> {{' โปรโมชั่นสินค้า' | translate}}

            เมือซื้อเสื้อยีนส์ 1 แถม กางเกงยีนส์ขาสั้น 1 ตัว
        </ion-item>
        โปรดเลือกขนาด
        <ion-list class="radio-tags" radio-group>
            <ion-item class="radio-tag">
                <ion-label>S</ion-label>
                <ion-radio value="s"></ion-radio>
            </ion-item>
            <ion-item class="radio-tag">
                <ion-label>
                    M
                </ion-label>
                <ion-radio value="m"></ion-radio>
            </ion-item>
            <ion-item class="radio-tag">
                <ion-label>
                    L
                </ion-label>
                <ion-radio value="l"></ion-radio>
            </ion-item>
            <ion-item class="radio-tag">
                <ion-label>
                    XL
                </ion-label>
                <ion-radio value="xl"></ion-radio>
            </ion-item>
        </ion-list>

    </ion-list>

สินค้าที่เกี่ยวข้อง

    <ion-scroll scrollX="true" class="horizontal-categories">
        <ion-row class="categories-row">
            <ion-col width-30 class="horizontal-item" *ngFor="let item of product.productrelate">
                <preload-image [ratio]="{w:1, h:1}" [src]="item.img" title="item.name"></preload-image>

{{item.name}}

{{item.price | number}} ฿

            </ion-col>
        </ion-row>
    </ion-scroll>
</ion-content>

<ion-footer>
    <ion-toolbar color="warning">

            <ion-buttons>
                <button ion-button icon-left (click)="goToSchedulePage()">
        <ion-icon name="cart"></ion-icon>ใส่ตะกร้า
      </button>
            </ion-buttons>

    </ion-toolbar>
</ion-footer>


text:
package entities

import persistence.entities.{SimpleQuestion, Question, SimpleSurvey, Survey}
import spray.json.DefaultJsonProtocol

object JsonProtocol extends DefaultJsonProtocol {
  implicit val surveyFormat = jsonFormat2(Survey)
  implicit val simpleSurveyFormat = jsonFormat1(SimpleSurvey)

  implicit val questionFormat = jsonFormat2(Question)
  implicit val simpleQuestionFormat = jsonFormat1(SimpleQuestion)
}


text:
/*
  mixin-js-flags.js 0.1.5
  (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/
  License: MIT (http://www.opensource.org/licenses/mit-license.php)
  Dependencies: Mixin.Core
*/
(function() {
  return (function(factory) {
    // AMD
    if (typeof define === 'function' && define.amd) {
      return define('mixin-js-flags', ['mixin-js'], factory);
    }
    // CommonJS/NodeJS or No Loader
    else {
      return factory.call(this);
    }
  })(function() {'__REPLACE__'; return Mixin;});
}).call(this);


text:
# frozen_string_literal: true

require 'pry-byebug'

require 'simplecov'

if ENV['CI']
	require 'simplecov-cobertura'
	SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter
end

SimpleCov.start

RSpec.configure do |config|
	config.example_status_persistence_file_path = "#{__dir__}/examples.txt"
end

require_relative '../lib/flame'

Dir["#{__dir__}/**/spec_helper.rb"].sort.each do |spec_helper|
	next if spec_helper == __FILE__
	next if spec_helper.include?('require_dirs')

	require spec_helper
end

def transform_words_into_regexp(*words)
	words.map { |word| "(?=.*#{Regexp.escape(word)})" }.join
end

RSpec::Matchers.define :match_words do |*words|
	regexp = transform_words_into_regexp(*words.flatten)

	match do |actual|
		actual.match(/#{regexp}/m)
	end

	diffable
end


text:
package edu.wfu.inotado.mock;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.sakaiproject.service.gradebook.shared.AssessmentNotFoundException;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException;
import org.sakaiproject.service.gradebook.shared.CategoryDefinition;
import org.sakaiproject.service.gradebook.shared.CommentDefinition;
import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException;
import org.sakaiproject.service.gradebook.shared.GradeDefinition;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.service.gradebook.shared.InvalidGradeException;
import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException;

public class GradebookServiceMock implements GradebookService{

	@Override
	public void addAssignment(String arg0, Assignment arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void addExternalAssessment(String arg0, String arg1, String arg2,
			String arg3, double arg4, Date arg5, String arg6)
			throws GradebookNotFoundException,
			ConflictingAssignmentNameException, ConflictingExternalIdException,
			AssignmentHasIllegalPointsException {
		// TODO Auto-generated method stub

	}

	@Override
	public void addExternalAssessment(String arg0, String arg1, String arg2,
			String arg3, Double arg4, Date arg5, String arg6, Boolean arg7)
			throws GradebookNotFoundException,
			ConflictingAssignmentNameException, ConflictingExternalIdException,
			AssignmentHasIllegalPointsException {
		// TODO Auto-generated method stub

	}

	@Override
	public void addGradebook(String arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean checkStudentsNotSubmitted(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean checkStuendsNotSubmitted(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean currentUserHasEditPerm(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean currentUserHasGradeAllPerm(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean currentUserHasGradingPerm(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean currentUserHasViewOwnGradesPerm(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void deleteGradebook(String arg0) throws GradebookNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void finalizeGrades(String arg0) throws GradebookNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public Assignment getAssignment(String arg0, String arg1)
			throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Assignment getAssignment(String arg0, Long arg1)
			throws AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Double getAssignmentScore(String arg0, String arg1, String arg2)
			throws GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Double getAssignmentScore(String arg0, Long arg1, String arg2)
			throws GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CommentDefinition getAssignmentScoreComment(String arg0,
			String arg1, String arg2) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CommentDefinition getAssignmentScoreComment(String arg0, Long arg1,
			String arg2) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getAssignmentScoreString(String arg0, String arg1, String arg2)
			throws GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getAssignmentScoreString(String arg0, Long arg1, String arg2)
			throws GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getAssignments(String arg0) throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getAverageCourseGrade(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getCalculatedCourseGrade(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getCalculatedCourseGrade(String arg0, boolean arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getCategories(Long arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CategoryDefinition> getCategoryDefinitions(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getEnteredCourseGrade(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public GradeDefinition getGradeDefinitionForStudentForItem(String arg0,
			Long arg1, String arg2) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getGradeEntryType(String arg0) throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getGradeViewFunctionForUserForStudentForItem(String arg0,
			Long arg1, String arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getGradeViewFunctionForUserForStudentForItem(String arg0,
			String arg1, String arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object getGradebook(String arg0) throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getGradebookDefinitionXml(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<GradeDefinition> getGradesForStudentsForItem(String arg0,
			Long arg1, List<String> arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getImportCourseGrade(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getImportCourseGrade(String arg0, boolean arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getLowestPossibleGradeForGbItem(String arg0, Long arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Assignment> getViewableAssignmentsForCurrentUser(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map getViewableSectionUuidToNameMap(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, String> getViewableStudentsForItemForCurrentUser(
			String arg0, Long arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, String> getViewableStudentsForItemForUser(String arg0,
			String arg1, Long arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> identifyStudentsWithInvalidGrades(String arg0,
			Map<String, String> arg1) throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isAssignmentDefined(String arg0, String arg1)
			throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isExternalAssignmentDefined(String arg0, String arg1)
			throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isGradableObjectDefined(Long arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isGradeValid(String arg0, String arg1)
			throws GradebookNotFoundException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isGradebookDefined(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public PointsPossibleValidation isPointsPossibleValid(String arg0,
			Assignment arg1, Double arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isUserAbleToGradeItemForStudent(String arg0, Long arg1,
			String arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUserAbleToGradeItemForStudent(String arg0, String arg1,
			String arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUserAbleToViewItemForStudent(String arg0, Long arg1,
			String arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUserAbleToViewItemForStudent(String arg0, String arg1,
			String arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUserAllowedToGrade(String arg0, String arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUserAllowedToGradeAll(String arg0, String arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void mergeGradebookDefinitionXml(String arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeAssignment(Long arg0)
			throws StaleObjectModificationException {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeCategory(Long arg0)
			throws StaleObjectModificationException {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeExternalAssessment(String arg0, String arg1)
			throws GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void saveGradeAndCommentForStudent(String arg0, Long arg1,
			String arg2, String arg3, String arg4)
			throws InvalidGradeException, GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void saveGradesAndComments(String arg0, Long arg1,
			List<GradeDefinition> arg2) throws InvalidGradeException,
			GradebookNotFoundException, AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setAssignmentScore(String arg0, String arg1, String arg2,
			Double arg3, String arg4) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setAssignmentScoreComment(String arg0, String arg1,
			String arg2, String arg3) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setAssignmentScoreString(String arg0, String arg1, String arg2,
			String arg3, String arg4) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setAvailableGradingScales(Collection arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setDefaultGradingScale(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void transferGradebookDefinitionXml(String arg0, String arg1,
			String arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateAssignment(String arg0, String arg1, Assignment arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateExternalAssessment(String arg0, String arg1, String arg2,
			String arg3, double arg4, Date arg5)
			throws GradebookNotFoundException, AssessmentNotFoundException,
			ConflictingAssignmentNameException,
			AssignmentHasIllegalPointsException {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateExternalAssessment(String arg0, String arg1, String arg2,
			String arg3, Double arg4, Date arg5)
			throws GradebookNotFoundException, AssessmentNotFoundException,
			ConflictingAssignmentNameException,
			AssignmentHasIllegalPointsException {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateExternalAssessmentScore(String arg0, String arg1,
			String arg2, Double arg3) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateExternalAssessmentScores(String arg0, String arg1,
			Map arg2) throws GradebookNotFoundException,
			AssessmentNotFoundException {
		// TODO Auto-generated method stub

	}}


text:
require_relative "package"
require_relative "../mixin/uris"

class Chef
  class Resource
    class CabPackage < Chef::Resource::Package
      include Chef::Mixin::Uris
      unified_mode true

      provides :cab_package

      description "Use the **cab_package** resource to install or remove Microsoft Windows cabinet (.cab) packages."
      introduced "12.15"

      allowed_actions :install, :remove

      property :package_name, String,
        description: "An optional property to set the package name if it differs from the resource block's name.",
        identity: true

      property :version, String,
        description: "The version of a package to be installed or upgraded."

      property :source, String,
        description: "The local file path or URL for the CAB package.",
        coerce: (proc do |s|
          unless s.nil?
            uri_scheme?(s) ? s : Chef::Util::PathHelper.canonical_path(s, false)
          end
        end),
        default: lazy { package_name }, default_description: "The package name."
    end
  end
end


text:
class CreateKeywords < ActiveRecord::Migration
  def self.up
    create_table :keywords do |t|
      t.string :text
      t.integer :participant_id

      t.timestamps
    end

    add_column :notifications, :keyword_id, :integer
  end

  def self.down
    drop_table :keywords
    remove_column :notifications, :keyword_id
  end
end


text:
package com.github.dannil.scbjavaclient.client.livingconditions.families;

import java.util.Locale;

import com.github.dannil.scbjavaclient.client.AbstractContainerClient;
import com.github.dannil.scbjavaclient.client.livingconditions.families.adoptions.LivingConditionsFamiliesAdoptionsClient;
import com.github.dannil.scbjavaclient.client.livingconditions.families.housing.LivingConditionsFamiliesHousingClient;
import com.github.dannil.scbjavaclient.client.livingconditions.families.legalguardians.LivingConditionsFamiliesLegalGuardiansClient;
import com.github.dannil.scbjavaclient.client.livingconditions.families.siblings.LivingConditionsFamiliesSiblingsClient;
import com.github.dannil.scbjavaclient.communication.URLEndpoint;

/**
 *
Client which handles living conditions families data fetching.

 *
 * @since 0.2.0
 */
public class LivingConditionsFamiliesClient extends AbstractContainerClient {

    /**
     *
Default constructor. Initializes values and creates sub-clients.

     */
    public LivingConditionsFamiliesClient() {
        super();

        addClient("adoptions", new LivingConditionsFamiliesAdoptionsClient());
        addClient("housing", new LivingConditionsFamiliesHousingClient());
        addClient("legalguardians", new LivingConditionsFamiliesLegalGuardiansClient());
        addClient("siblings", new LivingConditionsFamiliesSiblingsClient());
    }

    /**
     *
Overloaded constructor.

     *
     * @param locale
     *            the Locale for this client
     */
    public LivingConditionsFamiliesClient(Locale locale) {
        this();

        setLocale(locale);
    }

    /**
     *
Retrieve the client for interacting with living conditions families adoptions
     * data.

     *
     * @return a client for living conditions families adoptions data
     */
    public LivingConditionsFamiliesAdoptionsClient adoptions() {
        return (LivingConditionsFamiliesAdoptionsClient) getClient("adoptions");
    }

    /**
     *
Retrieve the client for interacting with living conditions families housing
     * data.

     *
     * @return a client for living conditions families housing data
     */
    public LivingConditionsFamiliesHousingClient housing() {
        return (LivingConditionsFamiliesHousingClient) getClient("housing");
    }

    /**
     *
Retrieve the client for interacting with living conditions families legal
     * guardians data.

     *
     * @return a client for living conditions families legal guardians data
     */
    public LivingConditionsFamiliesLegalGuardiansClient legalGuardians() {
        return (LivingConditionsFamiliesLegalGuardiansClient) getClient("legalguardians");
    }

    /**
     *
Retrieve the client for interacting with living conditions families siblings
     * data.

     *
     * @return a client for living conditions families siblings data
     */
    public LivingConditionsFamiliesSiblingsClient siblings() {
        return (LivingConditionsFamiliesSiblingsClient) getClient("siblings");
    }

    @Override
    public URLEndpoint getUrl() {
        return getRootUrl().append("LE/LE0102/");
    }

}


text:
import contract = require('truffle-contract');
import { W3 } from './';
import SolidityCoder = require('web3/lib/solidity/coder.js');

/**
 * Base contract for all Soltsice contracts
 */
export class SoltsiceContract {
  public static silent: boolean = false;
  public transactionHash: Promise<string>;
  public w3: W3;
  protected _Contract: any;
  /** Truffle-contract instance. Use it if Soltsice doesn't support some features yet */
  protected _instance: any;
  protected _instancePromise: Promise<any>;
  protected _sendParams: W3.TX.TxParams;

  protected static newDataImpl(w3?: W3, tokenArtifacts?: any, constructorParams?: W3.TX.ContractDataType[]): string {
    if (!w3) {
      w3 = W3.default;
    }
    let ct = w3.web3.eth.contract(tokenArtifacts.abi);
    let data = ct.new.getData(...constructorParams!, { data: tokenArtifacts.bytecode });
    return data;
  }

  protected constructor(
    web3?: W3,
    tokenArtifacts?: any,
    constructorParams?: W3.TX.ContractDataType[],
    deploymentParams?: string | W3.TX.TxParams | object,
    link?: SoltsiceContract[]
  ) {
    if (!web3) {
      web3 = W3.default;
    }
    this.w3 = web3;

    if (
      typeof deploymentParams === 'string' &&
      deploymentParams !== '' &&
      !W3.isValidAddress(deploymentParams as string)
    ) {
      throw 'Invalid deployed contract address';
    }

    this._Contract = contract(tokenArtifacts);
    this._Contract.setProvider(web3.currentProvider);

    function instanceOfTxParams(obj: any): obj is W3.TX.TxParams {
      return 'from' in obj && 'gas' in obj && 'gasPrice' in obj && 'value' in obj;
    }

    let linkage = new Promise<any>(async (resolve, reject) => {
      if (link && link.length > 0) {
        let network = +(await this.w3.networkId);
        this._Contract.setNetwork(network);
        link.forEach(async element => {
          let inst = await element._instancePromise;
          this._Contract.link(element._Contract.contractName, inst.address);
        });
        resolve(true);
      } else {
        resolve(true);
      }
    });

    let instance = new Promise<any>(async (resolve, reject) => {
      await linkage;
      if (this.w3.defaultAccount) {
        this._sendParams = W3.TX.txParamsDefaultSend(this.w3.defaultAccount);
        if ((await this.w3.networkId) !== '1') {
          this._sendParams.gasPrice = 20000000000; // 20 Gwei, tests are too slow with the 2 Gwei default one
        }
      }

      let useDeployed = async () => {
        let network = +(await this.w3.networkId);
        this._Contract.setNetwork(network);
        this._Contract
          .deployed()
          .then(inst => {
            this.transactionHash = inst.transactionHash;
            if (!SoltsiceContract.silent) {
              console.log('SOLTSICE: USING DEPLOYED CONTRACT', this.constructor.name, ' at ', deploymentParams!);
            }
            resolve(inst);
          })
          .catch(err => {
            reject(err);
          });
      };

      let useExisting = (address: string) => {
        if (!SoltsiceContract.silent) {
          console.log('SOLTSICE: USING EXISTING CONTRACT', this.constructor.name, ' at ', deploymentParams!);
        }
        this._Contract
          .at(address)
          .then(inst => {
            this.transactionHash = inst.transactionHash;
            resolve(inst);
          })
          .catch(err => {
            reject(err);
          });
      };

      if (!deploymentParams) {
        useDeployed();
      } else if (typeof deploymentParams === 'string') {
        useExisting(deploymentParams!);
      } else if (instanceOfTxParams(deploymentParams)) {
        this._Contract
          .new(...constructorParams!, deploymentParams)
          .then(inst => {
            if (!SoltsiceContract.silent) {
              console.log('SOLTSICE: DEPLOYED NEW CONTRACT ', this.constructor.name, ' at ', inst.address);
            }
            this.transactionHash = inst.transactionHash;
            resolve(inst);
          })
          .catch(err => {
            reject(err);
          });
      } else if ((<any>deploymentParams).address && typeof (<any>deploymentParams).address === 'string') {
        // support any object with address property
        useExisting((<any>deploymentParams).address);
      }
    });

    this._instancePromise = instance.then(i => {
      this._instance = i;
      return i;
    });
  }

  public get address(): string {
    return this._instance.address;
  }

  public get instance(): any {
    return this._instance;
  }

  /** Default tx params for sending transactions. */
  public get sendTxParams() {
    return this._sendParams;
  }

  /** Send a transaction to the fallback function */
  public async sendTransaction(txParams?: W3.TX.TxParams): Promise<W3.TX.TransactionResult> {
    txParams = txParams || this._sendParams;
    if (!txParams) {
      throw new Error('Default tx parameters are not set.');
    }
    let instance = await this.instance;
    return instance.sendTransaction(txParams);
  }

  public async parseLogs(logs: W3.Log[]): Promise<W3.Log[]> {
    let web3 = this.w3;
    let inst = await this.instance;
    let abi = inst.abi;

    return logs!
      .map(log => {
        let logABI: any = null;

        for (let i = 0; i < abi.length; i++) {
          let item = abi[i];
          if (item.type !== 'event') {
            continue;
          }
          // tslint:disable-next-line:max-line-length
          let signature =
            item.name +
            '(' +
            item.inputs
              .map(function(input: any) {
                return input.type;
              })
              .join(',') +
            ')';
          let hash = this.w3.web3.sha3(signature);
          if (hash === log.topics![0]) {
            logABI = item;
            break;
          }
        }
        if (logABI != null) {
          // Adapted from truffle-contract
          let copy = Object.assign({}, log);

          let decode = (fullABI, indexed, data) => {
            let _inputs = fullABI.inputs.filter(function(input: any) {
              return input.indexed === indexed;
            });

            let partial = {
              inputs: _inputs,
              name: fullABI.name,
              type: fullABI.type,
              anonymous: fullABI.anonymous
            };

            let types = partial.inputs.map(x => x.type);
            let params = SolidityCoder.decodeParams(types, data);
            let temp = {};

            for (let index = 0; index < _inputs.length; index++) {
              temp[_inputs[index].name] = params[index];
            }

            return temp;
          };

          let argTopics = logABI.anonymous ? copy.topics : copy.topics!.slice(1);
          let indexedData = argTopics!
            .map(function(topics: string) {
              return topics.slice(2);
            })
            .join('');
          // tslint:disable-next-line:max-line-length
          let indexedParams = decode(logABI, true, indexedData);

          let notIndexedData = copy.data!.replace('0x', '');
          // tslint:disable-next-line:max-line-length
          let notIndexedParams = decode(logABI, false, notIndexedData);

          copy.event = logABI.name;

          copy.args = logABI.inputs.reduce(function(acc: any, current: any) {
            let val = indexedParams[current.name];

            if (val === undefined) {
              val = notIndexedParams[current.name];
            }

            acc[current.name] = val;
            return acc;
          }, {});

          Object.keys(copy.args).forEach(function(key: any) {
            let val = copy.args[key];

            // We have BN. Convert it to BigNumber
            if (val.constructor.isBN) {
              copy.args[key] = web3.toBigNumber('0x' + val.toString(16));
            }
          });

          delete copy.data;
          delete copy.topics;

          return copy;
        } else {
          return undefined;
        }
      })
      .filter(d => d) as W3.Log[];
  }

  public async parseReceipt(receipt: W3.TransactionReceipt): Promise<W3.Log[]> {
    if (!receipt.logs) {
      return [];
    }
    return this.parseLogs(receipt.logs);
  }

  /** Get transaction result by hash. Returns receipt + parsed logs. */
  public getTransactionResult(txHash: string): Promise<W3.TX.TransactionResult> {
    return new Promise<W3.TX.TransactionResult>((resolve, reject) => {
      this.w3.web3.eth.getTransactionReceipt(txHash, async (err, receipt) => {
        if (err) {
          reject(err);
        } else {
          if (!receipt) {
            reject('Receipt is falsy, transaction does not exists or was not mined yet.');
          } else {
            try {
              let result: W3.TX.TransactionResult = {} as W3.TX.TransactionResult;
              result.tx = receipt.transactionHash;
              result.receipt = receipt;
              result.logs = await this.parseReceipt(receipt);
              resolve(result);
            } catch (e) {
              reject({ error: e, description: 'Unhandled exception' });
            }
          }
        }
      });
    });
  }

  public async waitTransactionReceipt(hashString: string): Promise<W3.TX.TransactionResult> {
    return new Promise<W3.TX.TransactionResult>((accept, reject) => {
      var timeout = 240000;
      var start = new Date().getTime();
      let makeAttempt = () => {
        this.w3.web3.eth.getTransactionReceipt(hashString, async (err, receipt) => {
          if (err) {
            return reject(err);
          }

          if (receipt != null) {
            try {
              let result: W3.TX.TransactionResult = {} as W3.TX.TransactionResult;
              result.tx = receipt.transactionHash;
              result.receipt = receipt;
              result.logs = await this.parseReceipt(receipt);
              accept(result);
            } catch (e) {
              reject({ error: e, description: 'Unhandled exception' });
            }
          }

          if (timeout > 0 && new Date().getTime() - start > timeout) {
            return reject(
              new Error('Transaction ' + hashString + " wasn't processed in " + timeout / 1000 + ' seconds!')
            );
          }

          setTimeout(makeAttempt, 1000);
        });
      };

      makeAttempt();
    });
  }

  public async newFilter(fromBlock: number, toBlock?: number): Promise<number> {
    let toBlock1 = toBlock ? this.w3.fromDecimal(toBlock) : 'latest';
    const id = 'W3:' + W3.getNextCounter();
    let filter = await this.w3
      .sendRPC({
        jsonrpc: '2.0',
        method: 'eth_newFilter',
        params: [
          {
            fromBlock: this.w3.fromDecimal(fromBlock),
            toBlock: toBlock1,
            address: await this.address
          }
        ],
        id: id
      })
      .then(async r => {
        if (r.error) {
          throw 'Cannot set filter';
        }
        return r.result as number;
      });
    return this.w3.toBigNumber(filter).toNumber(); // filter
  }

  public async uninstallFilter(filter: number): Promise<boolean> {
    const id = 'W3:' + W3.getNextCounter();
    let ret = await this.w3
      .sendRPC({
        jsonrpc: '2.0',
        method: 'eth_uninstallFilter',
        params: [this.w3.fromDecimal(filter)],
        id: id
      })
      .then(async r => {
        if (r.error) {
          throw 'Cannot uninstall filter';
        }
        return r.result as boolean;
      });
    return ret;
  }

  public async getFilterChanges(filter: number): Promise<W3.Log[]> {
    const id = 'W3:' + W3.getNextCounter();

    let logs = this.w3
      .sendRPC({
        jsonrpc: '2.0',
        method: 'eth_getFilterChanges',
        params: [this.w3.fromDecimal(filter)],
        id: id
      })
      .then(async r => {
        if (r.error) {
          console.log('FILTER ERR: ', r);
          return [];
        }
        console.log('FILTER: ', r);
        let parsed = await this.parseLogs(r.result as W3.Log[]);
        return parsed;
      });
    return logs;
  }

  public async getFilterLogs(filter: number): Promise<W3.Log[]> {
    const id = 'W3:' + W3.getNextCounter();

    let logs = this.w3
      .sendRPC({
        jsonrpc: '2.0',
        method: 'eth_getFilterLogs',
        params: [this.w3.fromDecimal(filter)],
        id: id
      })
      .then(async r => {
        if (r.error) {
          return [];
        }
        let parsed = await this.parseLogs(r.result as W3.Log[]);
        return parsed;
      });
    return logs;
  }

  public async getLogs(fromBlock: number, toBlock?: number): Promise<W3.Log[]> {
    let toBlock1 = toBlock ? this.w3.fromDecimal(toBlock) : 'latest';

    return new Promise<W3.Log[]>(async (resolve, reject) => {
      (await this.instance).allEvents({ fromBlock: fromBlock, toBlock: toBlock1 }).get((error, log) => {
        if (error) {
          reject(error);
        }
        resolve(log);
      });
    });
  }
}


text:
<?php

/**
 * Container for multiple TalkModel objects, also handles
 * collection metadata such as pagination
 */
class TalkModelCollection extends AbstractModelCollection
{
    protected $list = array();
    protected $total;

    /**
     * Take arrays of data and create a collection of models; store metadata
     */
    public function __construct(array $data, $total)
    {
        $this->total = $total;

        // hydrate the model objects if necessary and store to list
        foreach ($data as $item) {
            if (!$item instanceof TalkModel) {
                $item = new TalkModel($item);
            }
            $this->list[] = $item;
        }
    }

    /**
     * Present this collection ready for the output handlers
     *
     * This creates the expected output structure, converting each resource
     * to it's presentable representation and adding the meta fields for totals
     * and pagination
     */
    public function getOutputView($request, $verbose = false)
    {
        // handle the collection first
        $retval['talks'] = [];
        foreach ($this->list as $item) {
            $retval['talks'][] = $item->getOutputView($request, $verbose);
        }

        // add other fields
        $retval['meta'] = $this->addPaginationLinks($request);

        return $retval;
    }

    /**
     * Return the list of talks (internal representation)
     *
     * @return array
     */
    public function getTalks()
    {
        return $this->list;
    }
}


text:
/*
* Hangman chat plugin
* By bumbadadabum and Zarel. Art by crobat.
*/

'use strict';

const permission = 'announce';
const maxMistakes = 6;

class Hangman extends Rooms.RoomGame {
	constructor(room, user, word, hint) {
		super(room);

		if (room.gameNumber) {
			room.gameNumber++;
		} else {
			room.gameNumber = 1;
		}

		this.gameid = 'hangman';
		this.title = 'Hangman';
		this.creator = user.userid;
		this.word = word;
		this.hint = hint;
		this.incorrectGuesses = 0;

		this.guesses = [];
		this.letterGuesses = [];
		this.lastGuesser = '';
		this.wordSoFar = [];

		for (let i = 0; i < word.length; i++) {
			if (/[a-zA-Z]/.test(word[i])) {
				this.wordSoFar.push('_');
			} else {
				this.wordSoFar.push(word[i]);
			}
		}
	}

	guess(word, user) {
		if (user.userid === this.room.game.creator) return user.sendTo(this.room, "You can't guess in your own hangman game.");

		let sanitized = word.replace(/[^A-Za-z ]/g, '');
		let normalized = toId(sanitized);
		if (normalized.length < 1) return user.sendTo(this.room, "Guess too short.");
		if (sanitized.length > 30) return user.sendTo(this.room, "Guess too long.");

		for (let i = 0; i < this.guesses.length; i++) {
			if (normalized === toId(this.guesses[i])) return user.sendTo(this.room, "Your guess has already been guessed.");
		}

		if (sanitized.length > 1) {
			if (!this.guessWord(sanitized, user.name)) {
				user.sendTo(this.room, "Invalid guess");
			} else {
				this.room.send(user.name + " guessed \"" + sanitized + "\"!");
			}
		} else {
			if (!this.guessLetter(sanitized, user.name)) {
				user.sendTo(this.room, "Invalid guess");
			}
		}
	}

	guessLetter(letter, guesser) {
		letter = letter.toUpperCase();
		if (this.guesses.indexOf(letter) >= 0) return false;
		if (this.word.toUpperCase().indexOf(letter) > -1) {
			for (let i = 0; i < this.word.length; i++) {
				if (this.word[i].toUpperCase() === letter) {
					this.wordSoFar[i] = this.word[i];
				}
			}

			if (this.wordSoFar.indexOf('_') < 0) {
				this.incorrectGuesses = -1;
				this.guesses.push(letter);
				this.letterGuesses.push(letter + '1');
				this.lastGuesser = guesser;
				this.finish();
				return true;
			}
			this.letterGuesses.push(letter + '1');
		} else {
			this.incorrectGuesses++;
			this.letterGuesses.push(letter + '0');
		}

		this.guesses.push(letter);
		this.lastGuesser = guesser;
		this.update();
		return true;
	}

	guessWord(word, guesser) {
		let ourWord = toId(this.word);
		let guessedWord = toId(word);
		if (ourWord === guessedWord) {
			for (let i = 0; i < this.wordSoFar.length; i++) {
				if (this.wordSoFar[i] === '_') {
					this.wordSoFar[i] = this.word[i];
				}
			}
			this.incorrectGuesses = -1;
			this.guesses.push(word);
			this.lastGuesser = guesser;
			this.finish();
			return true;
		} else if (ourWord.length === guessedWord.length) {
			this.incorrectGuesses++;
			this.guesses.push(word);
			this.lastGuesser = guesser;
			this.update();
			return true;
		}
		return false;
	}

	hangingMan() {
		return '';
	}

	generateWindow() {
		let result = 0;

		if (this.incorrectGuesses === maxMistakes) {
			result = 1;
		} else if (this.wordSoFar.indexOf('_') < 0) {
			result = 2;
		}

		let output = '
';
		output += '
' + (result === 1 ? 'Too bad! The mon has been hanged.' : (result === 2 ? 'The word has been guessed. Congratulations!' : 'Hangman')) + '
';
		output += '

' + this.hangingMan() + '	';

		let wordString = this.wordSoFar.join('');
		if (result === 1) {
			let word = this.word;
			wordString = wordString.replace(/_+/g, (match, offset) =>
				'' + word.substr(offset, match.length) + ''
			);
		}

		if (this.hint) output += '
(Hint: ' + Tools.escapeHTML(this.hint) + ')
';
		output += '
' + wordString + '
';
		if (this.guesses.length) {
			if (this.letterGuesses.length) {
				output += 'Letters: ' + this.letterGuesses.map(g =>
					'' + Tools.escapeHTML(g[0]) + ''
				).join(', ');
			}
			if (result === 2) {
				output += '
Winner: ' + Tools.escapeHTML(this.lastGuesser);
			} else if (this.guesses[this.guesses.length - 1].length === 1) {
				// last guess was a letter
				output += ' – ' + Tools.escapeHTML(this.lastGuesser) + '';
			} else {
				output += '
Guessed: ' + this.guesses[this.guesses.length - 1] + ' – ' + Tools.escapeHTML(this.lastGuesser) + '';
			}
		}

		output += '

';

		return output;
	}

	display(user, broadcast) {
		if (broadcast) {
			this.room.add('|uhtml|hangman' + this.room.gameNumber + '|' + this.generateWindow());
		} else {
			user.sendTo(this.room, '|uhtml|hangman' + this.room.gameNumber + '|' + this.generateWindow());
		}
	}

	update() {
		this.room.add('|uhtmlchange|hangman' + this.room.gameNumber + '|' + this.generateWindow());

		if (this.incorrectGuesses === maxMistakes) {
			this.finish();
		}
	}

	end() {
		this.room.add('|uhtmlchange|hangman' + this.room.gameNumber + '|
(The game of hangman was ended.)
');
		this.room.add("The game of hangman was ended.");
		delete this.room.game;
	}

	finish() {
		this.room.add('|uhtmlchange|hangman' + this.room.gameNumber + '|
(The game of hangman has ended – scroll down to see the results)
');
		this.room.add('|html|' + this.generateWindow());
		delete this.room.game;
	}
}

exports.commands = {
	hangman: {
		create: 'new',
		new: function (target, room, user) {
			let params = target.split(',');

			if (!this.can(permission, null, room)) return false;
			if (room.hangmanDisabled) return this.errorReply("Hangman is disabled for this room.");
			if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
			if (room.game) return this.errorReply("There is already a game in progress in this room.");

			if (!params) return this.errorReply("No word entered.");
			let word = params[0].replace(/[^A-Za-z '-]/g, '');
			if (word.replace(/ /g, '').length < 1) return this.errorReply("Enter a valid word");
			if (word.length > 30) return this.errorReply("Phrase must be less than 30 characters.");
			if (word.split(' ').some(w => w.length > 20)) return this.errorReply("Each word in the phrase must be less than 20 characters.");
			if (!/[a-zA-Z]/.test(word)) return this.errorReply("Word must contain at least one letter.");

			let hint;
			if (params.length > 1) {
				hint = params.slice(1).join(',').trim();
				if (hint.length > 150) return this.errorReply("Hint too long.");
			}

			room.game = new Hangman(room, user, word, hint);
			room.game.display(user, true);

			return this.privateModCommand("(A game of hangman was started by " + user.name + ".)");
		},
		createhelp: ["/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # & ~"],

		guess: function (target, room, user) {
			if (!target) return this.parse('/help guess');
			if (!room.game || room.game.gameid !== 'hangman') return this.errorReply("There is no game of hangman running in this room.");
			if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");

			room.game.guess(target, user);
		},
		guesshelp: ["/hangman guess [letter] - Makes a guess for the letter entered.",
					"/hangman guess [word] - Same as a letter, but guesses an entire word."],

		stop: 'end',
		end: function (target, room, user) {
			if (!this.can(permission, null, room)) return false;
			if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
			if (!room.game || room.game.gameid !== 'hangman') return this.errorReply("There is no game of hangman running in this room.");

			room.game.end();
			return this.privateModCommand("(The game of hangman was ended by " + user.name + ".)");
		},
		endhelp: ["/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # & ~"],

		disable: function (target, room, user) {
			if (!this.can('tournamentsmanagement', null, room)) return;
			if (room.hangmanDisabled) {
				return this.errorReply("Hangman is already disabled.");
			}
			room.hangmanDisabled = true;
			if (room.chatRoomData) {
				room.chatRoomData.hangmanDisabled = true;
				Rooms.global.writeChatRoomData();
			}
			return this.sendReply("Hangman has been disabled for this room.");
		},

		enable: function (target, room, user) {
			if (!this.can('tournamentsmanagement', null, room)) return;
			if (!room.hangmanDisabled) {
				return this.errorReply("Hangman is already enabled.");
			}
			delete room.hangmanDisabled;
			if (room.chatRoomData) {
				delete room.chatRoomData.hangmanDisabled;
				Rooms.global.writeChatRoomData();
			}
			return this.sendReply("Hangman has been enabled for this room.");
		},

		display: function (target, room, user) {
			if (!room.game || room.game.title !== 'Hangman') return this.errorReply("There is no game of hangman running in this room.");
			if (!this.canBroadcast()) return;
			room.update();

			room.game.display(user, this.broadcasting);
		},

		'': function (target, room, user) {
			return this.parse('/help hangman');
		},
	},

	hangmanhelp: ["/hangman allows users to play the popular game hangman in PS rooms.",
				"Accepts the following commands:",
				"/hangman create [word], [hint] - Makes a new hangman game. Requires: % @ # & ~",
				"/hangman guess [letter] - Makes a guess for the letter entered.",
				"/hangman guess [word] - Same as a letter, but guesses an entire word.",
				"/hangman display - Displays the game.",
				"/hangman end - Ends the game of hangman before the man is hanged or word is guessed. Requires: % @ # & ~",
				"/hangman [enable/disable] - Enables or disables hangman from being started in a room. Requires: # & ~"],

	guess: function (target, room, user) {
		if (!room.game) return this.errorReply("There is no game running in this room.");
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!room.game.guess) return this.errorReply("You can't guess anything in this game.");

		room.game.guess(target, user);
	},
	guesshelp: ["/guess - Shortcut for /hangman guess.", "/hangman guess [letter] - Makes a guess for the letter entered.",
					"/hangman guess [word] - Same as a letter, but guesses an entire word."],
};


text:
using System;
using System.Linq;

namespace Atata
{
    /// <summary>
    /// Provides a set of extensions methods for <see cref="Type"/>.
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// Determines whether the type is subclass of the specified raw generic type (e.g. <c>typeof(List<>)</c>).
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="genericType">Type of the generic.</param>
        /// <returns>
        ///   <c>true</c> if the type is a subclass of the specified raw generic type; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsSubclassOfRawGeneric(this Type type, Type genericType) =>
            type.GetDepthOfInheritanceOfRawGeneric(genericType) != null;

        /// <summary>
        /// Gets the depth of inheritance of the specified raw generic type (e.g. <c>typeof(List<>)</c>).
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="genericType">Type of the generic.</param>
        /// <returns>The depth of inheritance or <see langword="null"/>.</returns>
        public static int? GetDepthOfInheritanceOfRawGeneric(this Type type, Type genericType)
        {
            if (genericType == null)
                return null;

            Type typeToCheck = type;
            int depth = 0;

            while (typeToCheck != null && typeToCheck != typeof(object))
            {
                if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == genericType)
                    return depth;

                typeToCheck = typeToCheck.BaseType;
                depth++;
            }

            return null;
        }

        /// <summary>
        /// Determines whether the type implements the specified generic interface type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="genericType">Type of the generic interface.</param>
        /// <returns>
        ///   <c>true</c> if it implements the generic interface type; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsImplementGenericInterface(this Type type, Type genericType) =>
            type.GetGenericInterfaceType(genericType) != null;

        /// <summary>
        /// Gets an actual type of the specified generic interface that this type implements.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="genericType">Type of the generic interface.</param>
        /// <returns>The actual generic interface type or <see langword="null"/>.</returns>
        public static Type GetGenericInterfaceType(this Type type, Type genericType) =>
            type.GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == genericType);
    }
}


text:
ScriptLoader.load('ModalBox', 'Overlay');

var GoodsCompare = new Class({

	initialize:function (el) {
		this.element = $(el);

		// инициализация информера в шапке + мини-папапа информера
		this.informer();

		// обработчик по ссылке "сравнить" из блоков товаров
		$$('a[name=to_compare]').addEvent('click', function(e) {
			e.stop();
			var id = e.target.getProperty('data-goods-id');
			this.add(id);
		}.bind(this));
	},

	informer: function() {
		var url = this.element.getProperty('data-informer-url')+'?html&' + Math.floor((Math.random()*10000));
		this.element.set(
			'load',
			{
				method: 'get',
				'onFailure': this.error.bind(this),
				'onComplete': this.init.bind(this)
			});
		this.element.load(url);
	},

	init: function() {
		// если информер не пустой - инициализация обработчиков
		if (this.element.getElement('.compare_link')) {

			// показ мини-попапа сравнения по клику на кнопку информера
			this.element.getElement('.compare_link').addEvent('click', function (e) {
				e.stop();
				this.popup();
			}.bind(this));

			// показ попапа сравнения по клику на кнопку внутри мини-попапа сравнения
			this.element.getElements('.compare').addEvent('click', function (e) {
				e.stop();
				var goods_ids = e.target.getProperty('data-goods-ids');
				this.compare(goods_ids);
			}.bind(this));

			// очистка сравнения
			this.element.getElement('.clear_compare_list').addEvent('click', function (e) {
				e.stop();
				this.clear();
			}.bind(this));
		}
	},

	error: function() {
		this.element.empty();
		this.element.set('html', '');
	},

	add: function(goods_id) {
		var url = this.element.getProperty('data-add-url') + goods_id + '/?html&' + Math.floor((Math.random()*10000));
		this.element.set(
			'load',
			{
				method: 'get',
				'onFailure': this.error.bind(this),
				'onComplete': this.init.bind(this)
			});
		this.element.load(url);
	},

	remove: function(goods_id) {
		alert(1);
		var url = this.element.getProperty('data-remove-url') + goods_id + '/?html&' + Math.floor((Math.random()*10000));
		this.element.set(
			'load',
			{
				method: 'get',
				'onFailure': this.error.bind(this),
				'onComplete': this.init.bind(this)
			});
		this.element.load(url);
	},

	popup: function() {
		var el = this.element.getElement('.popup_compare');
		el.toggle();
	},

	compare: function(goods_ids) {
		var url = this.element.getProperty('data-compare-url') + goods_ids + '/?html';
		ModalBox.open({
			url: url,
			onClose: function (result) {
			}.bind(this)
		});
		// todo: init onclick for remove from compare to
		// 1. call this.remove()
		// 2. remove element from compare form by js
	},

	clear: function() {
		var url = this.element.getProperty('data-clear-url') + '?html&' + Math.floor((Math.random() * 10000));
		this.element.set(
			'load',
			{
				method: 'get',
				'onFailure': this.error.bind(this),
				'onComplete': this.init.bind(this)
			});
		this.element.load(url);
	}

});


text:
package org.project.thunder_streaming.analyses

import org.project.thunder_streaming.rdds.StreamingData
import org.project.thunder_streaming.util.ThunderStreamingContext

import scala.util.{Failure, Success, Try}
import scala.xml.NodeSeq

import scala.collection.mutable.HashMap

object Analysis {
  /*
  Schema:
    <analysis>
      <name>{name}</name>
      <param name={name_1} value={value_1} />
      ...
      <param name={name_n} value={value_n} />
    </analysis>;
   */

  final val OUTPUT = "output"
  final val INPUT = "input"
  final val PREFIX = "prefix"
  final val IDENTIFIER = "identifier"

  class BadAnalysisConfigException(msg: String) extends RuntimeException(msg)

  def instantiateFromConf(tssc: ThunderStreamingContext, nodes: NodeSeq): Try[Analysis[_]] = {
    // Try to find a class with the given type name
    def extractAndFindClass(nodes: NodeSeq): Try[Class[_ <: Analysis[_]]] = {
      val nameNodes = nodes \ "name"
      if (nameNodes.length != 1) {
        Failure(new BadAnalysisConfigException("The Analysis name was not correctly specified in a single <name> element"))
      } else {
        nameNodes(0) match {
          case <name>{ name @ _* }</name> => Success(Class.forName(name(0).text)
            .asSubclass(classOf[Analysis[_]]))
          case _ => Failure(new BadAnalysisConfigException("The Analysis name was not correctly specified"))
        }
      }
    }
    // Extract all parameters necessary to instantiate an instance of the above output type
    def extractParameters(nodes: NodeSeq): Try[AnalysisParams] =  {
      val paramNodes = nodes \ "param"
      val ungroupedParams = (paramNodes \\ "@name").map(_.text).zip((paramNodes \\ "@value").map(_.text)).toList
      val groupedParams = ungroupedParams.groupBy{ case (k, v) => k }.map{ case (k, v) => (k, v.map(_._2)) }
      println("groupedParams: %s".format(groupedParams.toString))
      Success(new AnalysisParams(groupedParams))
    }
    // Attempt to invoke the (maybe) AnalysisOutput class' constructor with paramMap as an argument
    // Not using for..yield because I want Failures to propagate out of this method
    extractAndFindClass(nodes) match {
      case Success(clazz) => extractParameters(nodes) match {
        case Success(parameters) => Try(instantiateAnalysis(clazz)(tssc, parameters))
        case Failure(f) => Failure(f)
      }
      case Failure(f) => Failure(f)
    }
  }

  // Code modified from http://stackoverflow.com/questions/1641104/instantiate-object-with-reflection-using-constructor-arguments
  def instantiateAnalysis[T <: Analysis[_]](clazz: java.lang.Class[T])(tssc: ThunderStreamingContext, params: AnalysisParams): T = {
    val constructors = clazz.getConstructors
    val constructor = constructors(0)
    constructor.newInstance(tssc, params).asInstanceOf[T]
  }
}

class AnalysisParams(val param_map: Map[String, List[String]]) {
  def getParam(key: String): List[String] = param_map.getOrElse(key, List(""))
  def getSingleParam(key: String): String = getParam(key)(0)
}

trait Updatable {
  def handleUpdate(update: (String, String))
}

// Right now there's only ONE namespace for updatable parameters among all the analyses (this can be changed later)

object UpdatableParameters extends Serializable {
  // TODO: This should be made more generic (restricting the value type to String is too limiting)
  val params = new HashMap[String, String]()
  def getUpdatableParam(key: String): Option[String] = params.get(key)
  def setUpdatableParam(key: String, value: String): Unit = params.put(key, value)
}

abstract class Analysis[T <: StreamingData[_, _]](@transient val tssc: ThunderStreamingContext,
                                                  @transient val params: AnalysisParams)
  extends Updatable with Serializable {

  @transient var context = tssc.context

  override def handleUpdate(update: (String, String)): Unit = {
  }

  /**
   * Starts an UpdateListener which connects to the Python-side Analysis object and receives updates (in JSON form)
   * from an external source. These updates must be handled in an Analysis-specific way, and will typically update
   * the updatableVars map.
   */
  def startListening(): Unit = {
    val keySet = Set(DataReceiver.FORWARDER_ADDR, DataReceiver.TAGS)
    val receiverParams = new AnalysisParams(params.param_map.filterKeys(keySet.contains(_)))
    val self = this
    new Thread(new Runnable {
      def run() = {
        // This is NOT thread-safe, but that should be fine.
        // TODO: Would changing updatableParams into a thread-safe data structure affect Spark's serialization?
        val receiver = DataReceiver.getDataReceiver(tssc, self, receiverParams)
        while (!Thread.interrupted()) {
          receiver.receive()
        }
      }
    }).start
  }

  def process(): Unit = {
    val data = load(params.getSingleParam(Analysis.INPUT))
    val out = run(data)
    out.save(params.getSingleParam(Analysis.OUTPUT), params.getSingleParam(Analysis.PREFIX))
    startListening()
  }

  def load(path: String): T

  def run(data: T): T
}


text: <template id="logo">...</template>


text:
#include "wxe_return.h"

#define INLINE

wxeReturn::wxeReturn (wxeMemEnv * _memenv,
                      ErlNifPid   _caller,
		      bool        _isResult) {
  memenv  = _memenv;
  env     = _memenv->tmp_env;
  caller  = _caller;

  isResult = _isResult;
}

//clear everything so we can re-use if we want
void wxeReturn::reset() {
  enif_clear_env(env);
}

wxeReturn::~wxeReturn () {
}

int wxeReturn::send(ERL_NIF_TERM msg) {
  int res;
  if(wxe_debug) {
    if(isResult)
      enif_fprintf(stderr, "return to %T:  %T\r\n", caller, msg);
  }
  if(isResult) {
    res = enif_send(NULL, &caller, env,
                    enif_make_tuple2(env, WXE_ATOM_reply, msg));
  } else {
    res = enif_send(NULL, &caller, env, msg);
  }
  reset();
  return res;
}

// Helper for callbacks
void wxeReturn::send_callback(int callback, wxObject *obj, const char *class_name, ERL_NIF_TERM tail)
{
  ERL_NIF_TERM ref = make_ref(((WxeApp *) wxTheApp)->getRef((void *)obj, memenv), class_name);
  ERL_NIF_TERM args = enif_make_list_cell(env, ref, tail);
  send_callback(callback, args);
}

void wxeReturn::send_callback(int callback, ERL_NIF_TERM args)
{
    ERL_NIF_TERM cb_term = enif_make_tuple4(env,
                                          make_atom("_wx_invoke_cb_"),
                                          make_int(callback),
                                          args,
                                          make_atom("undefined"));
  if(wxe_debug) {
    enif_fprintf(stderr, "send CB %T:  %T\r\n", caller, cb_term);
  }
  send(cb_term);
  handle_event_callback(memenv->me_ref, caller);
}

INLINE
ERL_NIF_TERM wxeReturn::make_ref(const unsigned int ref, ERL_NIF_TERM className) {
  return enif_make_tuple4(env,
                          WXE_ATOM_wx_ref,
                          enif_make_uint(env, ref),
                          className,
                          enif_make_list(env, 0));
}

INLINE
ERL_NIF_TERM wxeReturn::make_ref(const unsigned int ref, const char* className) {
  return enif_make_tuple4(env,
                          WXE_ATOM_wx_ref,
                          enif_make_uint(env, ref),
                          enif_make_atom(env, className),
                          enif_make_list(env, 0));
}

INLINE
ERL_NIF_TERM wxeReturn::make_atom(const char* atomName) {
  return enif_make_atom(env, atomName);
}

INLINE
ERL_NIF_TERM wxeReturn::make_binary(const char* buf, const size_t size) {
  ERL_NIF_TERM bin;
  unsigned char * data;
  if(buf) {
    data = enif_make_new_binary(env, size, &bin);
    memcpy(data, buf, size);
    return bin;
  } else {
    return make_atom("null");
  }
}

INLINE
ERL_NIF_TERM wxeReturn::make_ext2term(wxeErlTerm *term) {
  if(term) {
    return enif_make_copy(env, term->term);
  } else {
    return enif_make_list(env, 0);
  }
}

INLINE
ERL_NIF_TERM wxeReturn::make_ext2term(wxETreeItemData *val) {
  if(val) {
    return enif_make_copy(env, val->term);
  } else
    return enif_make_list(env, 0);
}

INLINE
ERL_NIF_TERM wxeReturn::make_bool(int val) {
    if (val) {
      return WXE_ATOM_true;
    } else {
      return WXE_ATOM_false;
    }
}

ERL_NIF_TERM wxeReturn::make_int(int val) {
  return  enif_make_int(env, val);
}
ERL_NIF_TERM wxeReturn::make_uint(unsigned int val) {
  return  enif_make_uint(env, val);
}

ERL_NIF_TERM wxeReturn::make_double(double val) {
  return enif_make_double(env, val);
}

INLINE
ERL_NIF_TERM wxeReturn::make(const wxString s) {
    int strLen = s.Len();
    wxCharBuffer resultCB = s.mb_str(utfConverter);
    int * resultPtr = (int *) resultCB.data();
    ERL_NIF_TERM head, tail;
    tail = enif_make_list(env, 0);
    for (int i = strLen-1; i >= 0; i--) {
      head = enif_make_int(env, resultPtr[i]);
      tail = enif_make_list_cell(env, head, tail);
    }
    return tail;
}

INLINE
ERL_NIF_TERM wxeReturn::make(const wxString* s) {
  return make(*s);
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxArrayString val) {
    unsigned int len = val.GetCount();

    ERL_NIF_TERM head, tail;
    tail = enif_make_list(env, 0);
    for (int i = len-1; i >= 0; i--) {
      head = make(val[i]);
      tail = enif_make_list_cell(env, head, tail);
    }
    return tail;
}

ERL_NIF_TERM wxeReturn::make_list_objs(const wxSizerItemList& list, WxeApp *app, const char *cname)
{
  ERL_NIF_TERM head, tail;
  ERL_NIF_TERM class_name = enif_make_atom(env, cname);
  tail = enif_make_list(env, 0);
  for(wxSizerItemList::const_reverse_iterator it = list.rbegin(); it != list.rend(); ++it) {
    void * ResultTmp = *it;
    head = make_ref(app->getRef(ResultTmp,memenv), class_name);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

ERL_NIF_TERM wxeReturn::make_list_objs(const wxMenuItemList& list, WxeApp *app, const char *cname)
{
  ERL_NIF_TERM head, tail;
  ERL_NIF_TERM class_name = enif_make_atom(env, cname);
  tail = enif_make_list(env, 0);
  for(wxMenuItemList::const_reverse_iterator it = list.rbegin(); it != list.rend(); ++it) {
    void * ResultTmp = *it;
    head = make_ref(app->getRef(ResultTmp,memenv), class_name);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

ERL_NIF_TERM wxeReturn::make_list_objs(const wxWindowList& list, WxeApp *app, const char *cname)
{
  ERL_NIF_TERM head, tail;
  ERL_NIF_TERM class_name = enif_make_atom(env, cname);
  tail = enif_make_list(env, 0);
  for(wxWindowList::const_reverse_iterator it = list.rbegin(); it != list.rend(); ++it) {
    void * ResultTmp = *it;
    head = make_ref(app->getRef(ResultTmp,memenv), class_name);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

ERL_NIF_TERM wxeReturn::make_array_objs(wxAuiPaneInfoArray& arr, WxeApp *app, const char *cname)
{
  ERL_NIF_TERM head, tail;
  ERL_NIF_TERM class_name = enif_make_atom(env, cname);
  tail = enif_make_list(env, 0);
  for(unsigned int i = arr.GetCount() -1; i >= 0; i--) {
    head = make_ref(app->getRef((void *) &arr.Item(i),memenv), class_name);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

ERL_NIF_TERM wxeReturn::make_array_objs(wxArrayTreeItemIds& arr)
{
  ERL_NIF_TERM head, tail;
  tail = enif_make_list(env, 0);
  for(unsigned int i = arr.GetCount() -1; i >= 0; i--) {
    head = make((wxUIntPtr *) arr[i].m_pItem);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

ERL_NIF_TERM wxeReturn::make_array_objs(wxGridCellCoordsArray& arr)
{
  ERL_NIF_TERM head, tail;
  tail = enif_make_list(env, 0);
  for(unsigned int i = arr.GetCount() -1; i >= 0; i--) {
    head = make(arr[i]);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

INLINE
ERL_NIF_TERM wxeReturn::make_list_strings(size_t size, wxString* strings)
{
  wxArrayString tmpArrayStr(size, strings);
  return make(tmpArrayStr);
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxArrayInt val) {
    unsigned int len = val.GetCount();
    ERL_NIF_TERM head, tail;
    tail = enif_make_list(env, 0);
    for (int i = len-1; i >= 0; i--) {
      head = enif_make_int(env, val[i]);
      tail = enif_make_list_cell(env, head, tail);
    }
    return tail;
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxArrayDouble val) {
  unsigned int len = val.GetCount();

  ERL_NIF_TERM head, tail;
  tail = enif_make_list(env, 0);
  for (int i = len-1; i >= 0; i--) {
    head = enif_make_double(env, val[i]);
    tail = enif_make_list_cell(env, head, tail);
  }
  return tail;
}

INLINE
ERL_NIF_TERM wxeReturn::make(wxUIntPtr *val) {
  return enif_make_uint64(env, (ErlNifUInt64) val);
}

INLINE
ERL_NIF_TERM wxeReturn::make(wxPoint pt) {
  return enif_make_tuple2(env,
                          enif_make_int(env,pt.x),
                          enif_make_int(env,pt.y)
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxPoint2DDouble pt) {
  return enif_make_tuple2(env,
                          enif_make_double(env,pt.m_x),
                          enif_make_double(env,pt.m_y)
                          );
}

INLINE
ERL_NIF_TERM wxeReturn::make(wxSize size) {
  return enif_make_tuple2(env,
                          enif_make_int(env,size.GetWidth()),
                          enif_make_int(env,size.GetHeight())
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxRect rect) {
  return enif_make_tuple4(env,
                          enif_make_int(env,rect.x),
                          enif_make_int(env,rect.y),
                          enif_make_int(env,rect.width),
                          enif_make_int(env,rect.height)
                          );
}

INLINE
ERL_NIF_TERM wxeReturn::make(wxColour colour) {
  return enif_make_tuple4(env,
                          enif_make_int(env, colour.Red()),
                          enif_make_int(env, colour.Green()),
                          enif_make_int(env, colour.Blue()),
                          enif_make_int(env, colour.Alpha())
                          );
}

INLINE
ERL_NIF_TERM wxeReturn::make(wxGraphicsGradientStop stop) {
  return enif_make_tuple2(env,
                          make(stop.GetColour()),
                          enif_make_double(env, (double) stop.GetPosition()));
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxDateTime dateTime) {
  return enif_make_tuple2(env,
                          make_date(dateTime),
                          make_time(dateTime)
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make_date(wxDateTime dateTime) {
  return enif_make_tuple3(env,
                          enif_make_int(env, dateTime.GetYear()),
                          enif_make_int(env, dateTime.GetMonth()+1), // c++ month is zero based
                          enif_make_int(env, dateTime.GetDay())
                          );
}

INLINE ERL_NIF_TERM  wxeReturn::make_time(wxDateTime dateTime) {
  return enif_make_tuple3(env,
                          enif_make_int(env, dateTime.GetHour()),
                          enif_make_int(env, dateTime.GetMinute()),
                          enif_make_int(env, dateTime.GetSecond())
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxRect2DDouble rect2D) {
  return enif_make_tuple4(env,
                          enif_make_double(env, rect2D.m_x),
                          enif_make_double(env, rect2D.m_y),
                          enif_make_double(env, rect2D.m_width),
                          enif_make_double(env, rect2D.m_height)
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxGridCellCoords val) {
  return enif_make_tuple2(env,
                          enif_make_int(env, val.GetRow()),
                          enif_make_int(env, val.GetCol())
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxGBPosition val) {
  return enif_make_tuple2(env,
                          enif_make_int(env, val.GetRow()),
                          enif_make_int(env, val.GetCol())
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxGBSpan val) {
  return enif_make_tuple2(env,
                          enif_make_int(env, val.GetRowspan()),
                          enif_make_int(env, val.GetColspan())
                          );
}

INLINE
ERL_NIF_TERM  wxeReturn::make(wxMouseState val) {
  return enif_make_tuple(env, 11,
                         enif_make_atom(env, "wxMouseState"),
                         // TODO not int?
                         enif_make_uint(env, val.GetX()),
                         enif_make_uint(env, val.GetY()),
                         make_bool(val.LeftIsDown()),
                         make_bool(val.MiddleIsDown()),
                         make_bool(val.RightIsDown()),
                         make_bool(val.ControlDown()),
                         make_bool(val.ShiftDown()),
                         make_bool(val.AltDown()),
                         make_bool(val.MetaDown()),
                         make_bool(val.CmdDown())
                         );
}

INLINE
ERL_NIF_TERM wxeReturn::make(const wxHtmlLinkInfo *val) {
  return enif_make_tuple3(env,
                          make_atom("wxHtmlLinkInfo"),
                          make(val->GetHref()),
                          make(val->GetTarget())
                          );
}

INLINE
ERL_NIF_TERM wxeReturn::make(const wxHtmlLinkInfo &val) {
  return enif_make_tuple3(env,
                          make_atom("wxHtmlLinkInfo"),
                          make(val.GetHref()),
                          make(val.GetTarget())
                          );
}


text:
KindEditor.plugin('insertblank', function(K) {
    var self = this, name = 'insertblank';
    self.clickToolbar(name, function() {
        var html = ['
',
                    '
',
                    '
',
                    '      <input class="ke-input-text" type="text" value="" style="width:250px;" />',
                    '
',
                    '
',
                    '
',
                    '    + 添加',
                    '
',
                    '
',
                    '
提示:点击 [+添加],可为一个填空设置多个答案
',
                    '
'].join(''),

            dialog = self.createDialog({
                name : name,
                width : 450,
                title : '插入填空项',
                body : html,
                yesBtn : {
                    name : self.lang('yes'),
                    click : function(e) {

                        var blankValues = [];

                        K('div.insertblank-inputs').scan(function(node){
                            if (K(node).hasClass('ke-input-text')){
                                blankValues.push(K(node).val());
                            }
                        });

                        html = '[[' + blankValues.join('|') + ']]';

                        self.insertHtml(html).hideDialog().focus();
                    }
                }
            }),

            dialogRoot = dialog.div,

            blankInput = K('.ke-input-text', dialogRoot);

        blankInput[0].focus();

        K('.insertblank-add-btn', dialogRoot).click(function() {
            var blankInputHtml = [
                    '
',
                    '<input class="ke-input-text" type="text" value="" style="width:250px;" />',
                    '
'].join(''),
                blankInputNode = K(blankInputHtml);
            K('.insertblank-inputs', dialogRoot).append(blankInputNode);
            K('.ke-input-text', blankInputNode).get(0).focus();

            dialogRoot.height(dialogRoot.height() + 26);
        });

        K('.insertblank-inputs', dialogRoot).bind('keydown', function(event) {
            if (event.keyCode == 13){
                var blankInputHtml = [
                        '
',
                        '<input class="ke-input-text" type="text" value="" style="width:250px;" />',
                        '
'].join(''),
                    blankInputNode = K(blankInputHtml);
                K('.insertblank-inputs', dialogRoot).append(blankInputNode);
                K('.ke-input-text', blankInputNode).get(0).focus();

                dialogRoot.height(dialogRoot.height() + 26);
            }
        });

    });

});


text:
<productname>{PRODUCT}</productname>
<productnumber>{PRODUCT_VERSION}</productnumber>
<subtitle>
</subtitle>
<abstract>
	<para>This document describes how to integrate Red Hat Developer Studio with {PRODUCT}.</para>
</abstract>
<xi:include href="Common_Content/Legal_Notice.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />