text:
/*
 * CoursesPlus Abstraction Layer
 * This abstracts away things like storage or resource-ness.
 * Firefox version
 */

cpal = {};

/*
 * cpal.extension
 */
cpal.extension = {};

cpal.extension.getBrowser = function() {
	return "firefox";
};
cpal.extension.getBrowserVersion = function() {
	return navigator.appVersion.split("/")[3];//.replace(" Firefox", "");
};
cpal.extension.getExtensionVersion = function() {
	return "??";
};

/*
 * cpal.logging
 */
cpal.logging = {};

cpal.logging.getReportLink = function() {
	return "";
};
cpal.logging.specificErrorDetails = function() {
	var details = "";

		details += "Platform: Mozilla Firefox";
		details += "\n";
		details += "Extension ID: " + chrome.runtime.id;
		details += "\n"

	return details;
};

/*
 * cpal.resources
 */
cpal.resources = {};

cpal.resources._baseUrl = self.options.dataTestUrl.replace("WOOTWOOTWOOT", "");
cpal.resources.getURL = function(item) {
	return cpal.resources._baseUrl + item;
};

/*
 * cpal.request
 */
cpal.request = {};

cpal.request.addBeforeSendHeaders = function(urls, listener) {

};

/*
 * cpal.storage
 */
cpal.storage = {};

cpal.storage.clear = function(callback) {
	callback();
};
cpal.storage.getKey = function(keyName, callback) {
	callback(undefined, keyName);
};
cpal.storage.getAll = function(callback) {
	callback({});
};
cpal.storage.setKey = function(keyName, keyValue, callback) {
	callback(keyName);
};
cpal.storage.removeKey = function(keyName, callback) {
	callback();
};

/*
 * cpal.storage.quota
 */
cpal.storage.quota = {};
cpal.storage.quota.getUsedBytes = function(callback) {
	callback(0);
};
cpal.storage.quota.getTotalBytes = function() {
	return 0;
};


text:
$ErrorActionPreference = 'Stop'
$toolsDir   = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
# Internal packages (organizations) or software that has redistribution rights (community repo)
# - Use `Install-ChocolateyInstallPackage` instead of `Install-ChocolateyPackage`
#   and put the binaries directly into the tools folder (we call it embedding)
$fileLocation = Join-Path $toolsDir 'TeamViewer_Host_Setup.exe'
# If embedding binaries increase total nupkg size to over 1GB, use share location or download from urls

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  unzipLocation = $toolsDir
  fileType      = 'EXE'
  file         = $fileLocation

  softwareName  = 'TeamViewer*'

  checksum      = '1D0BDA2364034D8F20082DFF5E17EA10CB0CA7B3099A8DCC5F8DB90B37FE6A21'
  checksumType  = 'sha256'
  checksum64    = '1D0BDA2364034D8F20082DFF5E17EA10CB0CA7B3099A8DCC5F8DB90B37FE6A21'
  checksumType64= 'sha256'

  silentArgs    = "/S /norestart"
  validExitCodes= @(0, 3010, 1641)
}

Install-ChocolateyInstallPackage @packageArgs

redpajama_set_name: RedPajamaGithub


text:
package mods.railcraft.api.tracks;

import net.minecraft.block.Block;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.world.World;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author CovertJaguar <http://www.railcraft.info>
 */
public class TrackKitMissing extends TrackKitInstance {
    private final boolean swapOut;
    private int counter;

    public TrackKitMissing() {
        this(true);
    }

    public TrackKitMissing(boolean swapOut) {
        this.swapOut = swapOut;
    }

    @NotNull
    @Override
    public TrackKit getTrackKit() {
        return TrackRegistry.getMissingTrackKit();
    }

    @Override
    public void update() {
        swapTrack();
    }

    @Override
    public void onNeighborBlockChange(IBlockState state, @Nullable Block neighborBlock) {
        super.onNeighborBlockChange(state, neighborBlock);
        swapTrack();
    }

    private void swapTrack() {
        World world = theWorld();
        if (swapOut && world != null && !world.isRemote && counter > 4) {
            IBlockState oldState = world.getBlockState(getPos());
            BlockRailBase oldBlock = (BlockRailBase) oldState.getBlock();
            TrackType type = getTile().getTrackType();
            BlockRailBase newBlock = type.getBaseBlock();
            IBlockState newState = newBlock.getDefaultState().withProperty(newBlock.getShapeProperty(), oldState.getValue(oldBlock.getShapeProperty()));
            world.setBlockState(getPos(), newState);
        }
        counter++;
    }
}


text:
from django import template
register = template.Library()

@register.simple_tag
def url_replace(request, field, value):
    dict_ = request.GET.copy()
    dict_[field] = value
    return dict_.urlencode()


text:
@interface IntroPanelHeader : NSObject

@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) id value;

- (id)initWithDictionary:(NSDictionary *)dictionary;

@end

@implementation IntroPanelHeader

- (id)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
        _type = dictionary[@"type"];
        if ([_type isEqualToString:@"image"]) {
            _value = [[UIImageView alloc] initWithImage:[UIImage imageNamed:dictionary[@"value"]]];
        } else {
            NSString *className = dictionary[@"value"];
            CGRect frame = CGRectMake(0, 0, 180, 180);
            UIView *headerView = (UIView *)[[NSClassFromString(className) alloc] initWithFrame:frame];
            [headerView setBackgroundColor:[UIColor clearColor]];
            _value = [[UIView alloc] initWithFrame:CGRectInset(frame, 0, -20)];
            [_value addSubview:headerView];
            [headerView setCenter:CGPointMake(CGRectGetMidX(((UIView *)_value).frame), CGRectGetMidY(((UIView *)_value).frame))];
            [_value setBackgroundColor:[UIColor clearColor]];
        }
    }
    return self;
}

@end

@implementation PanelFactory

+ (NSArray *)panelsForVersion:(NSString *)version {
    NSDictionary *introPlist = [[self class] introPlistForVersion:version];
    NSArray *panelsPlist = [introPlist objectForKey:@"panels"];
    NSMutableArray *panels = [NSMutableArray arrayWithCapacity:panelsPlist.count];
    for (NSDictionary *panel in panelsPlist) {
        MYIntroductionPanel *introPanel = [[self class] panelForDictionary:panel];
        [panels addObject:introPanel];
    }
    return panels;
}

+ (MYIntroductionPanel *)panelForDictionary:(NSDictionary *)dictionary {
    NSString *title = ([((NSString *)dictionary[@"title"]) length]>0)?dictionary[@"title"]:nil;
    NSString *description = ([((NSString *)dictionary[@"description"]) length]>0)?dictionary[@"description"]:nil;
    NSString *image = ([((NSString *)dictionary[@"image"]) length]>0)?dictionary[@"image"]:nil;
    IntroPanelHeader *header = [[IntroPanelHeader alloc] initWithDictionary:dictionary[@"header"]];

    NSString *panelClassName = NSStringFromClass([MYIntroductionPanel class]);
    if (dictionary[@"class"] && ((NSString *)dictionary[@"class"]).length > 0) {
        panelClassName = dictionary[@"class"];
    }
    return [[NSClassFromString(panelClassName) alloc] initWithFrame:[[[[UIApplication sharedApplication] delegate] window] bounds] title:title description:description image:(image)?[UIImage imageNamed:image]:nil header:header.value];
}

+ (UIImage *)imageBackgroundForVersion:(NSString *)version {
    NSDictionary *introPlist = [[self class] introPlistForVersion:version];
    NSString *imageName = [introPlist objectForKey:@"backgroundImage"];
    return [UIImage imageNamed:imageName];
}

+ (NSDictionary *)introPlistForVersion:(NSString *)version {
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    NSString *plistPath;
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                              NSUserDomainMask, YES) objectAtIndex:0];
    plistPath = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", version]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        plistPath = [[NSBundle mainBundle] pathForResource:version ofType:@"plist"];
    }
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
                                          propertyListFromData:plistXML
                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];
    if (!temp) {
        NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
    }
    return temp;
}

@end


text:
// Code generated by applyconfiguration-gen. DO NOT EDIT.

package v1beta1

// PolicyRulesWithSubjectsApplyConfiguration represents an declarative configuration of the PolicyRulesWithSubjects type for use
// with apply.
type PolicyRulesWithSubjectsApplyConfiguration struct {
	Subjects         []SubjectApplyConfiguration               `json:"subjects,omitempty"`
	ResourceRules    []ResourcePolicyRuleApplyConfiguration    `json:"resourceRules,omitempty"`
	NonResourceRules []NonResourcePolicyRuleApplyConfiguration `json:"nonResourceRules,omitempty"`
}

// PolicyRulesWithSubjectsApplyConfiguration constructs an declarative configuration of the PolicyRulesWithSubjects type for use with
// apply.
func PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration {
	return &PolicyRulesWithSubjectsApplyConfiguration{}
}

