text:
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.filters;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.beanutils.ConversionException;

import com.google.common.collect.Lists;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;

/**
 *

 * A filter that uses comments to suppress audit events.
 *

 *

 * Rationale:
 * Sometimes there are legitimate reasons for violating a check.  When
 * this is a matter of the code in question and not personal
 * preference, the best place to override the policy is in the code
 * itself.  Semi-structured comments can be associated with the check.
 * This is sometimes superior to a separate suppressions file, which
 * must be kept up-to-date as the source file is edited.
 *

 *

 * Usage:
 * This check only works in conjunction with the FileContentsHolder module
 * since that module makes the suppression comments in the .java
 * files available sub rosa.
 *

 * @author Mike McMahon
 * @author Rick Giles
 * @see FileContentsHolder
 */
public class SuppressionCommentFilter
    extends AutomaticBean
    implements Filter {

    /** Turns checkstyle reporting off. */
    private static final String DEFAULT_OFF_FORMAT = "CHECKSTYLE\\:OFF";

    /** Turns checkstyle reporting on. */
    private static final String DEFAULT_ON_FORMAT = "CHECKSTYLE\\:ON";

    /** Control all checks. */
    private static final String DEFAULT_CHECK_FORMAT = ".*";

    /** Whether to look in comments of the C type. */
    private boolean checkC = true;

    /** Whether to look in comments of the C++ type. */
    private boolean checkCPP = true;

    /** Parsed comment regexp that turns checkstyle reporting off. */
    private Pattern offRegexp;

    /** Parsed comment regexp that turns checkstyle reporting on. */
    private Pattern onRegexp;

    /** The check format to suppress. */
    private String checkFormat;

    /** The message format to suppress. */
    private String messageFormat;

    /** Tagged comments. */
    private final List<Tag> tags = Lists.newArrayList();

    /**
     * References the current FileContents for this filter.
     * Since this is a weak reference to the FileContents, the FileContents
     * can be reclaimed as soon as the strong references in TreeWalker
     * and FileContentsHolder are reassigned to the next FileContents,
     * at which time filtering for the current FileContents is finished.
     */
    private WeakReference<FileContents> fileContentsReference = new WeakReference<>(null);

    /**
     * Constructs a SuppressionCommentFilter.
     * Initializes comment on, comment off, and check formats
     * to defaults.
     */
    public SuppressionCommentFilter() {
        setOnCommentFormat(DEFAULT_ON_FORMAT);
        setOffCommentFormat(DEFAULT_OFF_FORMAT);
        checkFormat = DEFAULT_CHECK_FORMAT;
    }

    /**
     * Set the format for a comment that turns off reporting.
     * @param format a {@code String} value.
     * @throws ConversionException if unable to create Pattern object.
     */
    public final void setOffCommentFormat(String format) {
        offRegexp = CommonUtils.createPattern(format);
    }

    /**
     * Set the format for a comment that turns on reporting.
     * @param format a {@code String} value
     * @throws ConversionException if unable to create Pattern object.
     */
    public final void setOnCommentFormat(String format) {
        onRegexp = CommonUtils.createPattern(format);
    }

    /**
     * @return the FileContents for this filter.
     */
    public FileContents getFileContents() {
        return fileContentsReference.get();
    }

    /**
     * Set the FileContents for this filter.
     * @param fileContents the FileContents for this filter.
     */
    public void setFileContents(FileContents fileContents) {
        fileContentsReference = new WeakReference<>(fileContents);
    }

    /**
     * Set the format for a check.
     * @param format a {@code String} value
     */
    public final void setCheckFormat(String format) {
        checkFormat = format;
    }

    /**
     * Set the format for a message.
     * @param format a {@code String} value
     */
    public void setMessageFormat(String format) {
        messageFormat = format;
    }

    /**
     * Set whether to look in C++ comments.
     * @param checkCPP {@code true} if C++ comments are checked.
     */
    public void setCheckCPP(boolean checkCPP) {
        this.checkCPP = checkCPP;
    }

    /**
     * Set whether to look in C comments.
     * @param checkC {@code true} if C comments are checked.
     */
    public void setCheckC(boolean checkC) {
        this.checkC = checkC;
    }

    @Override
    public boolean accept(AuditEvent event) {
        boolean accepted = true;

        if (event.getLocalizedMessage() != null) {
            // Lazy update. If the first event for the current file, update file
            // contents and tag suppressions
            final FileContents currentContents = FileContentsHolder.getContents();

            if (currentContents != null) {
                if (getFileContents() != currentContents) {
                    setFileContents(currentContents);
                    tagSuppressions();
                }
                final Tag matchTag = findNearestMatch(event);
                accepted = matchTag == null || matchTag.isOn();
            }
        }
        return accepted;
    }

    /**
     * Finds the nearest comment text tag that matches an audit event.
     * The nearest tag is before the line and column of the event.
     * @param event the {@code AuditEvent} to match.
     * @return The {@code Tag} nearest event.
     */
    private Tag findNearestMatch(AuditEvent event) {
        Tag result = null;
        for (Tag tag : tags) {
            if (tag.getLine() > event.getLine()
                || tag.getLine() == event.getLine()
                    && tag.getColumn() > event.getColumn()) {
                break;
            }
            if (tag.isMatch(event)) {
                result = tag;
            }
        }
        return result;
    }

    /**
     * Collects all the suppression tags for all comments into a list and
     * sorts the list.
     */
    private void tagSuppressions() {
        tags.clear();
        final FileContents contents = getFileContents();
        if (checkCPP) {
            tagSuppressions(contents.getCppComments().values());
        }
        if (checkC) {
            final Collection<List<TextBlock>> cComments = contents
                    .getCComments().values();
            for (List<TextBlock> element : cComments) {
                tagSuppressions(element);
            }
        }
        Collections.sort(tags);
    }

    /**
     * Appends the suppressions in a collection of comments to the full
     * set of suppression tags.
     * @param comments the set of comments.
     */
    private void tagSuppressions(Collection<TextBlock> comments) {
        for (TextBlock comment : comments) {
            final int startLineNo = comment.getStartLineNo();
            final String[] text = comment.getText();
            tagCommentLine(text[0], startLineNo, comment.getStartColNo());
            for (int i = 1; i < text.length; i++) {
                tagCommentLine(text[i], startLineNo + i, 0);
            }
        }
    }

    /**
     * Tags a string if it matches the format for turning
     * checkstyle reporting on or the format for turning reporting off.
     * @param text the string to tag.
     * @param line the line number of text.
     * @param column the column number of text.
     */
    private void tagCommentLine(String text, int line, int column) {
        final Matcher offMatcher = offRegexp.matcher(text);
        if (offMatcher.find()) {
            addTag(offMatcher.group(0), line, column, false);
        }
        else {
            final Matcher onMatcher = onRegexp.matcher(text);
            if (onMatcher.find()) {
                addTag(onMatcher.group(0), line, column, true);
            }
        }
    }

    /**
     * Adds a {@code Tag} to the list of all tags.
     * @param text the text of the tag.
     * @param line the line number of the tag.
     * @param column the column number of the tag.
     * @param on {@code true} if the tag turns checkstyle reporting on.
     */
    private void addTag(String text, int line, int column, boolean on) {
        final Tag tag = new Tag(line, column, text, on, this);
        tags.add(tag);
    }

    /**
     * A Tag holds a suppression comment and its location, and determines
     * whether the suppression turns checkstyle reporting on or off.
     * @author Rick Giles
     */
    public static class Tag
        implements Comparable<Tag> {
        /** The text of the tag. */
        private final String text;

        /** The line number of the tag. */
        private final int line;

        /** The column number of the tag. */
        private final int column;

        /** Determines whether the suppression turns checkstyle reporting on. */
        private final boolean on;

        /** The parsed check regexp, expanded for the text of this tag. */
        private final Pattern tagCheckRegexp;

        /** The parsed message regexp, expanded for the text of this tag. */
        private final Pattern tagMessageRegexp;

        /**
         * Constructs a tag.
         * @param line the line number.
         * @param column the column number.
         * @param text the text of the suppression.
         * @param on {@code true} if the tag turns checkstyle reporting.
         * @param filter the {@code SuppressionCommentFilter} with the context
         * @throws ConversionException if unable to parse expanded text.
         */
        public Tag(int line, int column, String text, boolean on, SuppressionCommentFilter filter) {
            this.line = line;
            this.column = column;
            this.text = text;
            this.on = on;

            //Expand regexp for check and message
            //Does not intern Patterns with Utils.getPattern()
            String format = "";
            try {
                if (on) {
                    format =
                        expandFromComment(text, filter.checkFormat, filter.onRegexp);
                    tagCheckRegexp = Pattern.compile(format);
                    if (filter.messageFormat != null) {
                        format =
                            expandFromComment(text, filter.messageFormat, filter.onRegexp);
                        tagMessageRegexp = Pattern.compile(format);
                    }
                    else {
                        tagMessageRegexp = null;
                    }
                }
                else {
                    format =
                        expandFromComment(text, filter.checkFormat, filter.offRegexp);
                    tagCheckRegexp = Pattern.compile(format);
                    if (filter.messageFormat != null) {
                        format =
                            expandFromComment(
                                    text,
                                    filter.messageFormat,
                                    filter.offRegexp);
                        tagMessageRegexp = Pattern.compile(format);
                    }
                    else {
                        tagMessageRegexp = null;
                    }
                }
            }
            catch (final PatternSyntaxException e) {
                throw new ConversionException(
                    "unable to parse expanded comment " + format,
                    e);
            }
        }

        /**
         * @return the line number of the tag in the source file.
         */
        public int getLine() {
            return line;
        }

        /**
         * Determines the column number of the tag in the source file.
         * Will be 0 for all lines of multiline comment, except the
         * first line.
         * @return the column number of the tag in the source file.
         */
        public int getColumn() {
            return column;
        }

        /**
         * Determines whether the suppression turns checkstyle reporting on or
         * off.
         * @return {@code true}if the suppression turns reporting on.
         */
        public boolean isOn() {
            return on;
        }

        /**
         * Compares the position of this tag in the file
         * with the position of another tag.
         * @param object the tag to compare with this one.
         * @return a negative number if this tag is before the other tag,
         *     0 if they are at the same position, and a positive number if this
         *     tag is after the other tag.
         */
        @Override
        public int compareTo(Tag object) {
            if (line == object.line) {
                return Integer.compare(column, object.column);
            }

            return Integer.compare(line, object.line);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            final Tag tag = (Tag) o;
            return Objects.equals(line, tag.line)
                    && Objects.equals(column, tag.column)
                    && Objects.equals(on, tag.on)
                    && Objects.equals(text, tag.text);
        }

        @Override
        public int hashCode() {
            return Objects.hash(text, line, column, on);
        }

        /**
         * Determines whether the source of an audit event
         * matches the text of this tag.
         * @param event the {@code AuditEvent} to check.
         * @return true if the source of event matches the text of this tag.
         */
        public boolean isMatch(AuditEvent event) {
            boolean match = false;
            final Matcher tagMatcher = tagCheckRegexp.matcher(event.getSourceName());
            if (tagMatcher.find()) {
                if (tagMessageRegexp != null) {
                    final Matcher messageMatcher = tagMessageRegexp.matcher(event.getMessage());
                    match = messageMatcher.find();
                }
                else {
                    match = true;
                }
            }
            return match;
        }

        /**
         * Expand based on a matching comment.
         * @param comment the comment.
         * @param stringToExpand the string to expand.
         * @param regexp the parsed expander.
         * @return the expanded string
         */
        private static String expandFromComment(
                String comment,
                String stringToExpand,
                Pattern regexp) {
            final Matcher matcher = regexp.matcher(comment);
            // Match primarily for effect.
            if (!matcher.find()) {
                return stringToExpand;
            }
            String result = stringToExpand;
            for (int i = 0; i <= matcher.groupCount(); i++) {
                // $n expands comment match like in Pattern.subst().
                result = result.replaceAll("\\$" + i, matcher.group(i));
            }
            return result;
        }

        @Override
        public final String toString() {
            return "Tag[line=" + line + "; col=" + column
                + "; on=" + on + "; text='" + text + "']";
        }
    }
}