// WithSubjects adds the given value to the Subjects field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Subjects field.
func (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {
	for i := range values {
		if values[i] == nil {
			panic("nil value passed to WithSubjects")
		}
		b.Subjects = append(b.Subjects, *values[i])
	}
	return b
}

// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ResourceRules field.
func (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {
	for i := range values {
		if values[i] == nil {
			panic("nil value passed to WithResourceRules")
		}
		b.ResourceRules = append(b.ResourceRules, *values[i])
	}
	return b
}

// WithNonResourceRules adds the given value to the NonResourceRules field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the NonResourceRules field.
func (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {
	for i := range values {
		if values[i] == nil {
			panic("nil value passed to WithNonResourceRules")
		}
		b.NonResourceRules = append(b.NonResourceRules, *values[i])
	}
	return b
}


text:
<?php

namespace Symfony\Component\Console\Output;

use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;

/**
 * A BufferedOutput that keeps only the last N chars.
 *
 * @author Jérémy Derussé <jeremy@derusse.com>
 */
class TrimmedBufferOutput extends Output
{
    private $maxLength;
    private $buffer = '';

    public function __construct(
        int $maxLength,
        ?int $verbosity = self::VERBOSITY_NORMAL,
        bool $decorated = false,
        OutputFormatterInterface $formatter = null
    ) {
        if ($maxLength <= 0) {
            throw new InvalidArgumentException(sprintf('"%s()" expects a strictly positive maxLength. Got %d.', __METHOD__, $maxLength));
        }

        parent::__construct($verbosity, $decorated, $formatter);
        $this->maxLength = $maxLength;
    }

    /**
     * Empties buffer and returns its content.
     *
     * @return string
     */
    public function fetch()
    {
        $content = $this->buffer;
        $this->buffer = '';

        return $content;
    }

    /**
     * {@inheritdoc}
     */
    protected function doWrite($message, $newline)
    {
        $this->buffer .= $message;

        if ($newline) {
            $this->buffer .= \PHP_EOL;
        }

        $this->buffer = substr($this->buffer, 0 - $this->maxLength);
    }
}


text:
512-586-5866    monte@montehayward.com      greenfieldinnovation.com
## Summary
Experience strategist, application developer, and user experience technologist.
Evaluates business and consumer problems and devises creative and unobtrusive objects to solve them. Passionate about mental models and brainstorming. Provides the rapid prototyping skills needed to prove a novel solution.
Embraces the extreme uncertainty of start-ups and entrepreneurial ventures. Engages technical and business stakeholders in the lean, agile interplay that makes the most of an opportunity.

Veteran developer of social media, information feed, and search products.
Specialties: Experience strategies, user experience, distributed clients, JavaScript OOP, actionable metrics, Web applications.
Comfortable with JavaScript frameworks, single-page applications, SQL, CSS, XML, shell scripting, JBoss, Apache.

## Skills
* native JavaScript
* Angular.js
* D3.js Data Visualization
* RESTful APIs / JSON
* CSS, LESS, SCSS
* Mobile Applications
* OOP
* User Experience / UX
* Innovation Development
* Start-ups & Entrepreneurship
* Web Applications
* User Interface Design
* Web Development
* Agile Methodologies
* Rapid Prototyping
* Agile Modeling
* PCI-compliant Payment Systems
* Financial data applications
* SQL / noSQL
* Java
* XML

## Experience
### Greenfield Innovation Group
    Senior Freelance Developer
    01 / 2014 - Present
Full stack developer with a UX-First approach. Providing software development focused upon early stage innovation, from inception to 1.0. Twenty years experience in Internet startups.
#### Selected Projects
* Data Metrics Visualizations for Retail Merchandisers
    -Creation of D3.js tag cloud, table, and other views. Built atop client's home-grown MVC framework.
* Mobile Web App - Insurance
    - Beta to MVP to 1.20: UI/UX development on an Ember application
* Mobile Canvassing App - Fundraising
    - Functional testing, business analysis, and UX design consultation
* Payment Systems - Fundraising
    - JavaScript / jQuery front ends with JSON API. Implemented ACH, Chicago Marathon discount code solution.

### Kimbia
    Senior Director of Development
    09 / 2013 - 01 / 2014
Drove software product development on a SaaS platform for payments, fundraising, and event management. Tailored an agile development process to meet hard external commitments and introduce novel, market-disrupting technology.

Grew and strengthened the whole-team agile culture among business stakeholders and developers. Collaborated with clients and subject matter experts in related industries to provide compelling value. Analyzed business rules and engineered engaging user experiences. Specialized in distributed clients and applications.

    Director of Development
    08 / 2010 - 08 / 2013
Lead software product development for contextual giving, viral fundraising, and event management. Initiated a whole-company approach that emphasizes shared understanding. Gathered metrics and feedback, to attune product offerings to customer needs.

Validated PCI Level 1 compliance in all aspects of operations and development.

    Senior Software Engineer
    01 / 2008 - 08 / 2010
Primary developer of distributed client products. Team developer of server and client side products and bundles.

* Portable giving form
    - Any customer can paste a single-line snippet into their Web page. Upon page load, this JavaScript client "wakes up", finds its location, and inserts a form. The form takes donations and event registrations in the context of the customer brand and page.
* Advocacy workflows
    - People sign themselves up, and then may show support by placing a form snippet on their site or blog, and emailing personalized links. Viral advocacy supports the core Kimbia principle: Personal relationships motivate people to donate and sign up. The form is viral, so, the power of giving is pushed out to the very edges of a network of advocates, enabling geometric expansion.
* Mixin components
    - Conditional questions, complex validation, custom script events, and payment plans support a highly configurable experience.
* Ancillary widgets
    - Reporting, lookup, payment plan self-service, and others round out the suite.

### Pluck Corporation– $75M exit
    Solutions Engineer
    02 / 2007 - 09 / 2007
Solutions Engineer for a premiere social media platform serving publishers Better Homes and Gardens, McGraw Hill, Conde-Naste, Hearst, and Gannet. Wrote to a JSON API and debugged server application.

### Wetpaint– $30M exit
    User Experience Engineer
    02 / 2006 - 06 / 2006
Helped Wetpaint.com get their Internet collaboration software to beta and 1.0 launches, which were lauded by Cnet News, TechCrunch, and Technology Review. Enjoyed their rapid round-trip engineering process, which scaled well. Built features and templates to empower non-technical users to create social communities on their favorite topics. Employed JSP frameworks, RESTful API for data, AJAX for a reponsive user experience, and CSS skins.

### Singingfish– $30M exit
Software Engineer
2000 - 2005
Produced UX and prototypes for presentations that led to a $30M acquisition.

2000-2004 - Designed and developed Singingfish Audio-Video Search user interfaces, enabling fully featured, first-to-market releases. See A Short History of YouTube: http://amzn.to/bNUZFN

2000 - Developed first media search site for mobile devices

Developed media RSS feed ingester software, to pulls content from MSNBC, Yahoo! Music, CBS News, Marketwatch, NPR, and Reuters.

Coauthored the Singingfish RSS namespace extension to fully describe and syndicate media content. Helped Yahoo engineers to add Singingfish RSS fields into their Yahoo Media RSS 1.0.0. This became the standard Media RSS.
Supported partner company media feed development. Automated XML Schema validation, reducing feed ramp-up and removing skill barriers.

Wrote video search SDKs for Perl, Java Servlet, JSP, and XSLT.

Devised a click recording system to capture user behavior and relevance.

Shepherded Windows Media, RealPlayer, and other early customer implementations.

### HaggleZone
    Software Engineer
    1998 - 2000
Java servlet and Web application developer on Auction (US7024376) and Haggle/Negotiation (US7756772, US6035288) applications backed by an 800,000-product inventory system.

### Free Range Media– $32M exit
Web Builder
1997 - 1998
Team lead and Web site builder for agency customers including Swedish Medical Center, Bay Watch, and Advanced Interactive Systems.

### iCat Corporation– $40M exit
Web Production Specialist
1996 - 1997
Web Development, Product Development, Web Application Development, User Interface Design, Template Construction

## Education
* University of Illinois at Chicago, Master of Associated Medical Science, Biomedical Visualization
* University of Illinois at Urbana-Champaign, BFA and minor in Life Sciences

## Patents
* Method of Disseminating Advertisements Using an Embedded Media Player Page US Patent: 8122236 · Inventors: Monte Hayward · Issued, 10 / 2001
* Methods and Systems for Collecting Data For Media Files US Patent: 7849160 · Inventors: Monte Hayward · Issued, 10 / 2001
* Method of Sizing an Embedded Media Player Page
EU Patent: EP 1350392 B1 · Inventors: Monte Hayward · Issued, 01 / 2011


text:
require 'test_helper'

class CursorUnitTest < Test::Unit::TestCase
  class Mongo::Cursor
    public :construct_query_spec
  end

  context "Cursor options" do
    setup do
      @logger     = mock()
      @logger.stubs(:debug)
      @connection = stub(:class => MongoClient, :logger => @logger,
        :slave_ok? => false, :read => :primary, :log_duration => false,
        :tag_sets => [], :acceptable_latency => 10)
      @db         = stub(:name => "testing", :slave_ok? => false,
        :connection => @connection, :read => :primary,
        :tag_sets => [], :acceptable_latency => 10)
      @collection = stub(:db => @db, :name => "items", :read => :primary,
        :tag_sets => [], :acceptable_latency => 10)
      @cursor     = Cursor.new(@collection)
    end

    should "set timeout" do
      assert @cursor.timeout
      assert @cursor.query_options_hash[:timeout]
    end

    should "set selector" do
      assert_equal({}, @cursor.selector)

      @cursor = Cursor.new(@collection, :selector => {:name => "Jones"})
      assert_equal({:name => "Jones"}, @cursor.selector)
      assert_equal({:name => "Jones"}, @cursor.query_options_hash[:selector])
    end

    should "set fields" do
      assert_nil @cursor.fields

      @cursor = Cursor.new(@collection, :fields => [:name, :date])
      assert_equal({:name => 1, :date => 1}, @cursor.fields)
      assert_equal({:name => 1, :date => 1}, @cursor.query_options_hash[:fields])
    end

    should "allow $meta projection operator" do
      assert_nil @cursor.fields

      @cursor = Cursor.new(@collection, :fields => [{ :score => { :$meta => 'textScore' } }])
      assert_equal({ :score  => { :$meta => 'textScore' } }, @cursor.fields)
      assert_equal({ :score  => { :$meta => 'textScore' } }, @cursor.query_options_hash[:fields])

      @cursor = Cursor.new(@collection, :fields => [:name, { :score => { :$meta => 'textScore' } }])
      assert_equal({ :name => 1, :score => { :$meta => 'textScore' } }, @cursor.fields)
      assert_equal({ :name => 1, :score => { :$meta => 'textScore' } }, @cursor.query_options_hash[:fields])
    end

    should "set mix fields 0 and 1" do
      assert_nil @cursor.fields

      @cursor = Cursor.new(@collection, :fields => {:name => 1, :date => 0})
      assert_equal({:name => 1, :date => 0}, @cursor.fields)
      assert_equal({:name => 1, :date => 0}, @cursor.query_options_hash[:fields])
    end

    should "set limit" do
      assert_equal 0, @cursor.limit

      @cursor = Cursor.new(@collection, :limit => 10)
      assert_equal 10, @cursor.limit
      assert_equal 10, @cursor.query_options_hash[:limit]
    end

    should "set skip" do
      assert_equal 0, @cursor.skip

      @cursor = Cursor.new(@collection, :skip => 5)
      assert_equal 5, @cursor.skip
      assert_equal 5, @cursor.query_options_hash[:skip]
    end

    should "set sort order" do
      assert_nil @cursor.order

      @cursor = Cursor.new(@collection, :order => "last_name")
      assert_equal "last_name", @cursor.order
      assert_equal "last_name", @cursor.query_options_hash[:order]
    end

    should "set hint" do
      assert_nil @cursor.hint

      @cursor = Cursor.new(@collection, :hint => "name")
      assert_equal "name", @cursor.hint
      assert_equal "name", @cursor.query_options_hash[:hint]
    end

    should "set comment" do
      assert_nil @cursor.comment

      @cursor = Cursor.new(@collection, :comment => "comment")
      assert_equal "comment", @cursor.comment
      assert_equal "comment", @cursor.query_options_hash[:comment]
    end

    should "cache full collection name" do
      assert_equal "testing.items", @cursor.full_collection_name
    end

    should "raise error when batch_size is 1" do
      e = assert_raise ArgumentError do
        @cursor.batch_size(1)
        end
        assert_equal "Invalid value for batch_size 1; must be 0 or > 1.", e.message
    end

    should "use the limit for batch size when it's smaller than the specified batch_size" do
      @cursor.limit(99)
      @cursor.batch_size(100)
      assert_equal 99, @cursor.batch_size
      end

    should "use the specified batch_size" do
      @cursor.batch_size(100)
      assert_equal 100, @cursor.batch_size
    end

    context 'when an alternate namespace is specified' do

      should 'use the alternate namespace' do
        cursor = Cursor.new(@collection, :ns => 'other_db.other_collection')
        assert_equal('other_db.other_collection', cursor.full_collection_name)
      end
    end

    context "connected to mongos" do
      setup do
        @connection.stubs(:mongos?).returns(true)
        @tag_sets = [{:dc => "ny"}]
      end

      should "set $readPreference" do
        # secondary
        cursor = Cursor.new(@collection, { :read => :secondary })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'secondary', spec['$readPreference'][:mode]
        assert !spec['$readPreference'].has_key?(:tags)

        # secondary preferred with tags
        cursor = Cursor.new(@collection, { :read => :secondary_preferred, :tag_sets => @tag_sets })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'secondaryPreferred', spec['$readPreference'][:mode]
        assert_equal @tag_sets, spec['$readPreference'][:tags]

        # primary preferred
        cursor = Cursor.new(@collection, { :read => :primary_preferred })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'primaryPreferred', spec['$readPreference'][:mode]
        assert !spec['$readPreference'].has_key?(:tags)

        # primary preferred with tags
        cursor = Cursor.new(@collection, { :read => :primary_preferred, :tag_sets => @tag_sets })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'primaryPreferred', spec['$readPreference'][:mode]
        assert_equal @tag_sets, spec['$readPreference'][:tags]

        # nearest
        cursor = Cursor.new(@collection, { :read => :nearest })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'nearest', spec['$readPreference'][:mode]
        assert !spec['$readPreference'].has_key?(:tags)

        # nearest with tags
        cursor = Cursor.new(@collection, { :read => :nearest, :tag_sets => @tag_sets })

        spec = cursor.construct_query_spec
        assert spec.has_key?('$readPreference')
        assert_equal 'nearest', spec['$readPreference'][:mode]
        assert_equal @tag_sets, spec['$readPreference'][:tags]
      end

      should "not set $readPreference" do
        # for primary
        cursor = Cursor.new(@collection, { :read => :primary, :tag_sets => @tag_sets })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        # for secondary_preferred with no tags
        cursor = Cursor.new(@collection, { :read => :secondary_preferred })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :secondary_preferred, :tag_sets => [] })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :secondary_preferred, :tag_sets => nil })
        assert !cursor.construct_query_spec.has_key?('$readPreference')
      end
    end

    context "not connected to mongos" do
      setup do
        @connection.stubs(:mongos?).returns(false)
      end

      should "not set $readPreference" do
        cursor = Cursor.new(@collection, { :read => :primary })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :primary_preferred })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :secondary })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :secondary_preferred })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :nearest })
        assert !cursor.construct_query_spec.has_key?('$readPreference')

        cursor = Cursor.new(@collection, { :read => :secondary , :tag_sets => @tag_sets})
        assert !cursor.construct_query_spec.has_key?('$readPreference')
      end
    end
  end

  context "Query fields" do
    setup do
      @logger     = mock()
      @logger.stubs(:debug)
      @connection = stub(:class => MongoClient, :logger => @logger, :slave_ok? => false,
        :log_duration => false, :tag_sets =>{}, :acceptable_latency => 10)
      @db = stub(:slave_ok? => true, :name => "testing", :connection => @connection,
        :tag_sets => {}, :acceptable_latency => 10)
      @collection = stub(:db => @db, :name => "items", :read => :primary,
        :tag_sets => {}, :acceptable_latency => 10)
    end

    should "when an array should return a hash with each key" do
      @cursor = Cursor.new(@collection, :fields => [:name, :age])
      result  = @cursor.fields
      assert_equal result.keys.sort{|a,b| a.to_s <=> b.to_s}, [:age, :name].sort{|a,b| a.to_s <=> b.to_s}
      assert result.values.all? {|v| v == 1}
    end

    should "when a string, return a hash with just the key" do
      @cursor = Cursor.new(@collection, :fields => "name")
      result  = @cursor.fields
      assert_equal result.keys.sort, ["name"]
      assert result.values.all? {|v| v == 1}
    end

    should "return nil when neither hash nor string nor symbol" do
      @cursor = Cursor.new(@collection, :fields => 1234567)
      assert_nil @cursor.fields
    end
  end

  context "counts" do
    setup do
      @logger     = mock()
      @logger.stubs(:debug)
      @connection = stub(:class => Connection, :logger => @logger,
        :slave_ok? => false, :read => :primary, :log_duration => false,
        :tag_sets => {}, :acceptable_latency => 10)
      @db         = stub(:name => "testing", :slave_ok? => false,
        :connection => @connection, :read => :primary,
        :tag_sets => {}, :acceptable_latency => 10)
      @collection = stub(:db => @db, :name => "items", :read => :primary,
        :tag_sets => {}, :acceptable_latency => 10)
      @cursor     = Cursor.new(@collection)
    end

    should "pass the comment parameter" do
      query = {:field => 7}
      @db.expects(:command).with({ 'count' => "items",
                                   'query' => query,
                                   'fields' => nil},
                                 { :read => :primary,
                                   :comment => "my comment"}).
        returns({'ok' => 1, 'n' => 1})
      assert_equal(1, Cursor.new(@collection, :selector => query, :comment => 'my comment').count())
    end
  end
end


text:
package org.apache.hadoop.fs.cosn;

import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSExceptionMessages;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileSystem;

/**
 * The input stream for the COS blob store.
 * Optimized sequential read flow based on a forward read-ahead queue
 */
public class CosNInputStream extends FSInputStream {
  private static final Logger LOG =
      LoggerFactory.getLogger(CosNInputStream.class);

  /**
   * This class is used by {@link CosNInputStream}
   * and {@link CosNFileReadTask} to buffer data that read from COS blob store.
   */
  public static class ReadBuffer {
    public static final int INIT = 1;
    public static final int SUCCESS = 0;
    public static final int ERROR = -1;

    private final ReentrantLock lock = new ReentrantLock();
    private Condition readyCondition = lock.newCondition();

    private byte[] buffer;
    private int status;
    private long start;
    private long end;

    public ReadBuffer(long start, long end) {
      this.start = start;
      this.end = end;
      this.buffer = new byte[(int) (this.end - this.start) + 1];
      this.status = INIT;
    }

    public void lock() {
      this.lock.lock();
    }

    public void unLock() {
      this.lock.unlock();
    }

    public void await(int waitStatus) throws InterruptedException {
      while (this.status == waitStatus) {
        readyCondition.await();
      }
    }

    public void signalAll() {
      readyCondition.signalAll();
    }

    public byte[] getBuffer() {
      return this.buffer;
    }

    public int getStatus() {
      return this.status;
    }

    public void setStatus(int status) {
      this.status = status;
    }

    public long getStart() {
      return start;
    }

    public long getEnd() {
      return end;
    }
  }

  private FileSystem.Statistics statistics;
  private final Configuration conf;
  private final NativeFileSystemStore store;
  private final String key;
  private long position = 0;
  private long nextPos = 0;
  private long fileSize;
  private long partRemaining;
  private final long preReadPartSize;
  private final int maxReadPartNumber;
  private byte[] buffer;
  private boolean closed;

  private final ExecutorService readAheadExecutorService;
  private final Queue<ReadBuffer> readBufferQueue;

  public CosNInputStream(Configuration conf, NativeFileSystemStore store,
      FileSystem.Statistics statistics, String key, long fileSize,
      ExecutorService readAheadExecutorService) {
    super();
    this.conf = conf;
    this.store = store;
    this.statistics = statistics;
    this.key = key;
    this.fileSize = fileSize;
    this.preReadPartSize = conf.getLong(
        CosNConfigKeys.READ_AHEAD_BLOCK_SIZE_KEY,
        CosNConfigKeys.DEFAULT_READ_AHEAD_BLOCK_SIZE);
    this.maxReadPartNumber = conf.getInt(
        CosNConfigKeys.READ_AHEAD_QUEUE_SIZE,
        CosNConfigKeys.DEFAULT_READ_AHEAD_QUEUE_SIZE);

    this.readAheadExecutorService = readAheadExecutorService;
    this.readBufferQueue = new ArrayDeque<>(this.maxReadPartNumber);
    this.closed = false;
  }

  private synchronized void reopen(long pos) throws IOException {
    long partSize;

    if (pos < 0) {
      throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK);
    } else if (pos > this.fileSize) {
      throw new EOFException(FSExceptionMessages.CANNOT_SEEK_PAST_EOF);
    } else {
      if (pos + this.preReadPartSize > this.fileSize) {
        partSize = this.fileSize - pos;
      } else {
        partSize = this.preReadPartSize;
      }
    }

    this.buffer = null;

    boolean isRandomIO = true;
    if (pos == this.nextPos) {
      isRandomIO = false;
    } else {
      while (this.readBufferQueue.size() != 0) {
        if (this.readBufferQueue.element().getStart() != pos) {
          this.readBufferQueue.poll();
        } else {
          break;
        }
      }
    }

    this.nextPos = pos + partSize;

    int currentBufferQueueSize = this.readBufferQueue.size();
    long lastByteStart;
    if (currentBufferQueueSize == 0) {
      lastByteStart = pos - partSize;
    } else {
      ReadBuffer[] readBuffers =
          this.readBufferQueue.toArray(
              new ReadBuffer[currentBufferQueueSize]);
      lastByteStart = readBuffers[currentBufferQueueSize - 1].getStart();
    }