text:
<?php

namespace Tests\Louvre\ReservationBundle\Services\CodeGenerator;

use Louvre\ReservationBundle\Services\CodeGenerator\LouvreCodeGenerator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class LouvreCodeGeneratorTest extends WebTestCase
{
	private $codeGenerator;

	protected function setUp()
	{
		parent::setUp();

		$this->codeGenerator = new LouvreCodeGenerator();
	}

	/** @test */
	public function serviceShouldGenerateParticularString()
	{
		$testCode1 = $this->codeGenerator->generateRandomCode();
		$testCode2 = $this->codeGenerator->generateRandomCode();
		$testCode3 = $this->codeGenerator->generateRandomCode();

		// Test if testCode contains a code begining by "LR-" and containing 30 random caracters composed by only capital letters and numbers
		$this->assertTrue((preg_match('/LR-[A-Z0-9]{30}/', $testCode1) == 1) ? true : false);
		$this->assertTrue((preg_match('/LR-[A-Z0-9]{30}/', $testCode2) == 1) ? true : false);
		$this->assertTrue((preg_match('/LR-[A-Z0-9]{30}/', $testCode3) == 1) ? true : false);
	}
}

redpajama_set_name: RedPajamaGithub


text:
@interface KWBeSubclassOfClassMatcher : KWMatcher {
@private
    Class targetClass;
}

#pragma mark -
#pragma mark Configuring Matchers

- (void)beSubclassOfClass:(Class)aClass;

@end


text:
package com.dslplatform.json;

import java.io.IOException;

public class ParsingException extends IOException {

	private ParsingException(String reason) {
		super(reason);
	}

	private ParsingException(String reason, Throwable cause) {
		super(reason, cause);
	}

	public static ParsingException create(String reason, boolean withStackTrace) {
		return withStackTrace
				? new ParsingException(reason)
				: new ParsingStacklessException(reason);
	}

	public static ParsingException create(String reason, Throwable cause, boolean withStackTrace) {
		return withStackTrace
				? new ParsingException(reason, cause)
				: new ParsingStacklessException(reason, cause);
	}

	private static class ParsingStacklessException extends ParsingException {

		private ParsingStacklessException(String reason) {
			super(reason);
		}

		private ParsingStacklessException(String reason, Throwable cause) {
			super(reason, cause);
		}

		@Override
		public synchronized Throwable fillInStackTrace() {
			return this;
		}
	}
}


text:
require 'less-rails'
require 'kaminari'
require 'pagaxian/version'
require 'pagaxian/engine'
require 'pagaxian/acts_as_paged_datatable'


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.uniandes.csw.artwork.api;

import co.edu.uniandes.csw.artwork.entities.ShoppingCartItemEntity;
import java.util.List;

/**
 *
 * @author juan
 */
public interface IShoppingCartItemLogic {
    public int countItems();
    public List<ShoppingCartItemEntity> getItems(Long clientid);
    public List<ShoppingCartItemEntity> getItems(Integer page, Integer maxRecords, Long clientid, Long artworkId);
    public ShoppingCartItemEntity addItem(Long clientid, ShoppingCartItemEntity entity);
    public void removeItem(Long id);
    public ShoppingCartItemEntity updateItem(Long clientid, ShoppingCartItemEntity entity);
    public ShoppingCartItemEntity getItem(Long itemid);
}


text:
@interface SqliteObject()

@property (nonatomic ,strong) NSMutableArray *propertyList;

@end

@implementation SqliteObject

- (void)dealloc
{
    self.propertyList = nil;
    self.rowid = nil;
    [super dealloc];
}

+ (id)object
{
    SqliteObject *object = [[self alloc] init];

    return [object autorelease];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        for (NSString *property in self.propertyList) {
            [self setValue:@"" forKey:property];
        }
    }
    return self;
}

- (NSMutableArray *)propertyList
{
    if (_propertyList != nil) {
        return _propertyList;
    }
    _propertyList = [[NSMutableArray alloc] init];

    unsigned int outCount = 0;
    objc_property_t *properties = NULL;
    //添加父类的属性
    properties = class_copyPropertyList(class_getSuperclass(self.class), &outCount);
    for (int i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        if ([propertyName isEqualToString:@"propertyList"]) {
            continue;
        }
        [_propertyList addObject:propertyName];
    }
    //添加子类的属性
    properties = class_copyPropertyList([self class], &outCount);
    for (int i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];

        [_propertyList addObject:propertyName];
    }

    return _propertyList;
}

//创建数据库表格的SQL
- (NSString *)createSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"create table %@(",NSStringFromClass(self.class)];
    for (NSString *property in self.propertyList)
    {
        if ([property isEqualToString:@"rowid"])
        {
            [sql appendFormat:@"m_%@ integer primary key autoincrement,",property];
            continue;
        }
        [sql appendFormat:@"m_%@ text,",property];
    }
    NSRange lastRange = NSMakeRange(sql.length - 1, 1);
    [sql deleteCharactersInRange:lastRange];
    [sql appendFormat:@");"];

    return [sql autorelease];
}

- (NSString *)dropSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"drop table %@;",NSStringFromClass(self.class)];
    return [sql autorelease];
}

- (NSString *)insertSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"insert into %@(",NSStringFromClass(self.class)];
    for (NSString *property in self.propertyList)
    {
        if ([property isEqualToString:@"propertyList"]) {
            continue;
        }
        if ([property isEqualToString:@"rowid"]) {
            continue;
        }
        [sql appendFormat:@"m_%@,",property];
    }
    NSRange lastRange = NSMakeRange(sql.length - 1, 1);
    [sql deleteCharactersInRange:lastRange];
    [sql appendString:@")"];

    [sql appendString:@"values("];

    for (NSString *property in self.propertyList) {
        if ([property isEqualToString:@"propertyList"]) {
            continue;
        }
        if ([property isEqualToString:@"rowid"]) {
            continue;
        }
        [sql appendFormat:@"'%@',",[self valueForKey:property]];
    }

    lastRange = NSMakeRange(sql.length - 1, 1);
    [sql deleteCharactersInRange:lastRange];
    [sql appendString:@");"];

    return [sql autorelease];
}

- (NSString *)removeSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"delete from %@ ",NSStringFromClass(self.class)];
    [sql appendFormat:@"where m_rowid='%@';",self.rowid];
    return [sql autorelease];
}
- (NSString *)updateSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"update %@ set ",NSStringFromClass(self.class)];

    for (NSString *property in self.propertyList)
    {
        if ([property isEqualToString:@"propertyList"]) {
            continue;
        }
        if ([property isEqualToString:@"rowid"]) {
            continue;
        }
        [sql appendFormat:@"m_%@",property];
        [sql appendFormat:@"="];
        [sql appendFormat:@"%@,",[self valueForKey:property]];
    }
    NSRange lastRange = NSMakeRange(sql.length - 1, 1);
    [sql deleteCharactersInRange:lastRange];

    [sql appendFormat:@" where m_rowid=%@",self.rowid];
    return [sql autorelease];
}
- (NSString *)selectSQL
{
    NSMutableString *sql = [[NSMutableString alloc] init];
    [sql appendFormat:@"select * from %@",NSStringFromClass(self.class)];
    [sql appendFormat:@" where 1 "];
    //添加查询条件
    for (NSString *property  in self.propertyList) {
        if ([property isEqualToString:@"propertyList"]) {
            continue;
        }
        if ([[self valueForKey:property] isEqualToString:@""]) {
            continue;
        }

        [sql appendFormat:@"and m_%@",property];
        [sql appendFormat:@"="];
        [sql appendFormat:@"%@,",[self valueForKey:property]];
    }
    NSRange lastRange = NSMakeRange(sql.length - 1, 1);
    [sql deleteCharactersInRange:lastRange];

    return [sql autorelease];
}

@end


text:
/**
 * holiday-watchdog-api
 *
 * This file was automatically generated for Holiday Watchdog by APIMATIC v2.0 ( https://apimatic.io ) on 01/16/2017
 */
var BaseModel = require("./BaseModel");
/**
 * Creates an instance of AccommodationDetailedAlgolia
 *
 * @constructor
 */
AccommodationDetailedAlgolia = function (obj) {
    if(!obj) {
        this.id = null;
        this.source = null;
        this.locationId = null;
        this.ownerId = null;
        this.tripId = null;
        this.address1 = null;
        this.address2 = null;
        this.postcode = null;
        this.telephone = null;
        this.url = null;
        this.name = null;
        this.description = null;
        this.totalRatings = null;
        this.averageRating = null;
        this.stars = null;
        this.typeId = null;
        this.longitude = null;
        this.latitude = null;
        this.numRooms = null;
        this.redirectAccommodationId = null;
        this.redirectId = null;
        this.metaNoIndex = null;
        this.pageUrl = null;
        this.binaryOptions = null;
        this.descOverview = null;
        this.descRoomInformation = null;
        this.descFacilities = null;
        this.descFoodDrink = null;
        this.dateCreated = null;
        this.dateUpdated = null;
        this.dateRemoved = null;
        this.locationPath = null;
        this.photos = null;
        this.tripadvisor = null;
        this.commerceMappings = null;
        this.objectID = null;
        this.highlightResult = null;
        this.rankingInfo = null;
        this.geoloc = null;
        //Append to variable dictionary
        this._variableDict['locationId'] = 'location_id';
        this._variableDict['ownerId'] = 'owner_id';
        this._variableDict['tripId'] = 'trip_id';
        this._variableDict['totalRatings'] = 'total_ratings';
        this._variableDict['averageRating'] = 'average_rating';
        this._variableDict['typeId'] = 'type_id';
        this._variableDict['numRooms'] = 'num_rooms';
        this._variableDict['redirectAccommodationId'] = 'redirect_accommodation_id';
        this._variableDict['redirectId'] = 'redirect_id';
        this._variableDict['metaNoIndex'] = 'meta_no_index';
        this._variableDict['pageUrl'] = 'page_url';
        this._variableDict['binaryOptions'] = 'binary_options';
        this._variableDict['descOverview'] = 'desc_overview';
        this._variableDict['descRoomInformation'] = 'desc_room_information';
        this._variableDict['descFacilities'] = 'desc_facilities';
        this._variableDict['descFoodDrink'] = 'desc_food_drink';
        this._variableDict['dateCreated'] = 'date_created';
        this._variableDict['dateUpdated'] = 'date_updated';
        this._variableDict['dateRemoved'] = 'date_removed';
        this._variableDict['locationPath'] = 'location_path';
        this._variableDict['commerceMappings'] = 'commerce-mappings';
        this._variableDict['highlightResult'] = '_highlightResult';
        this._variableDict['rankingInfo'] = '_rankingInfo';
        this._variableDict['geoloc'] = '_geoloc';
    } else {
        this.id = (obj.id !== undefined && obj.id !== null)? obj.id : null;
        this.source = (obj.source !== undefined && obj.source !== null)? obj.source : null;
        this.locationId = (obj.location_id !== undefined && obj.location_id !== null)? obj.location_id : null;
        this.ownerId = (obj.owner_id !== undefined && obj.owner_id !== null)? obj.owner_id : null;
        this.tripId = (obj.trip_id !== undefined && obj.trip_id !== null)? obj.trip_id : null;
        this.address1 = (obj.address1 !== undefined && obj.address1 !== null)? obj.address1 : null;
        this.address2 = (obj.address2 !== undefined && obj.address2 !== null)? obj.address2 : null;
        this.postcode = (obj.postcode !== undefined && obj.postcode !== null)? obj.postcode : null;
        this.telephone = (obj.telephone !== undefined && obj.telephone !== null)? obj.telephone : null;
        this.url = (obj.url !== undefined && obj.url !== null)? obj.url : null;
        this.name = (obj.name !== undefined && obj.name !== null)? obj.name : null;
        this.description = (obj.description !== undefined && obj.description !== null)? obj.description : null;
        this.totalRatings = (obj.total_ratings !== undefined && obj.total_ratings !== null)? obj.total_ratings : null;
        this.averageRating = (obj.average_rating !== undefined && obj.average_rating !== null)? obj.average_rating : null;
        this.stars = (obj.stars !== undefined && obj.stars !== null)? obj.stars : null;
        this.typeId = (obj.type_id !== undefined && obj.type_id !== null)? obj.type_id : null;
        this.longitude = (obj.longitude !== undefined && obj.longitude !== null)? obj.longitude : null;
        this.latitude = (obj.latitude !== undefined && obj.latitude !== null)? obj.latitude : null;
        this.numRooms = (obj.num_rooms !== undefined && obj.num_rooms !== null)? obj.num_rooms : null;
        this.redirectAccommodationId = (obj.redirect_accommodation_id !== undefined && obj.redirect_accommodation_id !== null)? obj.redirect_accommodation_id : null;
        this.redirectId = (obj.redirect_id !== undefined && obj.redirect_id !== null)? obj.redirect_id : null;
        this.metaNoIndex = (obj.meta_no_index !== undefined && obj.meta_no_index !== null)? obj.meta_no_index : null;
        this.pageUrl = (obj.page_url !== undefined && obj.page_url !== null)? obj.page_url : null;
        this.binaryOptions = (obj.binary_options !== undefined && obj.binary_options !== null)? obj.binary_options : null;
        this.descOverview = (obj.desc_overview !== undefined && obj.desc_overview !== null)? obj.desc_overview : null;
        this.descRoomInformation = (obj.desc_room_information !== undefined && obj.desc_room_information !== null)? obj.desc_room_information : null;
        this.descFacilities = (obj.desc_facilities !== undefined && obj.desc_facilities !== null)? obj.desc_facilities : null;
        this.descFoodDrink = (obj.desc_food_drink !== undefined && obj.desc_food_drink !== null)? obj.desc_food_drink : null;
        this.dateCreated = (obj.date_created !== undefined && obj.date_created !== null)? obj.date_created : null;
        this.dateUpdated = (obj.date_updated !== undefined && obj.date_updated !== null)? obj.date_updated : null;
        this.dateRemoved = (obj.date_removed !== undefined && obj.date_removed !== null)? obj.date_removed : null;
        this.locationPath = (obj.location_path !== undefined && obj.location_path !== null)? obj.location_path : null;
        this.photos = ((obj.photos !== undefined && obj.photos !== null)? obj.photos : null !==undefined &&(obj.photos !== undefined && obj.photos !== null)? obj.photos : null !==null)?(obj.photos !== undefined && obj.photos !== null)? obj.photos : null.map(function(model){
            return new Photo(model);
        }):null;
        this.tripadvisor = (obj.tripadvisor !==undefined && obj.tripadvisor !==null)? new TripadvisorDetailedResponse(obj.tripadvisor) : null;
        this.commerceMappings = obj['commerce-mappings'];
        this.objectID = (obj.objectID !== undefined && obj.objectID !== null)? obj.objectID : null;
        this.highlightResult = (obj._highlightResult !==undefined && obj._highlightResult !==null)? new HighlightResult(obj._highlightResult) : null;
        this.rankingInfo = (obj._rankingInfo !==undefined && obj._rankingInfo !==null)? new RankingInfo(obj._rankingInfo) : null;
        this.geoloc = (obj._geoloc !==undefined && obj._geoloc !==null)? new Geoloc(obj._geoloc) : null;
        //Append to variable dictionary
        this._variableDict['locationId'] = 'location_id';
        this._variableDict['ownerId'] = 'owner_id';
        this._variableDict['tripId'] = 'trip_id';
        this._variableDict['totalRatings'] = 'total_ratings';
        this._variableDict['averageRating'] = 'average_rating';
        this._variableDict['typeId'] = 'type_id';
        this._variableDict['numRooms'] = 'num_rooms';
        this._variableDict['redirectAccommodationId'] = 'redirect_accommodation_id';
        this._variableDict['redirectId'] = 'redirect_id';
        this._variableDict['metaNoIndex'] = 'meta_no_index';
        this._variableDict['pageUrl'] = 'page_url';
        this._variableDict['binaryOptions'] = 'binary_options';
        this._variableDict['descOverview'] = 'desc_overview';
        this._variableDict['descRoomInformation'] = 'desc_room_information';
        this._variableDict['descFacilities'] = 'desc_facilities';
        this._variableDict['descFoodDrink'] = 'desc_food_drink';
        this._variableDict['dateCreated'] = 'date_created';
        this._variableDict['dateUpdated'] = 'date_updated';
        this._variableDict['dateRemoved'] = 'date_removed';
        this._variableDict['locationPath'] = 'location_path';
        this._variableDict['commerceMappings'] = 'commerce-mappings';
        this._variableDict['highlightResult'] = '_highlightResult';
        this._variableDict['rankingInfo'] = '_rankingInfo';
        this._variableDict['geoloc'] = '_geoloc';
    }
};

AccommodationDetailedAlgolia.prototype = new BaseModel();
AccommodationDetailedAlgolia.prototype.constructor = AccommodationDetailedAlgolia;

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getId = function() {
    return this.id;
};

/**
 * Setter for Id
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setId = function(value) {
    this.id = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getSource = function() {
    return this.source;
};

/**
 * Setter for Source
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setSource = function(value) {
    this.source = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getLocationId = function() {
    return this.locationId;
};

/**
 * Setter for LocationId
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setLocationId = function(value) {
    this.locationId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getOwnerId = function() {
    return this.ownerId;
};

/**
 * Setter for OwnerId
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setOwnerId = function(value) {
    this.ownerId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getTripId = function() {
    return this.tripId;
};

/**
 * Setter for TripId
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setTripId = function(value) {
    this.tripId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getAddress1 = function() {
    return this.address1;
};

/**
 * Setter for Address1
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setAddress1 = function(value) {
    this.address1 = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getAddress2 = function() {
    return this.address2;
};

/**
 * Setter for Address2
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setAddress2 = function(value) {
    this.address2 = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getPostcode = function() {
    return this.postcode;
};

/**
 * Setter for Postcode
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setPostcode = function(value) {
    this.postcode = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getTelephone = function() {
    return this.telephone;
};

/**
 * Setter for Telephone
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setTelephone = function(value) {
    this.telephone = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getUrl = function() {
    return this.url;
};

/**
 * Setter for Url
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setUrl = function(value) {
    this.url = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getName = function() {
    return this.name;
};

/**
 * Setter for Name
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setName = function(value) {
    this.name = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDescription = function() {
    return this.description;
};

/**
 * Setter for Description
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDescription = function(value) {
    this.description = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getTotalRatings = function() {
    return this.totalRatings;
};

/**
 * Setter for TotalRatings
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setTotalRatings = function(value) {
    this.totalRatings = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {double}
 */
AccommodationDetailedAlgolia.prototype.getAverageRating = function() {
    return this.averageRating;
};

/**
 * Setter for AverageRating
 *
 * @param {double} value
 */