    int maxLen = this.maxReadPartNumber - currentBufferQueueSize;
    for (int i = 0; i < maxLen && i < (currentBufferQueueSize + 1) * 2; i++) {
      if (lastByteStart + partSize * (i + 1) > this.fileSize) {
        break;
      }

      long byteStart = lastByteStart + partSize * (i + 1);
      long byteEnd = byteStart + partSize - 1;
      if (byteEnd >= this.fileSize) {
        byteEnd = this.fileSize - 1;
      }

      ReadBuffer readBuffer = new ReadBuffer(byteStart, byteEnd);
      if (readBuffer.getBuffer().length == 0) {
        readBuffer.setStatus(ReadBuffer.SUCCESS);
      } else {
        this.readAheadExecutorService.execute(
            new CosNFileReadTask(
                this.conf, this.key, this.store, readBuffer));
      }

      this.readBufferQueue.add(readBuffer);
      if (isRandomIO) {
        break;
      }
    }

    ReadBuffer readBuffer = this.readBufferQueue.poll();
    if (null != readBuffer) {
      readBuffer.lock();
      try {
        readBuffer.await(ReadBuffer.INIT);
        if (readBuffer.getStatus() == ReadBuffer.ERROR) {
          this.buffer = null;
        } else {
          this.buffer = readBuffer.getBuffer();
        }
      } catch (InterruptedException e) {
        LOG.warn("An interrupted exception occurred "
            + "when waiting a read buffer.");
      } finally {
        readBuffer.unLock();
      }
    }

    if (null == this.buffer) {
      throw new IOException("Null IO stream");
    }

    this.position = pos;
    this.partRemaining = partSize;
  }

  @Override
  public void seek(long pos) throws IOException {
    if (pos < 0) {
      throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK);
    }
    if (pos > this.fileSize) {
      throw new EOFException(FSExceptionMessages.CANNOT_SEEK_PAST_EOF);
    }

    if (this.position == pos) {
      return;
    }
    if (pos > position && pos < this.position + partRemaining) {
      long len = pos - this.position;
      this.position = pos;
      this.partRemaining -= len;
    } else {
      this.reopen(pos);
    }
  }

  @Override
  public long getPos() {
    return this.position;
  }

  @Override
  public boolean seekToNewSource(long targetPos) {
    // Currently does not support to seek the offset of a new source
    return false;
  }

  @Override
  public int read() throws IOException {
    if (this.closed) {
      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED);
    }

    if (this.partRemaining <= 0 && this.position < this.fileSize) {
      this.reopen(this.position);
    }

    int byteRead = -1;
    if (this.partRemaining != 0) {
      byteRead = this.buffer[
          (int) (this.buffer.length - this.partRemaining)] & 0xff;
    }
    if (byteRead >= 0) {
      this.position++;
      this.partRemaining--;
      if (null != this.statistics) {
        this.statistics.incrementBytesRead(byteRead);
      }
    }

    return byteRead;
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    if (this.closed) {
      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED);
    }

    if (len == 0) {
      return 0;
    }

    if (off < 0 || len < 0 || len > b.length) {
      throw new IndexOutOfBoundsException();
    }

    int bytesRead = 0;
    while (position < fileSize && bytesRead < len) {
      if (partRemaining <= 0) {
        reopen(position);
      }

      int bytes = 0;
      for (int i = this.buffer.length - (int) partRemaining;
           i < this.buffer.length; i++) {
        b[off + bytesRead] = this.buffer[i];
        bytes++;
        bytesRead++;
        if (off + bytesRead >= len) {
          break;
        }
      }

      if (bytes > 0) {
        this.position += bytes;
        this.partRemaining -= bytes;
      } else if (this.partRemaining != 0) {
        throw new IOException(
            "Failed to read from stream. Remaining: " + this.partRemaining);
      }
    }
    if (null != this.statistics && bytesRead > 0) {
      this.statistics.incrementBytesRead(bytesRead);
    }

    return bytesRead == 0 ? -1 : bytesRead;
  }

  @Override
  public int available() throws IOException {
    if (this.closed) {
      throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED);
    }

    long remaining = this.fileSize - this.position;
    if (remaining > Integer.MAX_VALUE) {
      return Integer.MAX_VALUE;
    }
    return (int)remaining;
  }

  @Override
  public void close() {
    if (this.closed) {
      return;
    }
    this.closed = true;
    this.buffer = null;
  }
}


text:
<!DOCTYPE html>
 <title>Fortunes</title>

id	message

{% for item in items %}

{{ item.id }}	{{ item.message }}

{% endfor %}


text:
module DB.Source (connect, defineTable) where

import Database.HDBC.MySQL                  ( MySQLConnectInfo(..), defaultMySQLConnectInfo
                                            , Connection, connectMySQL
                                            )
import Database.HDBC.Query.TH               (defineTableFromDB)
import Database.HDBC.Schema.Driver          (typeMap)
import Database.HDBC.Schema.MySQL           (driverMySQL)
import Language.Haskell.TH                  (TypeQ, Q, Dec)
import Language.Haskell.TH.Name.CamelCase   (ConName)

-- {-# ANN module "HLint: ignore Eta reduce" #-}

config :: MySQLConnectInfo
config = defaultMySQLConnectInfo
    { mysqlUser     = "hrr-tester"
    , mysqlPassword = ""
    , mysqlDatabase = "TEST"
    , mysqlHost     = "127.0.0.1"
    }

connect :: IO Connection
connect = connectMySQL config

defineTable :: [(String, TypeQ)] -> String -> String -> [ConName] -> Q [Dec]
defineTable tmap =
    defineTableFromDB connect (driverMySQL { typeMap = tmap })


text:
package org.apache.tools.ant.types.resources.comparators;

import org.apache.tools.ant.types.Resource;

/**
 * Compares Resources by is-directory status.  As a container
 * of files, a directory is deemed "greater" than a file.
 * @since Ant 1.7
 */
public class Type extends ResourceComparator {

    /**
     * Compare two Resources.
     * @param foo the first Resource.
     * @param bar the second Resource.
     * @return a negative integer, zero, or a positive integer as the first
     *         argument is less than, equal to, or greater than the second.
     */
    protected int resourceCompare(Resource foo, Resource bar) {
        boolean f = foo.isDirectory();
        if (f == bar.isDirectory()) {
            return 0;
        }
        return f ? 1 : -1;
    }

}


text:
import classNames from 'classnames';
import { FunctionComponent } from 'react';
import {
  Col,
  ControlLabel,
  FormGroup,
  InputGroup,
  OverlayTrigger,
  Tooltip as BootstrapTooltip,
} from 'react-bootstrap';
import { Field, WrappedFieldProps } from 'redux-form';

import { ENV } from '@waldur/configs/default';
import { FieldError } from '@waldur/form';
import { InputField } from '@waldur/form/InputField';
import { translate } from '@waldur/i18n';

// These limitations are imposed by underlying operating system
const MAXIMUM_USERNAME_LENGTH = 32;
const USERNAME_PATTERN = new RegExp(
  '^[a-zA-Z0-9_.][a-zA-Z0-9_.-]*[a-zA-Z0-9_.$-]?$',
);

const validateUsername = (username: string) => {
  if (!username) {
    return translate('Username is required.');
  }
  if (!username.match(USERNAME_PATTERN)) {
    return translate(
      'Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_) and periods (.).',
    );
  }
  if (username.length < 3) {
    return translate('Minimum username length is 3 characters.');
  }
  if (
    username.length >
    MAXIMUM_USERNAME_LENGTH - ENV.plugins.WALDUR_FREEIPA.USERNAME_PREFIX.length
  ) {
    return translate(
      'Maximum username length with mandatory username prefix is 32 characters.',
    );
  }
};

const UsernameField: FunctionComponent<WrappedFieldProps> = (props) => (
  <>
    <div
      className={classNames('m-b-sm', {
        'input-group': ENV.plugins.WALDUR_FREEIPA.USERNAME_PREFIX !== '',
      })}
    >
      {ENV.plugins.WALDUR_FREEIPA.USERNAME_PREFIX && (
        <OverlayTrigger
          placement="top"
          overlay={
            <BootstrapTooltip id="freeipa-username-prefix">
              {translate('Username prefix')}
            </BootstrapTooltip>
          }
        >
          <InputGroup.Addon>
            {ENV.plugins.WALDUR_FREEIPA.USERNAME_PREFIX}
          </InputGroup.Addon>
        </OverlayTrigger>
      )}
      <InputField {...props} />
    </div>
    {props.meta.touched && <FieldError error={props.meta.error} />}
  </>
);

export const UsernameGroup: FunctionComponent = () => (
  <FormGroup>
    <Col sm={3} componentClass={ControlLabel}>
      {translate('Username')}
    </Col>
    <Col sm={6}>
      <Field
        name="username"
        validate={validateUsername}
        component={UsernameField}
      />
      <p className="form-text text-muted">
        {translate(
          'Please select a username that you will use for login into the Linux systems.',
        )}
      </p>
    </Col>
  </FormGroup>
);


text:
<?php

class example01 extends output_html {

	function process() {
		$obj = new ExampleModel;

		$msg = elsyifa::instance()->message_receive();

        if (empty($msg[0])) {
            $conf_edit = elsyifa::instance()->get_config();
        } else {
            $conf_edit['app_name'] = $msg[0]['app_name'];
            $conf_edit['app_version'] = $msg[0]['app_version'];
        }

        $return['msg'] = $msg;
        $return['conf_edit'] = $conf_edit;
		$return['datalist'] = $obj->get_config();

		return $return;
	}

	function parse_template($data = NULL) {
		$this->tmpl->assign('URL_ACTION', './index.php?m=example&f=update');
        $this->tmpl->assign('APP_NAME', $data['conf_edit']['app_name']);
        $this->tmpl->assign('APP_VERSION', $data['conf_edit']['app_version']);

		$this->tmpl->assign('MSG_TEXT', $data['msg'][1]);
		$this->tmpl->assign('MSG_CSS', $data['msg'][2]);

		$this->tmpl->assign('datalist', $data['datalist']);
	}

}
?>


text:
package org.apache.geode.internal.memcached;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.geode.internal.memcached.commands.AbstractCommand;
import org.apache.geode.internal.memcached.commands.ClientError;
import org.apache.geode.memcached.GemFireMemcachedServer.Protocol;

/**
 * Reads the first line from the request and interprets the {@link Command} from the memcached
 * client
 *
 *
 */
public class RequestReader {

  private static final Charset charsetASCII = Charset.forName("US-ASCII");

  private static final ThreadLocal<CharsetDecoder> asciiDecoder =
      new ThreadLocal<CharsetDecoder>() {
        @Override
        protected CharsetDecoder initialValue() {
          return charsetASCII.newDecoder();
        }
      };

  private ByteBuffer buffer;

  private ByteBuffer response;

  private static final int RESPONSE_HEADER_LENGTH = 24;

  private static final byte RESPONSE_MAGIC = (byte) 0x81;

  private static final int HEADER_LENGTH = 24;

  private static final byte REQUEST_MAGIC = (byte) 0x80;

  private static final int POSITION_OPCODE = 1;

  private static final int POSITION_OPAQUE = 12;

  private Socket socket;

  private final Protocol protocol;

  private CharBuffer commandBuffer = CharBuffer.allocate(11); // no command exceeds 9 chars

  public RequestReader(Socket socket, Protocol protocol) {
    buffer = ByteBuffer.allocate(getBufferSize(socket.getChannel()));
    // set position to limit so that first read attempt
    // returns hasRemaining() false
    buffer.position(buffer.limit());
    this.socket = socket;
    this.protocol = protocol;
  }

  public Command readCommand() throws IOException {
    if (protocol == Protocol.ASCII) {
      return readAsciiCommand();
    }
    return readBinaryCommand();
  }

  private Command readBinaryCommand() throws IOException {
    SocketChannel channel = this.socket.getChannel();
    if (channel == null || !channel.isOpen()) {
      throw new IllegalStateException("cannot read from channel");
    }
    Command cmd = null;
    boolean done = false;
    boolean read = false;
    while (!done) {
      if (!buffer.hasRemaining()) {
        buffer.clear();
        read = true;
      } else if (!read) {
        // compact is meant for partial writes, but we want to use
        // it partial reads, so the new limit should be the position
        // after the compact operation and we want to start reading
        // from the beginning
        buffer.compact();
        buffer.limit(buffer.position());
        buffer.position(0);
      }
      if (read) {
        int bytesRead = channel.read(buffer);
        if (bytesRead == -1) {
          throw new IOException("EOF");
        }
        buffer.flip();
      }
      // read again if we did not read enough bytes
      if (buffer.limit() < HEADER_LENGTH) {
        buffer.compact();
        read = true;
        continue;
      }
      int requestLength = buffer.remaining();
      byte magic = buffer.get();
      if (magic != REQUEST_MAGIC) {
        throw new IllegalStateException("Not a valid request, magic byte incorrect");
      }
      byte opCode = buffer.get();
      if (ConnectionHandler.getLogger().finerEnabled()) {
        String str = Command.buffertoString(buffer);
        ConnectionHandler.getLogger().finer("Request:" + buffer + str.toString());
      }
      int bodyLength = buffer.getInt(AbstractCommand.TOTAL_BODY_LENGTH_INDEX);
      if ((HEADER_LENGTH + bodyLength) > requestLength) {
        // set the position back to the start of the request
        buffer.position(buffer.position() - 2 /* since we read two bytes */);
        buffer.compact();
        // ensure that the buffer is big enough
        if (buffer.capacity() < (HEADER_LENGTH + bodyLength)) {
          // allocate bigger buffer and copy the bytes to the bigger buffer
          ByteBuffer oldBuffer = buffer;
          oldBuffer.position(0);
          buffer = ByteBuffer.allocate(HEADER_LENGTH + bodyLength);
          buffer.put(oldBuffer);
        }
        read = true;
        continue;
      }
      cmd = Command.getCommandFromOpCode(opCode);
      done = true;
    }
    if (ConnectionHandler.getLogger().fineEnabled()) {
      ConnectionHandler.getLogger().fine("read command " + cmd);
    }
    return cmd;
  }

  private Command readAsciiCommand() throws IOException {
    SocketChannel channel = this.socket.getChannel();
    if (channel == null || !channel.isOpen()) {
      throw new IllegalStateException("cannot read from channel");
    }
    buffer.clear();
    int bytesRead = channel.read(buffer);
    if (bytesRead == -1) {
      throw new IOException("EOF");
    }
    buffer.flip();
    return Command.valueOf(readCommand(buffer));
  }

  private String readCommand(ByteBuffer buffer) throws CharacterCodingException {
    commandBuffer.clear();
    asciiDecoder.get().decode(buffer, commandBuffer, false);
    commandBuffer.flip();
    return trimCommand(commandBuffer.toString()).toUpperCase();
  }

  private String trimCommand(String str) {
    int indexOfSpace = str.indexOf(' ');
    String retVal = str;
    if (indexOfSpace != -1) {
      retVal = str.substring(0, indexOfSpace);
    }
    int indexOfR = retVal.indexOf("\r");
    if (indexOfR != -1) {
      retVal = retVal.substring(0, indexOfR);
    }
    if (retVal.equals("")) {
      if (ConnectionHandler.getLogger().infoEnabled()) {
        // TODO i18n
        ConnectionHandler.getLogger().info("Unknown command. ensure client protocol is ASCII");
      }
      throw new IllegalArgumentException("Unknown command. ensure client protocol is ASCII");
    }
    return retVal;
  }

  private int getBufferSize(SocketChannel channel) {
    int size = 1024;
    try {
      size = channel.socket().getReceiveBufferSize();
    } catch (SocketException e) {
      // use default size
    }
    return size;
  }

  public ByteBuffer getRequest() {
    this.buffer.rewind();
    return this.buffer;
  }

  public ByteBuffer getResponse() {
    return getResponse(RESPONSE_HEADER_LENGTH);
  }

  /**
   * Returns an initialized byteBuffer for sending the reply
   *
   * @param size size of ByteBuffer
   * @return the initialized response buffer
   */
  public ByteBuffer getResponse(int size) {
    if (this.response == null || this.response.capacity() < size) {
      this.response = ByteBuffer.allocate(size);
    }
    clear(this.response);
    this.response.put(RESPONSE_MAGIC);
    this.response.rewind();
    this.response.limit(size);
    return this.response;
  }

  private void clear(ByteBuffer response) {
    response.position(0);
    response.limit(response.capacity());
    response.put(getCleanByteArray());
    while (response.remaining() > getCleanByteArray().length) {
      response.put(getCleanByteArray());
    }
    while (response.remaining() > 0) {
      response.put((byte) 0);
    }
    response.clear();
  }

  private static byte[] cleanByteArray;

  private byte[] getCleanByteArray() {
    if (cleanByteArray != null) {
      return cleanByteArray;
    }
    cleanByteArray = new byte[RESPONSE_HEADER_LENGTH];
    for (int i = 0; i < cleanByteArray.length; i++) {
      cleanByteArray[i] = 0;
    }
    return cleanByteArray;
  }

  public void sendReply(ByteBuffer reply) throws IOException {
    // for binary set the response opCode
    if (this.protocol == Protocol.BINARY) {
      reply.rewind();
      reply.put(POSITION_OPCODE, buffer.get(POSITION_OPCODE));
      reply.putInt(POSITION_OPAQUE, buffer.getInt(POSITION_OPAQUE));
      if (ConnectionHandler.getLogger().finerEnabled()) {
        ConnectionHandler.getLogger()
            .finer("sending reply:" + reply + " " + Command.buffertoString(reply));
      }
    }
    SocketChannel channel = this.socket.getChannel();
    if (channel == null || !channel.isOpen()) {
      throw new IllegalStateException("cannot write to channel");
    }
    channel.write(reply);
  }

  public void sendException(Exception e) {
    SocketChannel channel = this.socket.getChannel();
    if (channel == null || !channel.isOpen()) {
      throw new IllegalStateException("cannot write to channel");
    }
    try {
      if (e instanceof ClientError) {
        channel.write(charsetASCII.encode(Reply.CLIENT_ERROR.toString()));
      } else {
        channel.write(charsetASCII.encode(Reply.ERROR.toString()));
      }
    } catch (IOException ex) {
    }
  }
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.ServiceModel.Security
{
  public partial class TripleDesSecurityAlgorithmSuite : SecurityAlgorithmSuite
  {
    #region Methods and constructors
    public override bool IsAsymmetricKeyLengthSupported(int length)
    {
      return default(bool);
    }

    public override bool IsSymmetricKeyLengthSupported(int length)
    {
      return default(bool);
    }

    public TripleDesSecurityAlgorithmSuite()
    {
    }
    #endregion

    #region Properties and indexers
    public override string DefaultAsymmetricKeyWrapAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override string DefaultAsymmetricSignatureAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override string DefaultCanonicalizationAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override string DefaultDigestAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override string DefaultEncryptionAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override int DefaultEncryptionKeyDerivationLength
    {
      get
      {
        return default(int);
      }
    }

    public override int DefaultSignatureKeyDerivationLength
    {
      get
      {
        return default(int);
      }
    }

    public override int DefaultSymmetricKeyLength
    {
      get
      {
        return default(int);
      }
    }

    public override string DefaultSymmetricKeyWrapAlgorithm
    {
      get
      {
        return default(string);
      }
    }

    public override string DefaultSymmetricSignatureAlgorithm
    {
      get
      {
        return default(string);
      }
    }
    #endregion
  }
}


text:
var webpackConfig = require('./webpack.test.js');

module.exports = function (config) {
  var _config = {
    basePath: '',

    frameworks: ['jasmine'],

    files: [
      {pattern: './karma-test-shim.js', watched: true}
    ],

    preprocessors: {
      './karma-test-shim.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      stats: 'errors-only'
    },

    webpackServer: {
      noInfo: true
    },

    browserConsoleLogOptions: {
      level: 'log',
      format: '%b %T: %m',
      terminal: true
    },

    reporters: ['kjhtml', 'dots'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: true
  };

  config.set(_config);
};


text:
// vi:si:et:sw=2:sts=2:ts=2
//
// tested in test/spec/services/things.js
//

/**
 * @ngdoc     service
 * @name      mushin.service:things
 * @requires  hoodie
 * @requires  mushin.service:Thing
 *
 * @description
The things service tracks all things, loads them from
 *                 the data store, and updates the rootScope tracking
 *                 variables.

 */
angular.module('mushin').factory('things',
  function($rootScope, $filter, hoodie, $q, Thing, $state) {

    var debug = new window.$debug('mushin:services/thing');

    /* hoodie is hoodie's hoodie.js, not the angularized version
     * FIXME: not sure how angular finds this at all */
    /* mock out hoodie using data on the state in stateProvider */
    if ($state.current.data && $state.current.data.mock &&
        $state.current.data.mock.indexOf("hoodie") > -1) {
      debug('mocking out hoodie');
      hoodie = {
        /* FIXME: load mocked data from serialized file served over http? */
        /* FIXME: create a mocked hoodie class in a separate js file and
         *        load it ? */
        store: {
          findAll: function() {
            return Promise.resolve([
              {
                title: 'my title',
                type: Thing.ACTIVE,
                id: 'a1',
                contexts: [ 'computer', ],
                projects: [ 'mushin', ],
                importance: 3,
                urgency: 5,
              },
              {
                title: 'my second thing',
                type: Thing.ACTIVE,
                id: 'a2',
                contexts: [ 'computer', ],
                projects: [ 'personal', ],
                importance: 3,
                urgency: 5,
              },
            ]);
          },
          on: function(evt, func) {
            debug('hoodie.store.on: ' + evt + func);
          },
          add: function(type, data) {
            debug('hoodie.store.add: ' + type + data);
            /* FIXME: don't use alert, since this is a mock service
             * should be changed to an event bubbling up that can be caught */
            debug('Faked adding thing with title ' + data.title);
          }
        }
      };
    }

    /* inject tracking variables in the root scope */
    $rootScope.contexts = {}; // context name -> obj with things, active, ...
    $rootScope.projects = {};
    $rootScope.importance = {}; // importance level -> obj with things, active, ...
    $rootScope.urgency = {};
    $rootScope.things = [];

    var service = {}; // the service object to which we will attach functions and
                      // return

    /* public API */

    // FIXME: this method is only used in this file?
    /**
     * @ngdoc method
     * @methodOf mushin.service:things
     * @name  mushin.service:things#loadedThingsData
     * @param {enum}           type       accepted type of things to be loaded;
     *                                    e.g. Thing.ACTIVE
     * @param {list of Object} thingsData list of data objects for things
     *
     * @description
     *
     * Reset our tracking state with the given loaded things.
     * Only loads things of the specified type.
     * Called after getting all data objects from the data store.
     */
    service.loadedThingsData = function(type, thingsData) {

      var thingsDataOfType = [];

      // reset when we recount
      resetHash($rootScope.projects);
      resetHash($rootScope.contexts);
      resetHash($rootScope.importance);
      resetHash($rootScope.urgency);

      for (var i = 0; i < thingsData.length; i++) {
        // FIXME: not sure if it's better to deal with thingData here or
        //        full thing objects
        var thing = thingsData[i];
        if ((thing.state === type) ||
            (type == Thing.ACTIVE && !thing.state)) {
          thingsDataOfType.push(thing);
          trackHash($rootScope.projects, 'project', thing);
          trackHash($rootScope.contexts, 'context', thing);
          trackNumberHash($rootScope.importance, 'importance', thing);
          trackNumberHash($rootScope.urgency, 'urgency', thing);
        }
      }
      debug('loaded ' + Object.keys($rootScope.projects).length +
          ' projects');
      debug('loaded ' + Object.keys($rootScope.contexts).length +
          ' contexts');
      debug('loaded ' + Object.keys($rootScope.importance).length +
          ' importance levels');
      debug('loaded ' + Object.keys($rootScope.urgency).length +
          ' urgency levels');
      return thingsDataOfType;
    };

    service.get = function(id) {
      return $q.when(hoodie.store.find('thing', id));
    };

    /* called by ThingsController to load all things */
    service.getAll = function(type) {
      var start = new Date();

      var promise = $q.when(hoodie.store.findAll('thing'));
      if (!Thing.isType(type)) {
        return promise;
      }

      var deferred = $q.defer();

      promise.then(function(thingsData) {
        debug('loaded ' + thingsData.length + ' hoodie things in ' +
            (new Date().getTime() - start.getTime()) + ' ms');

        var thingsDataOfType = service.loadedThingsData(type, thingsData);

        // now that we've loaded, make sure we start broadcasting
        // changes
        hoodie.store.on('change:thing', function(name, thing) {
          debug('change:thing handler, name ' + name + ', thing ' + thing);
          $rootScope.$broadcast('thingChange', {
            type: name,
            thing: thing
          })
        });
        debug('loaded ' + thingsDataOfType.length +
            ' hoodie things of type ' + type + ' in ' +
            (new Date().getTime() - start.getTime()) + ' ms');

        $rootScope.things = $filter('filter')(thingsDataOfType,
          function(thing) {
            // FIXME: I'm filtering on complete/end in a filter func
            if (!thing.done && !thing.deleted) { return true; }
          }
        );

        deferred.resolve(thingsDataOfType);
      });
      return deferred.promise;
    };

    /**
     * @ngdoc method
     * @methodOf mushin.service:things
     * @name  mushin.service:things#add
     * @param {string} title       title
     * @param {string} description a longer description
     * @param {Object} data        parsed thing data
     *
     * @description
     *
     * Create a new thing with the given title, description, and thing data,
     * and store it in the data store.
     */
    service.add = function(title, description, data) {
      var newThing = new Thing(title, description, data);
      return $q.when(hoodie.store.add('thing', newThing.data));
    };

    service.extend = function(scope) {
      /* service adds proxies for some functions on the Thing class,
       * instantiating them on the fly so they can be changed.
       */
      var methods = ['setDone', 'setDeleted', 'setComplete']

      angular.forEach(methods, function(method) {
        scope[method] = function(data) {
          var thing = new Thing(data)
          return thing[method]()
        }
      });

      /* generate all conversion functions, named convertTo... */
      /* service should match the Thing types in services/thing.js */
      var conversions = ['active', 'archive'];

      angular.forEach(conversions, function(conversion) {
        var methodName = 'convertTo' + conversion[0].toUpperCase() +
            conversion.substring(1);
        var state = Thing[conversion.toUpperCase()];

        scope[methodName] = function(data) {
          debug(methodName + '(): ' + JSON.stringify(data));
          var thing = new Thing(data);
          return thing.convertTo(state);
        };

      });
    };

    /* private API */

    // update the contexts/projects hash based on the thing
    var trackHash = function(hash, type, thing) {
      var plural = type + 's'

      if (thing[plural]) {
        for (var j = 0; j < thing[plural].length; ++j) {
          // for now, ignore completed things
          if (thing.complete == 100) { return; }

          var name = thing[plural][j];
          if (!(name in hash)) {
            hash[name] = {
              'name': name,
              'active': false,
              'things': [],
            }
          }

          hash[name].things.push(thing);
        }
      }
    }
    // update the importance/urgency hash based on the thing
    var trackNumberHash = function(hash, type, thing) {
      var number = thing[type];

      if (number) {
        if (!(number in hash)) {
          hash[number] = {
            'name': number,
            'active': false,
            'things': [],
          };
        }
        // for now, ignore completed things
        if (thing.complete == 100) { return; }

        hash[number].things.push(thing);
      }
    }

    var resetHash = function(hash) {
      for (var key in hash) {
        hash[key].things = [];
      }
    }

    return service;
  }
);


text:
This project is part of the [NUBOMEDIA](http://www.nubomedia.eu/) research initiative.

### Connectors Overview
NUBOMEDIA Connectors enable interoperability of the NUBOMEDIA platfrom with external media service providers with the main objective to enrich the capabilitiy set of the NUBOMEDIA services. Ths CDN connector is an SDK which offers a framework that aggregates different CDN Data APIs towards NUBOMEDIA applications. Developers can incorporate this SDK to upload media sessions to CDN networks.

## Getting Started
To obtain the CDN connector, it can be done by means of [Maven](https://maven.apache.org/) in a Java project. The CDN Connector library can be found on [Maven central repository](http://search.maven.org/#search%7Cga%7C1%7Cde.fhg.fokus.nubomedia). Simply include it on your project's *pom.xml* file as describe below.

```xml
<dependencies>
   <!-- Nubomedia cdn client dependency -->
   <dependency>
      <groupId>de.fhg.fokus.nubomedia</groupId>
      <artifactId>nubomedia-cdn-client</artifactId>
      <version>0.0.5</version>
   </dependency>
</dependencies>
```

## Usage for Application Developers
### Youtube Provider API
To use the Nubomedia CDN Connector to upload a video that is stored on the kurento repository server, you have to connect a browser to the following destination:
```
http://<cdn-connector-ip>:9090/youtube?videoUrl=<repository-url>

<cdn-connector-ip>: IP of this server
<repository-url>: kurento repository url that would let you play the video directly,
e.g. http://localhost:7676/repository_servlet/k9uaue12345o4t20cd9pd80vl0
```

To get the correct repository url for the item you want uploaded to youtube, the following code snipped should help you:
```
RepositoryItemRecorder repoItem;
...
RepositoryItemPlayer itemPlayer = repositoryClient.getReadEndpoint(repoItem.getId());
String urlString = itemPlayer.getUrl();
```

Please Note: `repoItem.getUrl()` is not the correct URL!

To get notifications of the upload status, you can set up an EventSource at:

`http://<cdn-connector-ip>:9090/event?videoUrl=<repository-url>`

You can provide meta data for the video by adding the "metaData" query in the initial request, its value should be a json encoded as base64.

Here is a code snippet showing you how your javascript solution could look like:
```
var cdnurl = "http://localhost:9090";
var cdn_youtube = cdnurl + "/youtube";
var cdn_event = cdnurl + "/event";

var metaData = {
    "title": "someTitle",
    "description": "someDescription",
    "tags": [
        "firstTag",
        "secondTag",
        "thirdTag"
    ]
};

// set up EventSource
var eventUrl = cdn_event + "?videoUrl=" + videoUrl;
console.log("trying to connect to eventSource: " + eventUrl);
var eventSource = new EventSource(eventUrl);
var notificationCallback = function (msg) {
    var content = JSON.parse(msg.data);
    console.log("NOTIFICATION for %s: %s", content["videoUrl"], content);
};
eventSource.addEventListener('NOTIFICATION', notificationCallback, false);

// open browser window for URL
var url = cdn_youtube + "?videoUrl=" + videoUrl + "&metaData=" + window.btoa(JSON.stringify(metaData));
console.log("opening new window for: " + url);
window.open(url);
```
Issue tracker
-------------

Issues and bug reports should be posted to the [GitHub Issue List](https://github.com/fhg-fokus-nubomedia/nubomedia-cdn-connector/issues)

Licensing and distribution
--------------------------

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.

Support and Contribution
-------------------------

Need some support, wish to contribute? Then get in contact with us via our [mailinglist](mailto:nubomedia@fokus.fraunhofer.de)!


text:
import sys
import pysat
import pandas as pds
from nose.tools import assert_raises, raises
import nose.tools
import pysat.instruments.pysat_testing
import numpy as np
if sys.version_info[0] >= 3:
    if sys.version_info[1] < 4:
        import imp
        reload = imp.reload
    else:
        import importlib
        reload = importlib.reload

class TestBasics:
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '10',
                                         clean_level='clean',
                                         update_files=True)

    def teardown(self):
        '''Runs after every method to clean up previous testing.'''
        del self.testInst

###########################
    # basic loading tests, by date, filename, file id
    # and checks for .next and .prev data loading
    def test_basic_instrument_load(self):
        '''Test if the correct day is being loaded (checking object date and data).'''
        self.testInst.load(2009,1)
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2009,1,1)) & (test_date == self.testInst.date)

    def test_basic_instrument_load_data(self):
        '''Test if the correct day is being loaded (checking data down to the second).'''
        self.testInst.load(2009,1)
        assert self.testInst.data.index[0] == pds.datetime(2009,1,1,0,0,0)

    def test_basic_instrument_load_leap_year(self):
        '''Test if the correct day is being loaded (Leap-Year).'''
        self.testInst.load(2008,366)
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2008,12,31))  & (test_date == self.testInst.date)

    def test_next_load_default(self):
        '''Test if first day is loaded by default when first invoking .next.'''
        self.testInst.next()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert test_date == pds.datetime(2008,1,1)

    def test_prev_load_default(self):
        '''Test if last day is loaded by default when first invoking .prev.'''
        self.testInst.prev()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert test_date == pds.datetime(2010,12,31)

    def test_basic_fid_instrument_load(self):
        '''Test if first day is loaded by default when first invoking .next.'''
        self.testInst.load(fid=0)
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2008,1,1)) & (test_date == self.testInst.date)

    def test_next_fid_load_default(self):
        '''Test next day is being loaded (checking object date).'''
        self.testInst.load(fid=0)
        self.testInst.next()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2008,1,2)) & (test_date == self.testInst.date)

    def test_prev_fid_load_default(self):
        '''Test prev day is loaded when invoking .prev.'''
        self.testInst.load(fid=3)
        self.testInst.prev()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2008,1,3))  & (test_date == self.testInst.date)

    def test_filename_load(self):
        '''Test if file is loadable by filename, relative to top_data_dir/platform/name/tag'''
        self.testInst.load(fname='12/31/10.nofile')
        assert self.testInst.data.index[0] == pds.datetime(2010,12,31)

    def test_next_filename_load_default(self):
        '''Test next day is being loaded (checking object date).'''
        self.testInst.load(fname='12/30/10.nofile')
        self.testInst.next()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2010,12,31)) & (test_date == self.testInst.date)

    def test_prev_filename_load_default(self):
        '''Test prev day is loaded when invoking .prev.'''
        self.testInst.load(fname='01/04/09.nofile')
        # print(self.testInst.date)
        self.testInst.prev()
        test_date = self.testInst.data.index[0]
        test_date = pysat.datetime(test_date.year, test_date.month, test_date.day)
        assert (test_date == pds.datetime(2009,1,3))  & (test_date == self.testInst.date)

    ###########################
    # test flags
    def test_empty_flag_data_empty(self):
        assert self.testInst.empty

    def test_empty_flag_data_not_empty(self):
        self.testInst.load(2009, 1)
        assert not self.testInst.empty

    ############################
    # test the textual representation
    def test_basic_repr(self):
        print(self.testInst)
        assert True

    def test_repr_w_orbit(self):
        self.testInst.orbit_info = {'index': 'mlt', 'kind': 'local time', 'period': np.timedelta64(97, 'm')}
        self.testInst.orbits.num = 10
        print(self.testInst)
        assert True

    def test_repr_w_padding(self):
        self.testInst.pad = pds.DateOffset(minutes=5)
        print(self.testInst)
        assert True

    def test_repr_w_custom_func(self):
        def testfunc(self):
            pass
        self.testInst.custom.add(testfunc, 'modify')
        print(self.testInst)
        assert True

    def test_repr_w_load_data(self):
        self.testInst.load(2009,1)
        print(self.testInst)
        assert True