AccommodationDetailedAlgolia.prototype.setAverageRating = function(value) {
    this.averageRating = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getStars = function() {
    return this.stars;
};

/**
 * Setter for Stars
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setStars = function(value) {
    this.stars = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getTypeId = function() {
    return this.typeId;
};

/**
 * Setter for TypeId
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setTypeId = function(value) {
    this.typeId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getLongitude = function() {
    return this.longitude;
};

/**
 * Setter for Longitude
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setLongitude = function(value) {
    this.longitude = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getLatitude = function() {
    return this.latitude;
};

/**
 * Setter for Latitude
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setLatitude = function(value) {
    this.latitude = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getNumRooms = function() {
    return this.numRooms;
};

/**
 * Setter for NumRooms
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setNumRooms = function(value) {
    this.numRooms = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getRedirectAccommodationId = function() {
    return this.redirectAccommodationId;
};

/**
 * Setter for RedirectAccommodationId
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setRedirectAccommodationId = function(value) {
    this.redirectAccommodationId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getRedirectId = function() {
    return this.redirectId;
};

/**
 * Setter for RedirectId
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setRedirectId = function(value) {
    this.redirectId = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getMetaNoIndex = function() {
    return this.metaNoIndex;
};

/**
 * Setter for MetaNoIndex
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setMetaNoIndex = function(value) {
    this.metaNoIndex = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getPageUrl = function() {
    return this.pageUrl;
};

/**
 * Setter for PageUrl
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setPageUrl = function(value) {
    this.pageUrl = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {int}
 */
AccommodationDetailedAlgolia.prototype.getBinaryOptions = function() {
    return this.binaryOptions;
};

/**
 * Setter for BinaryOptions
 *
 * @param {int} value
 */
AccommodationDetailedAlgolia.prototype.setBinaryOptions = function(value) {
    this.binaryOptions = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDescOverview = function() {
    return this.descOverview;
};

/**
 * Setter for DescOverview
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDescOverview = function(value) {
    this.descOverview = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDescRoomInformation = function() {
    return this.descRoomInformation;
};

/**
 * Setter for DescRoomInformation
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDescRoomInformation = function(value) {
    this.descRoomInformation = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDescFacilities = function() {
    return this.descFacilities;
};

/**
 * Setter for DescFacilities
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDescFacilities = function(value) {
    this.descFacilities = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDescFoodDrink = function() {
    return this.descFoodDrink;
};

/**
 * Setter for DescFoodDrink
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDescFoodDrink = function(value) {
    this.descFoodDrink = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDateCreated = function() {
    return this.dateCreated;
};

/**
 * Setter for DateCreated
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDateCreated = function(value) {
    this.dateCreated = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDateUpdated = function() {
    return this.dateUpdated;
};

/**
 * Setter for DateUpdated
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDateUpdated = function(value) {
    this.dateUpdated = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getDateRemoved = function() {
    return this.dateRemoved;
};

/**
 * Setter for DateRemoved
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setDateRemoved = function(value) {
    this.dateRemoved = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {array}
 */
AccommodationDetailedAlgolia.prototype.getLocationPath = function() {
    return this.locationPath;
};

/**
 * Setter for LocationPath
 *
 * @param {array} value
 */
AccommodationDetailedAlgolia.prototype.setLocationPath = function(value) {
    this.locationPath = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {array}
 */
AccommodationDetailedAlgolia.prototype.getPhotos = function() {
    return this.photos;
};

/**
 * Setter for Photos
 *
 * @param {array} value
 */
AccommodationDetailedAlgolia.prototype.setPhotos = function(value) {
    this.photos = value;
};

/**
 * An array of information from Tripadvisor
 *
 * @return {TripadvisorDetailedResponse}
 */
AccommodationDetailedAlgolia.prototype.getTripadvisor = function() {
    return this.tripadvisor;
};

/**
 * Setter for Tripadvisor
 *
 * @param {TripadvisorDetailedResponse} value
 */
AccommodationDetailedAlgolia.prototype.setTripadvisor = function(value) {
    this.tripadvisor = value;
};

/**
 * Any external mappings to commerce partners. E.g Package Holidays with Traveltek
 *
 * @return {array}
 */
AccommodationDetailedAlgolia.prototype.getCommerceMappings = function() {
    return this.commerceMappings;
};

/**
 * Setter for CommerceMappings
 *
 * @param {array} value
 */
AccommodationDetailedAlgolia.prototype.setCommerceMappings = function(value) {
    this.commerceMappings = value;
};

/**
 * Algolia record Id
 *
 * @return {string}
 */
AccommodationDetailedAlgolia.prototype.getObjectID = function() {
    return this.objectID;
};

/**
 * Setter for ObjectID
 *
 * @param {string} value
 */
AccommodationDetailedAlgolia.prototype.setObjectID = function(value) {
    this.objectID = value;
};

/**
 * TODO: Write general description for this method
 *
 * @return {HighlightResult}
 */
AccommodationDetailedAlgolia.prototype.getHighlightResult = function() {
    return this.highlightResult;
};

/**
 * Setter for HighlightResult
 *
 * @param {HighlightResult} value
 */
AccommodationDetailedAlgolia.prototype.setHighlightResult = function(value) {
    this.highlightResult = value;
};

/**
 * Any ranking information for the search this object belongs to. Distance, rating etc.
 *
 * @return {RankingInfo}
 */
AccommodationDetailedAlgolia.prototype.getRankingInfo = function() {
    return this.rankingInfo;
};

/**
 * Setter for RankingInfo
 *
 * @param {RankingInfo} value
 */
AccommodationDetailedAlgolia.prototype.setRankingInfo = function(value) {
    this.rankingInfo = value;
};

/**
 * Algolia Lat Lon information
 *
 * @return {Geoloc|null}
 */
AccommodationDetailedAlgolia.prototype.getGeoloc = function() {
    return this.geoloc;
};

/**
 * Setter for Geoloc
 *
 * @param {Geoloc|null} value
 */
AccommodationDetailedAlgolia.prototype.setGeoloc = function(value) {
    this.geoloc = value;
};

module.exports = AccommodationDetailedAlgolia;


text:
module CfnConverter
  module Patches
    class RemoveMultipleSubnet < Patch
      include PatchUtils

      def initialize
      end

      def need?(template, _parameters)
        return false unless template[:Resources]
        !template[:Resources].select(&type?('AWS::ElasticLoadBalancing::LoadBalancer')).empty?
      end

      def apply(template, _parameters)
        template = template.deep_dup

        subnets = template[:Resources].select(&type?('AWS::EC2::Subnet'))
        remove_resource(template, *subnets.keys.slice(1..-1))
      end
    end
  end
end


text:
<!doctype html>

    <title>Code coverage report for dms/server/config/</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files dms/server/config/

        64%
        Statements
        16/25

        100%
        Branches
        0/0

        100%
        Functions
        0/0

        64%
        Lines
        16/25

   File

   Statements

   Branches

   Functions

   Lines

	config.js

	100%
	1/1
	100%
	0/0
	100%
	0/0
	100%
	1/1

	db.js

	62.5%
	15/24
	100%
	0/0
	100%
	0/0
	62.5%
	15/24

  Code coverage
  generated by istanbul at Wed Sep 28 2016 00:56:01 GMT+0300 (EAT)


text:
namespace mom {

class EICBFM : public CFIE {
    using BlkPtr    = std::shared_ptr<component::CBF_Block>;
    using MatArray  = std::vector<Qcx_mat>;
public:
    EICBFM();
    ~EICBFM();
public:
    void    init(component::ConfigLoader* ploader) override;
    void    solve() override;
    void    output() override;
    void    clear() override;
    void    reportInfo(Qostream& strm) const override;
protected:
    void    prepareCBF(int max, int doublePole, int spacing);
    void    generateCBFs();
    void    calculateCBFs(const component::Block& blk, int curBlk);
    void    generateVMatrix(std::vector<int>& flds);
    void    fillMonostaticV();
    void    reducedZ();
    void    reducedV();
    void    reducedMonoV();
    void    constructI();
    void    constructMonoI();
    value_t getMonoRCS(size_t inc_id, const VectorR3& sca_k) const;
    Complex getV(int f);
protected:
    int         validBlks;
    int         m_spacing;
    int         m_poles, m_phis, m_thetas;
    int         reducedCols;
    BlkPtr      pBlock;
    MatArray    JkArray;
    Qcx_mat     cbfZ;
    Qcx_vec     cbfV;
    Qcx_mat     tmpBlkZ;
    Qcx_mat     tmpBlkVJArray;
    Qcx_mat     monoV_, monoI_;
    Qcx_mat     cbfmonoV_;
    Qofstream   debug;
};

} // namespace mom


text:
describe("FrameUtils suite", function() {
  var black = '#000000';
  var red = '#ff0000';
  var transparent = Constants.TRANSPARENT_COLOR;

  // shortcuts
  var toFrameGrid = test.testutils.toFrameGrid;
  var frameEqualsGrid = test.testutils.frameEqualsGrid;

  it("merges 2 frames", function () {
    var B = black, R = red, T = transparent;
    var frame1 = pskl.model.Frame.fromPixelGrid([
      [B, T],
      [T, B]
    ]);

    var frame2 = pskl.model.Frame.fromPixelGrid([
      [T, R],
      [R, T]
    ]);

    var mergedFrame = pskl.utils.FrameUtils.merge([frame1, frame2]);
    frameEqualsGrid(mergedFrame, [
      [B, R],
      [R, B]
    ]);
  });

  it("returns same frame when merging single frame", function () {
    var B = black, T = transparent;
    var frame1 = pskl.model.Frame.fromPixelGrid(toFrameGrid([
      [B, T],
      [B, T]
    ]));

    var mergedFrame = pskl.utils.FrameUtils.merge([frame1]);
    frameEqualsGrid(mergedFrame, [
      [B, T],
      [B, T]
    ]);
  });

  var checkPixelsColor = function (frame, pixels, color) {
    pixels.forEach(function (pixel) {
      var pixelColor = frame.getPixel(pixel[0], pixel[1]);
      expect(pixelColor).toBe(color);
    });
  };

  it ("converts an image to a frame", function () {
    var B = black, T = transparent;
    var frame1 = pskl.model.Frame.fromPixelGrid([
      [B, T],
      [T, B]
    ]);

    var image = pskl.utils.FrameUtils.toImage(frame1);
    expect(image.width).toBe(2);
    expect(image.height).toBe(2);

    var biggerImage = pskl.utils.FrameUtils.toImage(frame1, 3);
    expect(biggerImage.width).toBe(6);
    expect(biggerImage.height).toBe(6);

    var biggerFrame = pskl.utils.FrameUtils.createFromImage(biggerImage);

    frameEqualsGrid(biggerFrame, [
      [B, B, B, T, T, T],
      [B, B, B, T, T, T],
      [B, B, B, T, T, T],
      [T, T, T, B, B, B],
      [T, T, T, B, B, B],
      [T, T, T, B, B, B]
    ]);
  });

  it ("[LayerUtils] creates frames from a simple spritesheet", function () {
    var B = black, R = red;

    // original image in 4x2
    var frame = pskl.model.Frame.fromPixelGrid(toFrameGrid([
      [B, R, B, R],
      [R, B, B, R]
    ]));

    var spritesheet = pskl.utils.FrameUtils.toImage(frame);

    // split the spritesheet by 4
    var frames = pskl.utils.FrameUtils.createFramesFromSpritesheet(spritesheet, 4);

    // expect 4 frames of 1x2
    expect(frames.length).toBe(4);

    // verify frame content
    frameEqualsGrid(frames[0], [
      [B],
      [R]
    ]);
    frameEqualsGrid(frames[1], [
      [R],
      [B]
    ]);
    frameEqualsGrid(frames[2], [
      [B],
      [B]
    ]);
    frameEqualsGrid(frames[3], [
      [R],
      [R]
    ]);
  });

  it ("supports null values in frame array", function () {
    var B = black, T = transparent;
    var frame = pskl.model.Frame.fromPixelGrid([
      [B, null],
      [null, B]
    ]);

    var image = pskl.utils.FrameUtils.toImage(frame);

    // transform back to frame for ease of testing
    var testFrame = pskl.utils.FrameUtils.createFromImage(image);
    frameEqualsGrid(testFrame, [
      [B, T],
      [T, B]
    ]);
  });
});


text:
<resources>
    <!-- Item sizes. -->
    <dimen name="image_profile_size">100dp</dimen>
    <dimen name="item_app_size">80dp</dimen>

    <dimen name="border_profile_size">25dp</dimen>
    <dimen name="border_app_size">8dp</dimen>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">14dp</dimen>
    <dimen name="activity_vertical_margin">14dp</dimen>
    <dimen name="image_profile_margin">5dp</dimen>
    <dimen name="container_apps_margin">15dp</dimen>
    <dimen name="grid_apps_margin">14dp</dimen>
    <dimen name="related_margin">2dp</dimen>

</resources>


text:
[![](https://travis-ci.org/mattcomi/ReflectedStringConvertible.svg?branch=master)](https://travis-ci.org/mattcomi/ReflectedStringConvertible)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![](https://img.shields.io/cocoapods/v/ReflectedStringConvertible.svg?style=flat)](https://cocoapods.org/pods/ReflectedStringConvertible)
[![Platform](https://img.shields.io/cocoapods/p/ReflectedStringConvertible.svg?style=flat)](http://cocoadocs.org/docsets/ReflectedStringConvertible)

# ReflectedStringConvertible
A protocol that extends `CustomStringConvertible` and uses reflection to add a
detailed textual representation to any class. Two styles are supported:

1. `Normal`: Similar to Swift's default textual representation of structs.
2. `JSON`: Pretty JSON representation.

## Installation

### Cocoapods

Add the following to your Podfile:

```
pod 'ReflectedStringConvertible'
```

### Carthage

Add the following to your Cartfile:

```
github "mattcomi/ReflectedStringConvertible"
```

## Usage

Simply import `ReflectedStringConvertible` and conform to the
`ReflectedStringConvertible` protocol:

```swift
import ReflectedStringConvertible

class YourClass: ReflectedStringConvertible {
  // that's all.
}
```

For example:

```swift
class Person: ReflectedStringConvertible {
  var name: String
  var age: Int

  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}
```

`print(Person(name: "Matt", age: 33))` outputs:

```
Person(name: "Matt", age: 33)
```

A style may be specified with `reflectedDescription(style:)`. The default style is `Normal`. That is, calling `description` is the same as calling `reflectedDescription(.Normal)`.

For example, `print(Person(name: "Matt", age: 33).reflectedDescription(.JSON))` outputs:

```
{
  "age" : 33,
  "name" : "Matt"
}
```

Refer to the  [API Documentation](http://cocoadocs.org/docsets/ReflectedStringConvertible) for further information.

## Features

### `ReflectedStringConvertible` stored properties

`ReflectedStringConvertible` objects with `ReflectedStringConvertible` stored properties are handled correctly:

```swift
class Movie: ReflectedStringConvertible {
  var title: String
  var year: Int

  // another ReflectedStringConvertible
  var director: Person

  init(title: String, year: Int, director: Person) {
    self.title = title
    self.year = year
    self.director = director
  }
}

let george = Person(name: "George Miller", age: 71)
let movie = Movie(title: "Mad Max", year: 2015, director: george)
```

`print(movie.reflectedDescription(.Normal)` (or just `print(movie)`) outputs:

```
Movie(title: "Mad Max", year: 2015, director: Person(name: "George Miller", age: 71))
```

And `print(movie.reflectedDescription(.JSON))` outputs:

```
{
  "title" : "Mad Max",
  "year" : 2015,
  "director" : {
    "age" : 71,
    "name" : "George Miller"
  }
}
```

### Collections

`ReflectedStringConvertible` objects within `Array`, `Dictionary` and `Set` collections are handled correctly:

```swift
class Series: ReflectedStringConvertible {
  var title: String
  var cast: [Person]

  init(title: String, cast: [Person]) {
    self.cast = cast
  }
}

var cast = [Person]()

cast.append(Person(name: "Justin Theroux", age: 44))
cast.append(Person(name: "Carrie Coon", age: 35))

let series = Series(title: "The Leftovers", cast: cast)
```

`print(series)` outputs:

```
TVShow(title: "The Leftovers", cast: [Person(name: "Justin Theroux", age: 44), Person(name: "Carrie Coon", age: 35)])
```

`print(series.reflectedDescription(.JSON))` outputs:

```
{
  "title" : "The Leftovers",
  "cast" : [
    {
      "age" : 44,
      "name" : "Justin Theroux"
    },
    {
      "age" : 35,
      "name" : "Carrie Coon"
    }
  ]
}
```

## Credits

Developed by Matt Comi ([@mattcomi](http://twitter.com/mattcomi))


text:
<?php

namespace Users\Form;

use Zend\Form\Form;

class UsersForm extends Form
{
    public function __construct($name = null)
    {
        // we want to ignore the name passed
        parent::__construct('users');
    }
}

?>


text:
{{<unbranded}}

{{$pageTitle}}
	TEMP
{{/pageTitle}}

{{$content}}

		{{>includes/fleets_head}}

		<input type="hidden" name="count" value="1" />

            Nice Multiple Form Fields

                <form class="input-append">

<input autocomplete="off" class="input" id="field1" name="prof1" type="text" placeholder="Type something" data-items="8"/><button id="b1" class="btn add-more" type="button">+</button>

                </form>

            Press + to add another form field :)

{{/content}}

{{/unbranded}}


text:
layout: page
title: About
permalink: /about/
icon: octicon-heart
published: false
---

自我介绍什么的,最讨厌了!


text:
"""

Util - hellanzb misc functions

(c) Copyright 2005 Philip Jenvey, Ben Bangert
[See end of file]
"""
import errno, os, re, signal, string, sys, thread, Hellanzb
try:
    from distutils import spawn
except:
    pass
from heapq import heapify, heappop, heappush
from os.path import normpath
from random import randint
from shutil import move
from threading import Condition
from traceback import print_stack
from twisted.internet import protocol, utils
from Hellanzb.Log import *
from Queue import Empty, Queue
from StringIO import StringIO

__id__ = '$Id$'

# Size of buffer for file i/o
BUF_SIZE = 16 * 1024

class FatalError(Exception):
    """ An error that will cause the program to exit """

class EmptyForThisPool(Empty):
    """ The queue is empty in terms of our current serverPool, but there are still segments to
    be downloaded for alternate download pools """
    pass

class OutOfDiskSpace(Exception):
    """ Out of disk space """
    pass

class PoolsExhausted(Exception):
    """ Attempts to download a segment on all known server pools failed """
    pass

class IDPool:
    """ Returns a unique identifier, used for keying NZBs and their archives """
    nextId = 0
    skipIds = []
    def getNextId():
        """ Return a new unique identifier """
        while IDPool.nextId in IDPool.skipIds:
            IDPool.nextId += 1
        id = IDPool.nextId
        IDPool.nextId += 1
        return id
    getNextId = staticmethod(getNextId)

SPLIT_CMDLINE_ARGS_RE = re.compile(r'( |"[^"]*")')
class Topen(protocol.ProcessProtocol):
    """ Ptyopen (popen + extra hellanzb stuff)-like class for Twisted. Runs a sub process
    and wait()s for output """

    activePool = []

    def __init__(self, cmd, postProcessor, captureStdErr = True):
        # FIXME: seems like twisted just writes something to stderr if there was a
        # problem. this class should probably always capture stderr, optionally to another
        # stream
        self.cmd = cmd
        self.captureStdErr = captureStdErr
        self.outBuf = StringIO()
        self.finished = Condition()
        self.returnCode = None
        self.isRunning = False
        self.postProcessor = postProcessor

        self.threadIdent = thread.get_ident()

        # ProcessProtocol has no instructor (when I wrote this). just incase
        if hasattr(protocol.ProcessProtocol, '__init__') and \
                callable(protocol.ProcessProtocol.__init__):
            protocol.ProcessProtocol.__init__(self)

    def getPrettyCmd(self):
        """ Return a pretty representation of this command (one that could be ran via the
        command line) """
        quote = lambda item: ' ' in item and '"%s"' % item.replace('"', r'\"') or item
        return ' '.join(map(quote, self.cmd))
    prettyCmd = property(getPrettyCmd)

    def received(self, data):
        self.outBuf.write(data)

    def outReceived(self, data):
        self.received(data)

    def errReceived(self, data):
        if self.captureStdErr:
            self.received(data)

    def outputError(self, err):
        self.transport.loseConnection()

    def processEnded(self, reason):
        self.returnCode = reason.value.exitCode

        from Hellanzb.Log import debug
        import thread
        debug('processEnded THREAD ID: ' + str(thread.get_ident()) + ' (' + \
                  self.prettyCmd + ') ' + 'aquiring lock')
        self.finished.acquire()
        debug('processEnded THREAD ID: ' + str(thread.get_ident()) + ' (' + \
                  self.prettyCmd + ')' + ' (pid: ' + str(self.getPid()) + ')')
        self.finished.notify()
        self.finished.release()

        self.isRunning = False
        Topen.activePool.remove(self)

    def kill(self):
        from Hellanzb.Log import debug, error
        if isWindows():
            warn('Left running process: %s' % self.prettyCmd)
            return
        if self.isRunning:
            try:
                os.kill(self.getPid(), signal.SIGKILL)
            except OSError, ose:
                error('Unexpected problem while kill -9ing pid: ' + str(self.getPid()) + \
                      ' process: ' + self.prettyCmd, ose)
            except Exception, e:
                debug('could not kill process: ' + self.prettyCmd + ': ' + str(e))

        self.postProcessor.killed = True

        self.finished.acquire()
        self.finished.notify()
        self.finished.release()

    def parseCmdToList(self, cmd):
        cleanDoubleQuotesRe = re.compile(r'^"|"$')
        args = []
        fields = SPLIT_CMDLINE_ARGS_RE.split(cmd)
        for field in fields:
            if field == '' or field == ' ':
                continue
            args.append(cleanDoubleQuotesRe.sub('', field))
        return args

    def readlinesAndWait(self):
        from twisted.internet import reactor
        self.isRunning = True
        Topen.activePool.append(self)

        self.finished.acquire()
        from Hellanzb.Log import debug
        import thread
        debug('spawnProcess THREAD ID: ' + str(thread.get_ident()) + ' (' + \
                  self.prettyCmd + ')')

        # The reactor could have fallen asleep on us in -Lp mode! Why? I'm not sure, but
        # it dies after the first par2 process (Topen call) =[
        reactor.wakeUp()

        # Have the main, twisted thread, run the process. If we trigger spawnProcess from
        # a separate thread (which PostProcessor/Topens are always used from) instead, bad
        # things can occur (on Linux 2.6.x we can end up with defunct processes -- Trac
        # ticket #33). Running any twisted call from a non twisted thread is asking for
        # trouble. We also MUST usePTY, otherwise the processes receive signals (in
        # particular, SIGINT, rendering our first CTRL-C ignoring code useless, as it ends
        # up killing our sub processes)
        reactor.callFromThread(reactor.spawnProcess, self, self.cmd[0], self.cmd, os.environ,
                               usePTY = (not isWindows() and not isSolaris()) and 1 or 0)

        self.finished.wait()
        self.finished.release()

        # Here is where PostProcessor will typically die. After a process has been killed
        checkShutdown()

        # prepare the outbuffer (LAME)
        output = [line + '\n' for line in self.outBuf.getvalue().split('\n')]

        return output, self.returnCode

    def getPid(self):
        """ Return the pid of the process if it exists """
        if self.transport:
            return getattr(self.transport, 'pid', None)
        return None

    def killAll():
        """ kill -9 all active topens """
        for active in Topen.activePool:
            active.kill()
    killAll = staticmethod(killAll)

# Future optimization: Faster way to init this from xml files would be to set the entire
# list backing the queue in one operation (instead of putting 20k times)
# can heapq.heapify(list) help?
class PriorityQueue(Queue):
    """ Thread safe priority queue. This is the easiest way to do it (Queue.Queue
    providing the thread safety and heapq providing priority). We may be able to get
    better performance by using something other than heapq, but hellanzb use of pqueues is
    limited -- so performance is not so important. Notes on performance:

    o An O(1) priority queue is always preferable, but I'm not sure that's even feasible
      w/ this collection type and/or python.
    o From various google'd python hacker benchmarks it looks like python lists backed
      pqueues & bisect give you pretty good performance, and you probably won't benefit
      from heap based pqueues unless you're dealing with > 10k items. And dicts don't
      actually seem to help
    """
    def __init__(self):
        """ Python 2.4 replaces the list backed queue with a collections.deque, so we'll just
        emulate 2.3 behavior everywhere for now """
        Queue.__init__(self)
        self.queue = []

    def __len__(self):
        return len(self.queue)

    def clear(self):
        """ empty the queue """
        if len(self.queue):
            self.mutex.acquire()
            del self.queue
            self.queue = []
            if not hasattr(self, 'not_empty'):
                # python 2.3
                self.esema.acquire()
            self.mutex.release()

    def _put(self, item):
        """ Assume Queue is backed by a list. Add the new item to the list, taking into account
            priority via heapq """
        heappush(self.queue, item)

    def _get(self):
        """ Assume Queue is backed by a list. Pop off the first item, taking into account priority
            via heapq """
        return heappop(self.queue)

    def dequeueItems(self, items):
        """ Explicitly dequeue the specified items. Yes, this queue supports random access """
        succeded = items[:]
        self.mutex.acquire()
        for item in items:
            try:
                self.queue.remove(item)
            except ValueError:
                succeded.remove(item)

        heapify(self.queue)

        # python 2.3
        if not hasattr(self, 'not_empty') and not len(self.queue):
            self.esema.acquire()
        self.mutex.release()

        return succeded

class UnicodeList(list):
    """ Ensure all contained objects are casted to unicode. Allows Nones """
    def remove(self, value):
        super(UnicodeList, self).remove(toUnicode(value))

    def append(self, value):
        super(UnicodeList, self).append(toUnicode(value))

    def extend(self, iterable):
        super(UnicodeList, self).extend([toUnicode(value) for value in iterable])

    def insert(self, index, value):
        super(UnicodeList, self).insert(index, toUnicode(value))

def getLocalClassName(klass):
    """ Get the local name (no package/module information) of the specified class instance """
    klass = str(klass)

    lastDot = klass.rfind('.')
    if lastDot > -1:
        klass = klass[lastDot + 1:]

    return klass

def assertIsExe(exe_list):
    """ Abort the program if none of the specified files are executable """
    if not isinstance(exe_list, (list, tuple)):
        exe_list = [exe_list]
    if exe_list:
        for exe in exe_list:
            if exe == os.path.basename(exe):
                try:
                    fullPath = spawn.find_executable(exe)
                except:
                    raise FatalError('Cannot continue program, your platform does not support searching the path for an executable and you did not supply the full path to the %s executable.' % exe)
            else:
                fullPath = exe
            if fullPath != None and os.access(fullPath, os.X_OK):
                return fullPath
    raise FatalError('Cannot continue program, required executable not found: \'' + \
                     exe + '\'')

def dirHasFileType(dirName, fileExtension):
    return dirHasFileTypes(dirName, [ fileExtension ])

def dirHasFileTypes(dirName, fileExtensionList):
    """ Determine if the specified directory contains any files of the specified type -- that
    type being defined by its filename extension. the match is case insensitive """
    for file in os.listdir(dirName):
        ext = getFileExtension(file)
        if ext:
            for type in fileExtensionList:
                if ext.lower() == type.lower():
                    return True
    return False

def getFileExtension(fileName):
    """ Return the extenion of the specified file name, in lowercase """
    if len(fileName) > 1 and fileName.find('.') > -1:
        return string.lower(os.path.splitext(fileName)[1][1:])

def touch(fileName):
    """ Set the access/modified times of this file to the current time. Create the file if
    it does not exist """
    fd = os.open(fileName, os.O_WRONLY | os.O_CREAT, 0666)
    os.close(fd)
    os.utime(fileName, None)

NEWZBIN_FILE_PREFIX = r'^(?:(?:msgid|NZB)_)?(\d+)_(.*)'
NEWZBIN_FILE_SUFFIX = r'\.nzb$'
NEWZBIN_FILE_SUFFIX_RE = re.compile(r'\.nzb$', re.I)
NEWZBIN_FILE_RE = re.compile(NEWZBIN_FILE_PREFIX + NEWZBIN_FILE_SUFFIX, re.I)
def archiveName(dirName, unformatNewzbinNZB = True):
    """ Extract the name of the archive from the archive's absolute path, or its .nzb file
    name. Optionally remove newzbin 'msgid_99999' or 'NZB_' prefixes and the '.nzb' suffix
    from a newzbin formatted .nzb filename """
    from Hellanzb.PostProcessorUtil import DirName
    # pop off separator and basename
    while dirName[len(dirName) - 1] == os.sep:
        dirName = dirName[0:len(dirName) - 1]
    if isinstance(dirName, DirName) and dirName.isSubDir():
        name = os.path.basename(dirName.parentDir) + \
        normpath(dirName).replace(normpath(dirName.parentDir), '')
    else:
        name = os.path.basename(dirName)

    # Strip the msg_id and .nzb extension from an nzb file name
    if unformatNewzbinNZB:
        newzbinMatch = NEWZBIN_FILE_RE.match(name)
        if newzbinMatch:
            name = newzbinMatch.group(2)
        else:
            name = NEWZBIN_FILE_SUFFIX_RE.sub('', name)

    return name

def getMsgId(archiveName):
    """ Grab the msgid from a newzbin filename/archiveName """
    archiveName = os.path.basename(archiveName)
    match = NEWZBIN_FILE_RE.match(archiveName)
    if match:
        return match.group(1)
    return None

def checkShutdown(message = 'Shutting down..'):
    """ Raise a SystemExit exception if the SHUTDOWN flag has been set """
    try:
        if Hellanzb.SHUTDOWN:
            debug(message)
            raise SystemExit(Hellanzb.SHUTDOWN_CODE)
        return False

    except (AttributeError, NameError):
        # typical during app shutdown
        raise SystemExit(Hellanzb.SHUTDOWN_CODE)

    except Exception, e:
        print 'Error in Util.checkShutdown' + str(e)
        raise SystemExit(Hellanzb.SHUTDOWN_CODE)

# FIXME: defineServer and anything else called from the config file should be moved into
# their own ConfigFileFunctions Module. all config file functions should: Never call
# debug()
def defineServer(**args):
    """ Define a usenet server """
    id = args['id']
    Hellanzb.SERVERS[id] = {}

    for var in (args):
        Hellanzb.SERVERS[id][var] = args[var]

def truncate(str, length = 60, reverse = False):
    """ Truncate a string to the specified length. Appends '...' to the string if truncated --
    and those three periods are included in the specified length """
    if str == None:
        return str

    if len(str) > int(length):
        if reverse:
            return '...' + str[-(int(length) - 3):]
        else:
            return str[0:int(length) - 3] + '...'

    return str

def rtruncate(*args, **kwargs):
    """ Reverse truncate (truncate from the beginning) """
    return truncate(reverse = True, *args, **kwargs)

# FIXME: textwrap.fill() should replace this function
def truncateToMultiLine(line, length = 60, prefix = '', indentPrefix = None):
    """ Parse a one line message into multiple lines of the specified length """
    multiLine = StringIO()
    numLines = ((len(line) - 1) / length) + 1
    offset = 0
    for i in range(numLines):
        if indentPrefix != None and i > 0:
            multiLine.write(indentPrefix + line[offset:length * (i + 1)])
        else:
            multiLine.write(prefix + line[offset:length * (i + 1)])

        if i + 1 < numLines:
            multiLine.write('\n')

        offset += length
    return multiLine.getvalue()

def flattenDoc(docString):
    """ Take an indented doc string, and remove its newlines and their surrounding whitespace
    """
    clean = ''
    lines = docString.split('\n')
    for line in lines:
        clean += line.strip() + ' '
    return clean

RENAME_SUFFIX = '_hellanzb_renamed'
def hellaRename(filename):
    """ Rename a dupe file to filename _hellanzb_renamedX, and return the renamed filename
    """
    if os.path.exists(filename):
        # Rename the dir if it exists already
        renamedPrefix = filename + RENAME_SUFFIX
        i = 0
        while os.path.exists(renamedPrefix + str(i)):
            i += 1
        renamed = renamedPrefix + str(i)
        move(filename, renamed)
        return renamed

DUPE_SUFFIX = '_hellanzb_dupe'
DUPE_SUFFIX_RE = re.compile('(.*)' + DUPE_SUFFIX + '(\d{1,4})$')
def cleanDupeName(filename):
    """ For the given duplicate filename, return a tuple containing the non-duplicate
    filename, and the duplicate filename index. Returns an index of -1 for non-duplicate
    filenames.

    e.g.:

    cleanDupeName('/test/file') would return:
    ('/test/file', -1)

    cleanDupeName('/test/file_hellanzb_dupe0') would return:
    ('/test/file', 0)
    """
    i = -1
    dupeMatch = DUPE_SUFFIX_RE.match(filename)

    # If this is a dupe name already, pull the DUPE_SUFFIX off
    if dupeMatch:
        filename = dupeMatch.group(1)
        i = int(dupeMatch.group(2))
    return filename, i

def _nextDupeName(filename):
    """ Return the next dupeName in the dupeName sequence """
    filename, i = cleanDupeName(filename)

    # Increment dupeName sequence
    renamed = filename + DUPE_SUFFIX + str(i + 1)
    return renamed

def dupeName(filename, checkOnDisk = True, eschewNames = [], minIteration = 0):
    """ Returns a new filename with '_hellanzb_dupeX' appended to it (where X is the next
    integer in a sequence producing the first available unique filename on disk). The
    optional checkOnDisk option is mainly intended for use by the nextDupeName
    function. The optional eschewNames list acts as a list of filenames to be avoided --
    as if they were on disk

    e.g.:
    With no files in the /test/ dir,

    dupeName('/test/file') would return:
    '/test/file'

    dupeName('/test/file', eschewNames = ('/test/file')) would return:
    '/test/file_hellanzb_dupe0'

    With the files 'file' and 'file_hellanzb_dupe0' in the /test/ dir,
    dupeName('/test/file') would return:
    '/test/file_hellanzb_dupe1'

    dupeName('/test/file', eschewNames = ('/test/file_hellanzb_dupe1')) would return:
    '/test/file_hellanzb_dupe2'
    """
    if (not checkOnDisk or not os.path.exists(filename)) and minIteration == 0 and \
            filename not in eschewNames:
        return filename

    def onDisk(filename):
        if not checkOnDisk:
            return False
        return os.path.exists(filename)

    i = 0
    while True:
        i += 1
        filename = _nextDupeName(filename)
        if not onDisk(filename) and filename not in eschewNames and i >= minIteration:
            break

    return filename

def nextDupeName(*args, **kwargs):
    """ nextDupeName acts as dupeName, except it will always increment the dupeName sequence
    by at least one time

    e.g.:
    With no files in the /test/ dir,

    nextDupeName('/test/file') would return:
    '/test/file_hellanzb_dupe0'

    nextDupeName('/test/file', eschewNames = ('/test/file_hellanzb_dupe0')) would return:
    '/test/file_hellanzb_dupe1'

    With the files 'file' and 'file_hellanzb_dupe0' in the /test/ dir,
    nextDupeName('/test/file') would return:
    '/test/file_hellanzb_dupe1'

    nextDupeName('/test/file', checkOnDisk = False) would return:
    '/test/file_hellanzb_dupe0'

    nextDupeName('/test/file', checkOnDisk = False,
                 eschewNames = ('/test/file_hellanzb_dupe0')) would return:
    '/test/file_hellanzb_dupe1'
    """
    if not kwargs.has_key('minIteration'):
        kwargs['minIteration'] = 1
    return dupeName(*args, **kwargs)

def walk(root, recurse=0, pattern='*', return_folders=0):
    """ return a recursive directory listing.
    Author: Robin Parmar (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52664)
    """
    import fnmatch, os, string

    # initialize
    result = []

    # must have at least root folder
    try:
            names = os.listdir(root)
    except os.error:
            return result

    # expand pattern
    pattern = pattern or '*'
    pat_list = string.splitfields( pattern , ';' )

    # check each file
    for name in names:
            fullname = os.path.normpath(os.path.join(root, name))

            # grab if it matches our pattern and entry type
            for pat in pat_list:
                    if fnmatch.fnmatch(name, pat):
                            if os.path.isfile(fullname) or (return_folders and os.path.isdir(fullname)):
                                    if os.path.isdir(fullname):
                                            result.append(fullname + '/')
                                    else:
                                            result.append(fullname)
                            continue

            # recursively scan other folders, appending results
            if recurse:
                    if os.path.isdir(fullname) and not os.path.islink(fullname):
                            result = result + walk(fullname, recurse, pattern, return_folders)

    return result

def getStack():
    """ Return the current execution stack as a string """
    s = StringIO()
    print_stack(file = s)
    s = s.getvalue()
    return s

def inMainThread():
    """ whether or not the current thread is the main thread """
    if Hellanzb.MAIN_THREAD_IDENT == thread.get_ident():
        return True
    return False

def prettyEta(etaSeconds):
    """ return a cute eta string from seconds """
    hours = int(etaSeconds / (60 * 60))
    minutes = int((etaSeconds - (hours * 60 * 60)) / 60)
    seconds = etaSeconds - (hours * 60 * 60) - (minutes * 60)
    return '%.2d:%.2d:%.2d' % (hours, minutes, seconds)

def prettyElapsed(seconds):
    """ Return a pretty string representing the elapsed time in hours, minutes, seconds """
    def shiftTo(seconds, shiftToSeconds, shiftToLabel):
        """ Return a pretty string, shifting seconds to the specified unit of measure """
        prettyStr = '%i%s' % ((seconds / shiftToSeconds), shiftToLabel)
        mod = seconds % shiftToSeconds
        if mod != 0:
            prettyStr += ' %s' % prettyElapsed(mod)
        return prettyStr

    seconds = int(seconds)
    if seconds < 60:
        return '%is' % seconds
    elif seconds < 60 * 60:
        return shiftTo(seconds, 60, 'm')
    else:
        return shiftTo(seconds, 60 * 60, 'h')

def unPrettyBytes(prettyBytes):
    """ Convert a string representing a count in KB, MB, or GB to actual bytes as
    an integer """
    reStr = '^(\d+)%sB?$'
    res = {re.compile(reStr % 'K'): 2 ** 10,
               re.compile(reStr % 'M'): 2 ** 20,
               re.compile(reStr % 'G'): 2 ** 30}

    prettyBytes = str(prettyBytes).upper()
    for size_re, size in res.iteritems():
        if size_re.match(prettyBytes):
            return int(size_re.sub(r'\1', prettyBytes)) * size
    return int(prettyBytes)

def toUnicode(str):
    """ Convert the specified string to a unicode string """
    if str == None:
        return str
    elif not isinstance(str, unicode):
        # iso-8859-1 aka latin-1
        return unicode(str, 'iso-8859-1')
    return str

def tempFilename(prefix = 'hellanzb-tmp'):
    """ Return a temp filename, prefixed with 'hellanzb-tmp' """
    return prefix + str(randint(10000000, 99999999))

def prettySize(bytes):
    """ format a byte count for pretty display """
    bytes = float(bytes)

    if bytes < 1024:
            return '<1KB'
    elif bytes < (1024 * 1024):
            return '%dKB' % (bytes / 1024)
    else:
            return '%.1fMB' % (bytes / 1024.0 / 1024.0)

def nuke(filename):
    """ Delete the specified file on disk, ignoring any exceptions """
    try:
        os.remove(filename)
    except Exception, e:
        pass

def validNZB(nzbfilename):
    """ Return true if the specified filename is a valid NZB """
    from Hellanzb.Log import error
    if nzbfilename == None or not os.path.isfile(nzbfilename):
        error('Invalid NZB file: %s' % nzbfilename)
        return False
    elif not os.access(nzbfilename, os.R_OK):
        error('Unable to read NZB file: %s' % nzbfilename)
        return False
    elif archiveName(nzbfilename) == '':
        error('Invalid NZB file (No archive name): %s' % nzbfilename)
        return False
    return True

def ensureDirs(dirNames):
    """ Ensure the specified map of Hellanzb options to their required directory exist and are
    writable, otherwise attempt to create them. Raises a FatalError if any one of them
    cannot be created, or is not writable """
    # NOTE: this function is called prior to Logging is fully setup -- it CANNOT use the
    # logging system
    badPermDirs = []
    for arg, dirName in dirNames.iteritems():
        if not os.path.isdir(dirName):
            try:
                os.makedirs(dirName)
            except OSError, ose:
                raise FatalError('Unable to create directory for option: Hellanzb.' + \
                                 arg + ' dirName: ' + dirName + ' error: ' + str(ose))
        elif not os.access(dirName, os.W_OK):
            badPermDirs.append(dirName)

    if len(badPermDirs):
        dirTxt = 'directory'
        if len(badPermDirs) > 1:
            dirTxt = 'directories'
        err = 'Cannot continue: hellanzb needs write access to ' + dirTxt + ':'

        for dirName in badPermDirs:
            err += '\n' + dirName

        raise FatalError(err)

def uopen(filename, *args, **kwargs):
    """ Open a file. Unicode filenames are specially handled on certain platforms (OS X) """
    if Hellanzb.SYSNAME == "Darwin":
        filename = toUnicode(filename)
    return open(filename, *args, **kwargs)

def isHellaTemp(filename):
    """ Determine whether or not the specified file is a 'hellanzb-tmp-' file """
    return filename.find('hellanzb-tmp-') == 0

def find_packager():
    """ Detect packaging systems such as py2app and py2exe """
    frozen = getattr(sys, 'frozen', None)
    if not frozen:
        # COULD be certain cx_Freeze options or bundlebuilder, nothing to worry about though
        return None
    elif frozen in ('dll', 'console_exe', 'windows_exe'):
        return 'py2exe'
    elif frozen in ('macosx_app',):
        return 'py2app'
    elif frozen is True:
        # it doesn't ALWAYS set this
        return 'cx_Freeze'
    else:
        return '<unknown packager: %r>' % (frozen,)

def isPy2App():
    """ Whether or not this process is running via py2app """
    try:
        return Hellanzb.PACKAGER == 'py2app'
    except AttributeError:
        return find_packager() == 'py2app'

def isWindows():
    """ Whether or not this process is running in Windows (not cygwin) """
    return sys.platform.startswith('win')

def isSolaris():
    """ Whether or not this process is running in Solaris """
    return sys.platform.startswith('sunos')

ONE_MB = float(1024 ** 2)
try:
    import statvfs
    def diskFree(dirName):
        """ Return the disk free space for the specified dir's volume, in MB """
        try:
            s = os.statvfs(dirName)
            return (s[statvfs.F_BFREE] * s[statvfs.F_FRSIZE]) / ONE_MB
        except OSError:
            return 0.0

except AttributeError:
    try:
        import win32api
    except ImportError:
        pass
    def diskFree(dirName):
        """ Return the disk free space for the specified dir's volume, in MB """
        try:
            secp, byteper, freecl, noclu = win32api.GetDiskFreeSpace(dirName)
            return (secp * byteper * freecl) / ONE_MB
        except:
            return 0.0

Hellanzb.CMHELLA = \
'''
           ;;;;            .  .
      ... :liil ...........:..:      ,._    ,._      ...................
      :   l$$$:  _.,._       _..,,._ "$$$b. "$$$b.   `_..,,._        :::
      :   $$$$.d$$$$$$L   .d$$$$$$$$L $$$$:  $$$$: .d$$$$$$$$$;      :::
      :  :$$$$P`  T$$$$: :$$$$`  7$$F:$$$$  :$$$$ :$$$$: `$$$$ __  _  |_
      :  l$$$F   :$$$$$  8$$$l"""""` l$$$l  l$$$l l$$$l   $$$L | ) /_ |_)
      :  $$$$:   l$$$$$L `4$$$bcmang;ACID$::$$$88:`4$$$bmm$$$$;.     ...
      :    ```      ```""              ```    ```    .    ```.     ..:::..
      :..............................................:              `:::`
                                                                      `
'''

Hellanzb.CMHELLA_VERSIONED = \
'''
           ;;;;            .  .
      ... :liil ...........:..:      ,._    ,._      ...................
      :   l$$$:  _.,._       _..,,._ "$$$b. "$$$b.   `_..,,._        :::
      :   $$$$.d$$$$$$L   .d$$$$$$$$L $$$$:  $$$$: .d$$$$$$$$$;      :::
      :  :$$$$P`  T$$$$: :$$$$`  7$$F:$$$$  :$$$$ :$$$$: `$$$$ __  _  |_
      :  l$$$F   :$$$$$  8$$$l"""""` l$$$l  l$$$l l$$$l   $$$L | ) /_ |_)
      :  $$$$:   l$$$$$L `4$$$bcmang;ACID$::$$$88:`4$$$bmm$$$$;.     ...
      :    ```      ```""              ```    ```    .    ```.     ..:::..
      :..............................................:   %s  `:::`
                                                                      `
'''
def cmVersion(version = Hellanzb.version):
    """ try to make Hellanzb.version always look like this: 'V 1 . 0' """
    #cmV = '  V 1 . 0'
    version = version.replace('-trunk', '')
    muck = lambda v : 'v' + v.replace('', ' ').rstrip()
    if len(version) == len('0.10') and version.startswith('0.'):
        version = muck(version)
    elif len(version) == len('1.0'):
        version = muck(version)
        version = ' %s ' % version
    return version

def cmHella(version = Hellanzb.version):
    """ brand the ascii with a properly formatted version number """
    return Hellanzb.CMHELLA_VERSIONED % (cmVersion(version))

def daemonize():
    """ From twisted's twisted.scripts.twistd """
    # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
    if os.fork():   # launch child and...
        os._exit(0) # kill off parent
    os.setsid()
    if os.fork():   # launch child and...
        os._exit(0) # kill off parent again.
    os.umask(077)
    null=os.open('/dev/null', os.O_RDWR)
    for i in range(3):
        try:
            os.dup2(null, i)
        except OSError, e:
            if e.errno != errno.EBADF:
                raise
    os.close(null)

"""
Copyright (c) 2005 Philip Jenvey <pjenvey@groovie.org>
                   Ben Bangert <bbangert@groovie.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author or contributors may not be used to endorse or
   promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

$Id$
"""


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>boostui</title>
    <meta name="viewport" content="width=device-width,user-scalable=no">

badge

button

checkbox

counter

dialog

fixedbar

gallery

header

list

loading

nav

panel

picture

slider

tab

tabnav

toast


text:
//
// Copyright 2013 Facebook
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#import <Foundation/Foundation.h>

#import "Testable.h"

@class XcodeSubjectInfo;

/**
 * TestableExecutionInfo holds all the extra information we have to collect
 * in order to run a test bundle.
 */
@interface TestableExecutionInfo : NSObject

/**
 * The `Testable` this info belongs to.
 */
@property (nonatomic, retain) Testable *testable;

/**
 * The key/value pairs from `-showBuildSettings` for this testable.
 */
@property (nonatomic, copy) NSDictionary *buildSettings;

/**
 * Will contain an error message if retrieving build settings with xcodebuild have failed
 */
@property (nonatomic, copy) NSString *buildSettingsError;

/**
 * A list of all test cases in the bundle, the form of:
 * ['SomeClass/testA', 'SomeClass/testB']
 *
 * These are fetched via otest-query.  May be nil if an error occurred.
 */
@property (nonatomic, copy) NSArray *testCases;

/**
 * Will contain an error message if `otest-query` fails.
 */
@property (nonatomic, copy) NSString *testCasesQueryError;

/**
 * Any arguments that should be passed to otest, with all macros expanded.
 */
@property (nonatomic, copy) NSArray *expandedArguments;

/**
 * Any environment that should be set for otest, with all macros expanded.
 */
@property (nonatomic, copy) NSDictionary *expandedEnvironment;

/**
 * @return A populated TestableExecutionInfo instance.
 */
+ (instancetype)infoForTestable:(Testable *)testable
               xcodeSubjectInfo:(XcodeSubjectInfo *)xcodeSubjectInfo
            xcodebuildArguments:(NSArray *)xcodebuildArguments
                        testSDK:(NSString *)testSDK
                        cpuType:(cpu_type_t)cpuType;
@end


text:
package org.aksw.kbox.kibe;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.aksw.kbox.kns.KNSServer;
import org.aksw.kbox.kns.KNSServerList;
import org.aksw.kbox.kns.KNSServerListVisitor;
import org.apache.log4j.Logger;

public class URLKNSServerList implements KNSServerList {

	private URL serverURL;

	private final static Logger logger = Logger.getLogger(URLKNSServerList.class);

	private final static String DEFAULT_KNS_SERVER_TABLE_URL = "table.server.kns";

	public URLKNSServerList(URL serverURL) {
		this.serverURL = serverURL;
	}

	@Override
	public boolean visit(KNSServerListVisitor visitor) throws Exception {
		URL serverTable = new URL(serverURL + org.aksw.kbox.URL.SEPARATOR + DEFAULT_KNS_SERVER_TABLE_URL);
		boolean next = true;
		try(InputStream is = serverTable.openStream()) {
			try(BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
				String line = null;
				while((line = in.readLine()) != null) {
				    KNSServer knsServer = null;
					try {
						knsServer = KNSServerFactory.get(line);
						next = visitor.visit(knsServer);
						if(!next) {
							return false;
						}
					} catch (Exception e) {
						logger.error("KNS Server Table entry could not be parsed: " + line, e);
					}
				}
			}
		}
		return next;
	}
}


text:
var app = angular.module("jeopardy", []);

app.service("categoryService", function($http, $q)
{
	var deferred = $q.defer();

	/*http.get('files/questions.json').then(function(data)
    {
        deferred.resolve(data);
    });*/

	/*this.getQuestions = function()
	{
		return deferred.promise;
	};*/

});


text:
@implementation ItemDefinition

@synthesize name;
@synthesize identifier, price, sellprice, category;

+(id) readFromFile:(FDFileStream *)stream
{
	// Should implement from sub class

	return nil;
}

-(NSString *) getAttributeString
{
	return nil;

}

// Since money is special, put this function here
-(BOOL) isMoney
{
	return (identifier / 100 == 9);
}

-(int) getMoneyQuantity
{
	switch (identifier) {
		case 901:
			return 3000;
			break;
		case 902:
			return 5000;
			break;
		default:
			break;
	}
	return 0;
}

-(BOOL) isAttackItem
{
	return identifier / 100 == 2;
}

-(BOOL) isDefendItem
{
	return identifier / 100 == 3;
}

@end


text:
"use strict";
var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic');
var static_1 = require('@angular/upgrade/static');
var module_1 = require('./module');
platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(module_1.AppModule).then(function (platformRef) {
    var upgrade = platformRef.injector.get(static_1.UpgradeModule);
    upgrade.bootstrap(document.body, ['upgradeApp'], { strictDi: true });
});
//# sourceMappingURL=main.js.map