### testing init functions

###### need to check with default1!!!!!
    def test_instrument_init(self):
        """Test if init function supplied by instrument can modify object"""
        assert self.testInst.new_thing==True

#     def test_getyrdoy_1(self):
#         '''Test the date to year, day of year code functionality'''
#         date = pds.datetime(2009,1,1)
#         yr, doy = pysat.utils.getyrdoy(date)
#         assert ((yr == 2009) & (doy == 1))
#
#     def test_getyrdoy_leap_year(self):
#         '''Test the date to year, day of year code functionality (leap_year)'''
#         date = pds.datetime(2008,12,31)
#         yr, doy = pysat.utils.getyrdoy(date)
#         assert ((yr == 2008) & (doy == 366))

    def test_custom_instrument_load(self):
        '''
        Test if the correct day is being loaded (End-to-End),
        with no instrument file but routines are passed.
        '''
        import pysat.instruments.pysat_testing as test
        testInst = pysat.Instrument(inst_module=test, tag='', clean_level='clean')
        testInst.load(2009,32)
        assert testInst.date == pds.datetime(2009,2,1)

    @raises(AttributeError)
    def test_custom_instrument_load_2(self):
        '''
        Test if an exception is thrown correctly if there is no
        instrument file and supplied routines are incomplete.
        '''
        import pysat.instruments.pysat_testing as test
        del test.list_files
        testIn = pysat.Instrument(inst_module=test, tag='', clean_level='clean')
        testIn.load(2009,1)

    @raises(AttributeError)
    def test_custom_instrument_load_3(self):
        '''
        Test if an exception is thrown correctly if there is no
        instrument file and supplied routines are incomplete.
        '''
        import pysat.instruments.pysat_testing as test
        del test.load
        testIn = pysat.Instrument(inst_module=test, tag='', clean_level='clean')
        testIn.load(2009,1)

###################3
        # test data access features
    def test_basic_data_access_by_name(self):
        self.testInst.load(2009,1)
        assert np.all(self.testInst['uts'] == self.testInst.data['uts'])

    def test_data_access_by_row_slicing_and_name(self):
        self.testInst.load(2009,1)
        assert np.all(self.testInst[0:10,'uts'] == self.testInst.data.ix[0:10,'uts'])

    def test_data_access_by_row_and_name(self):
        self.testInst.load(2009,1)
        assert np.all(self.testInst[0,'uts'] == self.testInst.data.ix[0,'uts'])

    def test_data_access_by_datetime_and_name(self):
        self.testInst.load(2009,1)
        assert np.all(self.testInst[pysat.datetime(2009,1,1,0,0,0),'uts'] == self.testInst.data.ix[0,'uts'])

    def test_data_access_by_datetime_slicing_and_name(self):
        self.testInst.load(2009,1)
        assert np.all(self.testInst[pysat.datetime(2009,1,1,0,0,0):pysat.datetime(2009,1,1,0,0,10),'uts'] ==
                        self.testInst.data.ix[0:11,'uts'])

    def test_setting_data_by_name(self):
        self.testInst.load(2009,1)
        self.testInst['doubleMLT'] = 2.*self.testInst['mlt']
        assert np.all(self.testInst['doubleMLT'] == 2.*self.testInst['mlt'])

    def test_setting_data_by_name_with_meta(self):
        self.testInst.load(2009,1)
        self.testInst['doubleMLT'] = {'data':2.*self.testInst['mlt'],
                                      'units':'hours',
                                      'long_name':'double trouble'}
        check1 = np.all(self.testInst['doubleMLT'] == 2.*self.testInst['mlt'])
        check2 = self.testInst.meta['doubleMLT'].units == 'hours'
        check3 = self.testInst.meta['doubleMLT'].long_name == 'double trouble'
        assert check1 & check2 & check3

    def test_setting_partial_data_by_name(self):
        self.testInst.load(2009,1)
        self.testInst['doubleMLT'] = 2.*self.testInst['mlt']
        self.testInst[0,'doubleMLT'] = 0
        assert np.all(self.testInst[1:,'doubleMLT'] == 2.*self.testInst[1:,'mlt']) & (self.testInst[0,'doubleMLT'] == 0)

    def test_setting_partial_slice_data_by_name(self):
        self.testInst.load(2009,1)
        self.testInst['doubleMLT'] = 2.*self.testInst['mlt']
        self.testInst[0:10,'doubleMLT'] = 0
        assert np.all(self.testInst[10:,'doubleMLT'] == 2.*self.testInst[10:,'mlt']) & np.all(self.testInst[0:10,'doubleMLT'] == 0)

#######################
######
#### check iteration behavior
    @raises(StopIteration)
    def test_left_bounds_with_prev(self):
        '''Test if passing bounds raises StopIteration.'''
        # load first data
        self.testInst.next()
        # go back to no data
        self.testInst.prev()
        # self.testInst.prev()

    @raises(StopIteration)
    def test_right_bounds_with_next(self):
        '''Test if passing bounds raises StopIteration.'''
        # load last data
        self.testInst.prev()
        # move on to future data that doesn't exist
        self.testInst.next()
        # self.testInst.next()

    def test_set_bounds_by_date(self):
        start = pysat.datetime(2009,1,1)
        stop = pysat.datetime(2009,1,15)
        self.testInst.bounds = (start, stop)
        assert np.all(self.testInst._iter_list == pds.date_range(start, stop).tolist())

    def test_iterate_over_bounds_set_by_date(self):
        start = pysat.datetime(2009,1,1)
        stop = pysat.datetime(2009,1,15)
        self.testInst.bounds = (start, stop)
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start, stop).tolist()
        assert np.all(dates == out)

    def test_iterate_over_default_bounds(self):
        start = pysat.datetime(2008,1,1)
        stop = pysat.datetime(2010,12,31)
        self.testInst.bounds = (start, stop)
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start, stop).tolist()
        assert np.all(dates == out)

    def test_set_bounds_by_date_season(self):
        start = [pysat.datetime(2009,1,1), pysat.datetime(2009,2,1)]
        stop = [pysat.datetime(2009,1,15), pysat.datetime(2009,2,15)]
        self.testInst.bounds = (start, stop)
        out = pds.date_range(start[0], stop[0]).tolist()
        out.extend(pds.date_range(start[1], stop[1]).tolist())
        assert np.all(self.testInst._iter_list == out)

    def test_iterate_over_bounds_set_by_date_season(self):
        start = [pysat.datetime(2009,1,1), pysat.datetime(2009,2,1)]
        stop = [pysat.datetime(2009,1,15), pysat.datetime(2009,2,15)]
        self.testInst.bounds = (start, stop)
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start[0], stop[0]).tolist()
        out.extend(pds.date_range(start[1], stop[1]).tolist())
        assert np.all(dates == out)

    def test_set_bounds_by_fname(self):
        start = '01/01/09.nofile'
        stop = '01/03/09.nofile'
        self.testInst.bounds = (start, stop)
        assert np.all(self.testInst._iter_list ==
            ['01/01/09.nofile', '01/02/09.nofile', '01/03/09.nofile'])

    def test_iterate_over_bounds_set_by_fname(self):
        start = '01/01/09.nofile'
        stop = '01/15/09.nofile'
        start_d = pysat.datetime(2009,1,1)
        stop_d = pysat.datetime(2009,1,15)
        self.testInst.bounds = (start, stop)
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start_d, stop_d).tolist()
        assert np.all(dates == out)

    def test_iterate_over_bounds_set_by_fname_via_next(self):
        start = '01/01/09.nofile'
        stop = '01/15/09.nofile'
        start_d = pysat.datetime(2009,1,1)
        stop_d = pysat.datetime(2009,1,15)
        self.testInst.bounds = (start, stop)
        dates = []
        self.testInst.next()
        dates.append(self.testInst.date)
        while self.testInst.date < stop_d:
            self.testInst.next()
            dates.append(self.testInst.date)
        out = pds.date_range(start_d, stop_d).tolist()
        assert np.all(dates == out)

    def test_iterate_over_bounds_set_by_fname_via_prev(self):
        start = '01/01/09.nofile'
        stop = '01/15/09.nofile'
        start_d = pysat.datetime(2009,1,1)
        stop_d = pysat.datetime(2009,1,15)
        self.testInst.bounds = (start, stop)
        dates = []
        self.testInst.prev()
        dates.append(self.testInst.date)
        while self.testInst.date > start_d:
            self.testInst.prev()
            dates.append(self.testInst.date)
        out = pds.date_range(start_d, stop_d).tolist()
        assert np.all(dates == out[::-1])

    def test_set_bounds_by_fname_season(self):
        start = ['01/01/09.nofile', '02/01/09.nofile']
        stop = ['01/03/09.nofile', '02/03/09.nofile']
        self.testInst.bounds = (start, stop)
        assert np.all(self.testInst._iter_list ==
            ['01/01/09.nofile', '01/02/09.nofile', '01/03/09.nofile',
            '02/01/09.nofile', '02/02/09.nofile', '02/03/09.nofile'])

    def test_iterate_over_bounds_set_by_fname_season(self):
        start = ['01/01/09.nofile', '02/01/09.nofile']
        stop = ['01/15/09.nofile', '02/15/09.nofile']
        start_d = [pysat.datetime(2009,1,1), pysat.datetime(2009,2,1)]
        stop_d = [pysat.datetime(2009,1,15), pysat.datetime(2009,2,15)]
        self.testInst.bounds = (start, stop)
        dates = []
        for inst in self.testInst:
            dates.append(inst.date)
        out = pds.date_range(start_d[0], stop_d[0]).tolist()
        out.extend(pds.date_range(start_d[1], stop_d[1]).tolist())
        assert np.all(dates == out)

    def test_creating_empty_instrument_object(self):
        null = pysat.Instrument()

        assert isinstance(null, pysat.Instrument)

    @raises(ValueError)
    def test_incorrect_creation_empty_instrument_object(self):
        # both name and platform should be empty
        null = pysat.Instrument(platform='cnofs')

    @raises(AttributeError)
    def test_supplying_instrument_module_requires_name_and_platform(self):
        class Dummy: pass
        Dummy.name = 'help'

        temp = pysat.Instrument(inst_module=Dummy)

class TestDataPaddingbyFile():
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         pad={'minutes':5},
                                         update_files=True)
        self.testInst.bounds = ('01/01/08.nofile','12/31/10.nofile')

        self.rawInst = pysat.Instrument('pysat', 'testing', '',
                                    clean_level='clean',
                                    update_files=True)
        self.rawInst.bounds = self.testInst.bounds

    def test_fid_data_padding(self):
        self.testInst.load(fid=1, verifyPad=True)
        self.rawInst.load(fid=1)
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )

    def test_fid_data_padding_next(self):
        self.testInst.load(fid=1, verifyPad=True)
        self.testInst.next(verifyPad=True)
        self.rawInst.load(fid=2)
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )

    def test_fid_data_padding_multi_next(self):
        """This also tests that _prev_data and _next_data cacheing"""
        self.testInst.load(fid=1)
        self.testInst.next()
        self.testInst.next(verifyPad=True)
        self.rawInst.load(fid=3)
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )

    def test_fid_data_padding_prev(self):
        self.testInst.load(fid=2, verifyPad=True)
        self.testInst.prev(verifyPad=True)
        #print(self.testInst.data.index)
        self.rawInst.load(fid=1)
        #print(self.rawInst.data.index)
        #print(self.testInst.data.index[0], self.rawInst.data.index[0] - pds.DateOffset(minutes=5),
        #   self.testInst.data.index[-1],  self.rawInst.data.index[-1] + pds.DateOffset(minutes=5))
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )

    def test_fid_data_padding_multi_prev(self):
        """This also tests that _prev_data and _next_data cacheing"""
        self.testInst.load(fid=10)
        self.testInst.prev()
        self.testInst.prev(verifyPad=True)
        self.rawInst.load(fid=8)
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )

    def test_fid_data_padding_jump(self):
        self.testInst.load(fid=1, verifyPad=True)
        self.testInst.load(fid=10, verifyPad=True)
        self.rawInst.load(fid=10)
        assert ( (self.testInst.data.index[0] == self.rawInst.data.index[0] - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1] + pds.DateOffset(minutes=5)) )
    def test_fid_data_padding_uniqueness(self):
        self.testInst.load(fid=1, verifyPad=True)
        assert (self.testInst.data.index.is_unique)

    def test_fid_data_padding_all_samples_present(self):
        self.testInst.load(fid=1, verifyPad=True)
        test_index = pds.date_range(self.testInst.data.index[0], self.testInst.data.index[-1], freq='S')
        #print (test_index[0], test_index[-1], len(test_index))
        #print(self.testInst.data.index[0], self.testInst.data.index[-1], len(self.testInst.data))
        assert (np.all(self.testInst.data.index == test_index))

    def test_fid_data_padding_removal(self):
        self.testInst.load(fid=1)
        self.rawInst.load(fid=1)
        #print(self.testInst.data.index)
        #print(new_inst.data.index)
        assert (self.testInst.data.index[0] == self.rawInst.data.index[0] ) & \
                (self.testInst.data.index[-1] == self.rawInst.data.index[-1]) & \
                (len(self.rawInst.data) == len(self.testInst.data))

class TestOffsetRightFileDataPaddingBasics(TestDataPaddingbyFile):
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_right=True,
                                         pad={'minutes':5})
        self.rawInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_right=True)
        self.testInst.bounds = ('01/01/08.nofile','12/31/10.nofile')
        self.rawInst.bounds = self.testInst.bounds

class TestOffsetLeftFileDataPaddingBasics(TestDataPaddingbyFile):
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_left=True,
                                         pad={'minutes':5})
        self.rawInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_left=True)
        self.testInst.bounds = ('01/01/08.nofile','12/31/10.nofile')
        self.rawInst.bounds = self.testInst.bounds

class TestDataPadding():
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         pad={'minutes':5},
                                         update_files=True)

    def test_data_padding(self):
        self.testInst.load(2009,2, verifyPad=True)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_next(self):
        self.testInst.load(2009,2, verifyPad=True)
        self.testInst.next(verifyPad=True)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_multi_next(self):
        #"""This also tests that _prev_data and _next_data cacheing"""
        self.testInst.load(2009,2)
        self.testInst.next()
        self.testInst.next(verifyPad=True)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_prev(self):
        self.testInst.load(2009, 2, verifyPad=True)
        self.testInst.prev(verifyPad=True)
        print(self.testInst.data.index)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_multi_prev(self):
        #"""This also tests that _prev_data and _next_data cacheing"""
        self.testInst.load(2009, 10)
        self.testInst.prev()
        self.testInst.prev(verifyPad=True)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_jump(self):
        self.testInst.load(2009, 2, verifyPad=True)
        self.testInst.load(2009, 11, verifyPad=True)
        assert ( (self.testInst.data.index[0] == self.testInst.date - pds.DateOffset(minutes=5)) &
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hours=23,minutes=59,seconds=59) +
                                        pds.DateOffset(minutes=5)) )

    def test_data_padding_uniqueness(self):
        self.testInst.load(2009,1, verifyPad=True)
        assert (self.testInst.data.index.is_unique)

    def test_data_padding_all_samples_present(self):
        self.testInst.load(2009,1, verifyPad=True)
        test_index = pds.date_range(self.testInst.data.index[0], self.testInst.data.index[-1], freq='S')
        #print (test_index[0], test_index[-1], len(test_index))
        #print(self.testInst.data.index[0], self.testInst.data.index[-1], len(self.testInst.data))
        assert (np.all(self.testInst.data.index == test_index))

    def test_data_padding_removal(self):
        self.testInst.load(2009,1)
        #print(self.testInst.data.index)
        assert (self.testInst.data.index[0] == self.testInst.date ) & \
                (self.testInst.data.index[-1] == self.testInst.date + pds.DateOffset(hour=23, minutes=59,seconds=59) )

class TestMultiFileRightDataPaddingBasics(TestDataPadding):
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_right=True,
                                         pad={'minutes':5},
                                         multi_file_day=True)

class TestMultiFileLeftDataPaddingBasics(TestDataPadding):
    def setup(self):
        reload(pysat.instruments.pysat_testing)
        '''Runs before every method to create a clean testing setup.'''
        self.testInst = pysat.Instrument('pysat', 'testing', '',
                                         clean_level='clean',
                                         update_files=True,
                                         sim_multi_file_left=True,
                                         pad={'minutes':5},
                                         multi_file_day=True)


text:
#ifndef NETWORKEXCEPTIONS_H
#define NETWORKEXCEPTIONS_H

#include "../Exception/Exception.h"

namespace Net
{
    EXCEPTION_DEF(SocketException, Except::IOException)
    EXCEPTION_DEF(NetException, Except::IOException)

    EXCEPTION_DEF(ConnectionAbortedException, NetException)
    EXCEPTION_DEF(ConnectionResetException, NetException)
    EXCEPTION_DEF(ConnectionRefusedException, NetException)

    using InvalidSocketException = std::logic_error;
}

#endif  /* NETWORKEXCEPTIONS_H */


text:
namespace smug {
class SSScript : public SubSystem {
  public:
	SSScript();
	~SSScript();

	virtual void Startup();
	virtual void Update(const double deltaTime, Profiler* profiler);
	virtual void Shutdown();
  private:
};
}