text:
package jsonschema

// The Schema struct models a JSON Schema and, because schemas are
// defined hierarchically, contains many references to itself.
// All fields are pointers and are nil if the associated values
// are not specified.
type Schema struct {
	Schema *string // $schema
	ID     *string // id keyword used for $ref resolution scope
	Ref    *string // $ref, i.e. JSON Pointers

	// http://json-schema.org/latest/json-schema-validation.html
	// 5.1.  Validation keywords for numeric instances (number and integer)
	MultipleOf       *SchemaNumber
	Maximum          *SchemaNumber
	ExclusiveMaximum *bool
	Minimum          *SchemaNumber
	ExclusiveMinimum *bool

	// 5.2.  Validation keywords for strings
	MaxLength *int64
	MinLength *int64
	Pattern   *string

	// 5.3.  Validation keywords for arrays
	AdditionalItems *SchemaOrBoolean
	Items           *SchemaOrSchemaArray
	MaxItems        *int64
	MinItems        *int64
	UniqueItems     *bool

	// 5.4.  Validation keywords for objects
	MaxProperties        *int64
	MinProperties        *int64
	Required             *[]string
	AdditionalProperties *SchemaOrBoolean
	Properties           *[]*NamedSchema
	PatternProperties    *[]*NamedSchema
	Dependencies         *[]*NamedSchemaOrStringArray

	// 5.5.  Validation keywords for any instance type
	Enumeration *[]SchemaEnumValue
	Type        *StringOrStringArray
	AllOf       *[]*Schema
	AnyOf       *[]*Schema
	OneOf       *[]*Schema
	Not         *Schema
	Definitions *[]*NamedSchema

	// 6.  Metadata keywords
	Title       *string
	Description *string
	Default     *interface{}

	// 7.  Semantic validation with "format"
	Format *string
}

// These helper structs represent "combination" types that generally can
// have values of one type or another. All are used to represent parts
// of Schemas.

// SchemaNumber represents a value that can be either an Integer or a Float.
type SchemaNumber struct {
	Integer *int64
	Float   *float64
}

// NewSchemaNumberWithInteger creates and returns a new object
func NewSchemaNumberWithInteger(i int64) *SchemaNumber {
	result := &SchemaNumber{}
	result.Integer = &i
	return result
}

// NewSchemaNumberWithFloat creates and returns a new object
func NewSchemaNumberWithFloat(f float64) *SchemaNumber {
	result := &SchemaNumber{}
	result.Float = &f
	return result
}

// SchemaOrBoolean represents a value that can be either a Schema or a Boolean.
type SchemaOrBoolean struct {
	Schema  *Schema
	Boolean *bool
}

// NewSchemaOrBooleanWithSchema creates and returns a new object
func NewSchemaOrBooleanWithSchema(s *Schema) *SchemaOrBoolean {
	result := &SchemaOrBoolean{}
	result.Schema = s
	return result
}

// NewSchemaOrBooleanWithBoolean creates and returns a new object
func NewSchemaOrBooleanWithBoolean(b bool) *SchemaOrBoolean {
	result := &SchemaOrBoolean{}
	result.Boolean = &b
	return result
}

// StringOrStringArray represents a value that can be either
// a String or an Array of Strings.
type StringOrStringArray struct {
	String      *string
	StringArray *[]string
}

// NewStringOrStringArrayWithString creates and returns a new object
func NewStringOrStringArrayWithString(s string) *StringOrStringArray {
	result := &StringOrStringArray{}
	result.String = &s
	return result
}

// NewStringOrStringArrayWithStringArray creates and returns a new object
func NewStringOrStringArrayWithStringArray(a []string) *StringOrStringArray {
	result := &StringOrStringArray{}
	result.StringArray = &a
	return result
}

// SchemaOrStringArray represents a value that can be either
// a Schema or an Array of Strings.
type SchemaOrStringArray struct {
	Schema      *Schema
	StringArray *[]string
}

// SchemaOrSchemaArray represents a value that can be either
// a Schema or an Array of Schemas.
type SchemaOrSchemaArray struct {
	Schema      *Schema
	SchemaArray *[]*Schema
}

// NewSchemaOrSchemaArrayWithSchema creates and returns a new object
func NewSchemaOrSchemaArrayWithSchema(s *Schema) *SchemaOrSchemaArray {
	result := &SchemaOrSchemaArray{}
	result.Schema = s
	return result
}

// NewSchemaOrSchemaArrayWithSchemaArray creates and returns a new object
func NewSchemaOrSchemaArrayWithSchemaArray(a []*Schema) *SchemaOrSchemaArray {
	result := &SchemaOrSchemaArray{}
	result.SchemaArray = &a
	return result
}

// SchemaEnumValue represents a value that can be part of an
// enumeration in a Schema.
type SchemaEnumValue struct {
	String *string
	Bool   *bool
}

// NamedSchema is a name-value pair that is used to emulate maps
// with ordered keys.
type NamedSchema struct {
	Name  string
	Value *Schema
}

// NewNamedSchema creates and returns a new object
func NewNamedSchema(name string, value *Schema) *NamedSchema {
	return &NamedSchema{Name: name, Value: value}
}

// NamedSchemaOrStringArray is a name-value pair that is used
// to emulate maps with ordered keys.
type NamedSchemaOrStringArray struct {
	Name  string
	Value *SchemaOrStringArray
}

// Access named subschemas by name

func namedSchemaArrayElementWithName(array *[]*NamedSchema, name string) *Schema {
	if array == nil {
		return nil
	}
	for _, pair := range *array {
		if pair.Name == name {
			return pair.Value
		}
	}
	return nil
}

// PropertyWithName returns the selected element.
func (s *Schema) PropertyWithName(name string) *Schema {
	return namedSchemaArrayElementWithName(s.Properties, name)
}

// PatternPropertyWithName returns the selected element.
func (s *Schema) PatternPropertyWithName(name string) *Schema {
	return namedSchemaArrayElementWithName(s.PatternProperties, name)
}

// DefinitionWithName returns the selected element.
func (s *Schema) DefinitionWithName(name string) *Schema {
	return namedSchemaArrayElementWithName(s.Definitions, name)
}

// AddProperty adds a named property.
func (s *Schema) AddProperty(name string, property *Schema) {
	*s.Properties = append(*s.Properties, NewNamedSchema(name, property))
}


text:
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description:  The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/14/2009 3:58:48 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************

using System;
using System.Runtime.Serialization;

namespace DotSpatial.Data
{
    public class ExtentParseException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the ExtentParseException
        /// </summary>
        /// <param name="message">The string message to parse.</param>
        public ExtentParseException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the ExtentParseException
        /// </summary>
        /// <param name="message">The string message to parse.</param>
        /// <param name="innerException">The inner exception that caused this exception.</param>
        public ExtentParseException(string message, Exception innerException)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the ExtentParseException
        /// </summary>
        /// <param name="info">The Serialization info class that holds the serialized object about which
        /// the exception is being thrown.</param>
        /// <param name="context">The streaming context that contains contextual information about the
        /// source or destination.</param>
        public ExtentParseException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Gets the string expression that provoked the exception.
        /// </summary>
        public string Expression { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>VirtualFile (Play! API)</title>
<meta name="date" content="2016-03-30">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

play.vfs

Class VirtualFile

java.lang.Object

play.vfs.VirtualFile

public class VirtualFile
extends java.lang.Object

The VFS used by Play!

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.nio.channels.Channel
channel()

VirtualFile
child(java.lang.String name)

byte[]
content()

java.lang.String
contentAsString()

boolean
equals(java.lang.Object other)

boolean
exists()

static VirtualFile
fromRelativePath(java.lang.String relativePath)

java.lang.String
getName()

java.io.File
getRealFile()

int
hashCode()

java.io.InputStream
inputstream()

boolean
isDirectory()

java.lang.Long
lastModified()

long
length()

java.util.List<VirtualFile>
list()

boolean
matchName(java.lang.String fileName)

Method to check if the name really match (very useful on system without case sensibility (like windows))

static VirtualFile
open(java.io.File file)

static VirtualFile
open(java.lang.String file)

java.io.OutputStream
outputstream()

java.lang.String
relativePath()

static VirtualFile
search(java.util.Collection<VirtualFile> roots,
      java.lang.String path)

java.lang.String
toString()

void
write(java.lang.CharSequence string)

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Method Detail

getName

public java.lang.String getName()

isDirectory

public boolean isDirectory()

relativePath

public java.lang.String relativePath()

list

public java.util.List<VirtualFile> list()

exists

public boolean exists()

inputstream

public java.io.InputStream inputstream()

outputstream

public java.io.OutputStream outputstream()

lastModified

public java.lang.Long lastModified()

equals

public boolean equals(java.lang.Object other)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

length

public long length()

child

public VirtualFile child(java.lang.String name)

channel

public java.nio.channels.Channel channel()

open

public static VirtualFile open(java.lang.String file)

open

public static VirtualFile open(java.io.File file)

contentAsString

public java.lang.String contentAsString()

getRealFile

public java.io.File getRealFile()

write

public void write(java.lang.CharSequence string)

content

public byte[] content()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

search

public static VirtualFile search(java.util.Collection<VirtualFile> roots,
                                 java.lang.String path)

fromRelativePath

public static VirtualFile fromRelativePath(java.lang.String relativePath)

matchName

public boolean matchName(java.lang.String fileName)

Method to check if the name really match (very useful on system without case sensibility (like windows))

Parameters:

fileName -

Returns:

true if match

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
package snapshot

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"hash"
	"io"
	"os"

	"github.com/golang/protobuf/proto"
	"github.com/pkg/errors"
)

type NewHashFunc func() (hash.Hash, error)

// FileWriter creates a new file for ledger snapshot. This is expected to be used by various
// components of ledger, such as blockstorage and statedb for exporting the relevant snapshot data
type FileWriter struct {
	file              *os.File
	hasher            hash.Hash
	bufWriter         *bufio.Writer
	multiWriter       io.Writer
	varintReusableBuf []byte
}

// CreateFile creates a new file for exporting the ledger snapshot data
// This function returns an error if the file already exists. The `dataformat` is the first byte
// written to the file. The function newHash is used to construct an hash.Hash for computing the hash-sum of the data stream
func CreateFile(filePath string, dataformat byte, newHashFunc NewHashFunc) (*FileWriter, error) {
	hashImpl, err := newHashFunc()
	if err != nil {
		return nil, err
	}
	// create the file only if it does not already exist.
	// set the permission mode to read-only, as once the file is closed, we do not support modifying the file
	file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o444)
	if err != nil {
		return nil, errors.Wrapf(err, "error while creating the snapshot file: %s", filePath)
	}
	bufWriter := bufio.NewWriter(file)
	multiWriter := io.MultiWriter(bufWriter, hashImpl)
	if _, err := multiWriter.Write([]byte{dataformat}); err != nil {
		file.Close()
		return nil, errors.Wrapf(err, "error while writing data format to the snapshot file: %s", filePath)
	}
	return &FileWriter{
		file:              file,
		bufWriter:         bufWriter,
		multiWriter:       multiWriter,
		hasher:            hashImpl,
		varintReusableBuf: make([]byte, binary.MaxVarintLen64),
	}, nil
}

// EncodeString encodes and appends the string to the data stream
func (c *FileWriter) EncodeString(str string) error {
	return c.EncodeBytes([]byte(str))
}

// EncodeString encodes and appends a proto message to the data stream
func (c *FileWriter) EncodeProtoMessage(m proto.Message) error {
	b, err := proto.Marshal(m)
	if err != nil {
		return errors.Wrapf(err, "error marshalling proto message to write to the snapshot file: %s", c.file.Name())
	}
	return c.EncodeBytes(b)
}

// EncodeBytes encodes and appends bytes to the data stream
func (c *FileWriter) EncodeBytes(b []byte) error {
	if err := c.EncodeUVarint(uint64(len(b))); err != nil {
		return err
	}
	if _, err := c.multiWriter.Write(b); err != nil {
		return errors.Wrapf(err, "error while writing data to the snapshot file: %s", c.file.Name())
	}
	return nil
}

// EncodeUVarint encodes and appends a number to the data stream
func (c *FileWriter) EncodeUVarint(u uint64) error {
	n := binary.PutUvarint(c.varintReusableBuf, u)
	if _, err := c.multiWriter.Write(c.varintReusableBuf[:n]); err != nil {
		return errors.Wrapf(err, "error while writing data to the snapshot file: %s", c.file.Name())
	}
	return nil
}

// Done closes the snapshot file and returns the final hash of the data stream
func (c *FileWriter) Done() ([]byte, error) {
	if err := c.bufWriter.Flush(); err != nil {
		return nil, errors.Wrapf(err, "error while flushing to the snapshot file: %s ", c.file.Name())
	}
	if err := c.file.Sync(); err != nil {
		return nil, err
	}
	if err := c.file.Close(); err != nil {
		return nil, errors.Wrapf(err, "error while closing the snapshot file: %s ", c.file.Name())
	}
	return c.hasher.Sum(nil), nil
}

// Close closes the underlying file, if not already done. A consumer can invoke this function if the consumer
// encountered some error and simply wants to abandon the snapshot file creation (typically, intended to be used in a defer statement)
func (c *FileWriter) Close() error {
	if c == nil {
		return nil
	}
	return errors.Wrapf(c.file.Close(), "error while closing the snapshot file: %s", c.file.Name())
}

// FileReader reads from a ledger snapshot file. This is expected to be used for loading the ledger snapshot data
// during bootstrapping a channel from snapshot. The data should be read, using the functions `DecodeXXX`,
// in the same sequence in which the data was written by the functions `EncodeXXX` in the `FileCreator`.
// Note that the FileReader does not verifies the hash of stream and it is expected that the hash has been verified
// by the consumer. Later, if we decide to perform this, on-the-side, while loading the snapshot data, the FileRedear,
// like the FileCreator, would take a `hasher` as an input
type FileReader struct {
	file              *os.File
	bufReader         *bufio.Reader
	reusableByteSlice []byte
}

// OpenFile constructs a FileReader. This function returns an error if the format of the file, stored in the
// first byte, does not match with the expectedDataFormat
func OpenFile(filePath string, expectDataformat byte) (*FileReader, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, errors.Wrapf(err, "error while opening the snapshot file: %s", filePath)
	}
	bufReader := bufio.NewReader(file)
	dataFormat, err := bufReader.ReadByte()
	if err != nil {
		file.Close()
		return nil, errors.Wrapf(err, "error while reading from the snapshot file: %s", filePath)
	}
	if dataFormat != expectDataformat {
		file.Close()
		return nil, errors.New(fmt.Sprintf("unexpected data format: %x", dataFormat))
	}
	return &FileReader{
		file:      file,
		bufReader: bufReader,
	}, nil
}

// DecodeString reads and decodes a string
func (r *FileReader) DecodeString() (string, error) {
	b, err := r.decodeBytes()
	return string(b), err
}

// DecodeBytes reads and decodes bytes
func (r *FileReader) DecodeBytes() ([]byte, error) {
	b, err := r.decodeBytes()
	if err != nil {
		return nil, err
	}
	c := make([]byte, len(b))
	copy(c, b)
	return c, nil
}

// DecodeUVarInt reads and decodes a number
func (r *FileReader) DecodeUVarInt() (uint64, error) {
	u, err := binary.ReadUvarint(r.bufReader)
	if err != nil {
		return 0, errors.Wrapf(err, "error while reading from snapshot file: %s", r.file.Name())
	}
	return u, nil
}

// DecodeProtoMessage reads and decodes a protoMessage
func (r *FileReader) DecodeProtoMessage(m proto.Message) error {
	b, err := r.decodeBytes()
	if err != nil {
		return err
	}
	return proto.Unmarshal(b, m)
}

// Close closes the file
func (r *FileReader) Close() error {
	if r == nil {
		return nil
	}
	return errors.Wrapf(r.file.Close(), "error while closing the snapshot file: %s", r.file.Name())
}

func (r *FileReader) decodeBytes() ([]byte, error) {
	sizeUint, err := r.DecodeUVarInt()
	if err != nil {
		return nil, err
	}
	size := int(sizeUint)
	if size == 0 {
		return []byte{}, nil
	}
	if len(r.reusableByteSlice) < size {
		r.reusableByteSlice = make([]byte, size)
	}
	if _, err := io.ReadFull(r.bufReader, r.reusableByteSlice[0:size]); err != nil {
		return nil, errors.Wrapf(err, "error while reading from snapshot file: %s", r.file.Name())
	}
	return r.reusableByteSlice[0:size], nil
}


text:
import React from 'react';
import Post from '../Post';

class CategoryTemplateDetails extends React.Component {
  render() {
    const items = [];
    const { category } = this.props.pageContext;
    const posts = this.props.data.allMarkdownRemark.edges;
    posts.forEach((post) => {
      items.push(<Post data={post} key={post.node.fields.slug} />);
    });

    return (

{category}

{items}

    );
  }
}

export default CategoryTemplateDetails;


text: my code examples from Event Hub


text:
class BuildHooksWorker
  include Sidekiq::Worker
  sidekiq_options queue: :default

  def perform(build_id)
    Ci::Build.find_by(id: build_id)
      .try(:execute_hooks)
  end
end


text:
function initilizeDashboard() {
	$('#mcuDashboardPanel').hide();
	$('#showHm').click(function() {
		hideAllPanels();
		$('#mcuDashboardPanel').show();
	});
}
function loadAllMasterUnitIntoDashboard() {
	$.getJSON('rest/mcu/getAllMCU', function(data) {
		index = 1;
		addRecord = "";
		$.each(data, function(key, val) {
			addRecord += '
'
					+ val.masterUnitName + '
' + val.masterUnitMacID
					+ '
' + val.masterUnitSoftwareVersion + '
'
					+ val.masterUnitIPaddr + '
';
			index = index + 1;

		});
		appendEndDiv(addRecord);
		initilizeWebSocket();
	});
}
function appendEndDiv(addRecord) {
	$('#mcuDB').html('
' + addRecord + "
");
}
var wsocket;
var isConnected;
var timerFn;
var browserClient="HAServerAPP";

function initilizeWebSocket() {
	isConnected = false;
	url = "ws://localhost:8080/plugin-cloud-server/has";
//	alert(url);
	webSocket = new WebSocket(url);
	webSocket.onopen = function(message){ wsOpen(message);};
	webSocket.onmessage = function(message){ wsGetMessage(message);};
	webSocket.onclose = function(message){ wsClose(message);};
	webSocket.onerror = function(message){ wsError(message);};
}
function wsOpen(message){
	isConnected = true;
}
function wsSendRegMessage(){
	//Message Type: Register, Status: send to Server;; "Command": Send from Server
	var sendTo = "{'messageFrom':'"+browserClient+"', 'messageTo':'HAServer', 'messageType':'REG', 'masterUnitLicense':'ADMIN', 'message':'ADMIN'}";
	webSocket.send(sendTo);
	updateStatus();
	$('#liveUpdate').html('Disable Live');
}
function updateStatus() {
	var sendTo = "{'messageFrom':'"+browserClient+"', 'messageTo':'HAServer', 'messageType':'MUU', 'masterUnitLicense':'ADMIN', 'message':'ADMIN'}";
	webSocket.send(sendTo);
}
function wsCloseConnection(){
	webSocket.close();
}
function wsGetMessage(message){
	var response = JSON.parse(message.data);
	console.log(response);
	if(response.messageType === 'ACTMCU') {
		$('#'+response.message).removeClass('mcurecordRedColor').addClass('mcurecordGreenColor');
	}
	else if(response.messageType === 'DISMCU') {
		$('#'+response.message).removeClass('mcurecordGreenColor').addClass('mcurecordRedColor');
	}
	else if(response.messageType === 'MUU') {
		var msg = new String(response.message);
		var activeMCU = msg.split(',');
		for(i = 1; i < activeMCU.length; i ++) {
			alert(activeMCU[i-1]);
			$('#'+activeMCU[i-1]).removeClass('mcurecordRedColor').addClass('mcurecordGreenColor');
		}
	}
	else {
		console.log('No Mapping: '+response.message);
	}
}
function wsClose(message){
	console.log("Disconnect");
	isConnected = false;
	timerFn = setInterval(reconect, 10000);
}
function reconect() {
	console.log('Trying to Connect...');
	initilizeWebSocket();
	if(isConnected == true) clearInterval(timerFn);
}

function wserror(message){
	console.log("Error");
	isConnected = false;
	timerFn = setInterval(reconect, 3000);

}


text:
package jk_5.nailed.api.event.world;

import jk_5.nailed.api.event.PlatformEvent;
import jk_5.nailed.api.world.World;

/**
 * No description given
 *
 * @author jk-5
 */
public class WorldEvent extends PlatformEvent {

    private final World world;

    public WorldEvent(World world) {
        this.world = world;
    }

    public World getWorld() {
        return world;
    }
}


text:
package org.archive.tnh;

import java.io.*;
import java.util.*;

import org.apache.lucene.search.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.util.Version;

public class Search
{
  private static final DefaultQueryTranslator TRANSLATOR = new DefaultQueryTranslator( );

  public Map<String,Searcher> searchers;
  public FieldCache           siteCache;

  public Search( Searcher searcher )
  {
    if ( searcher == null ) throw new IllegalArgumentException( "searcher cannot be null" );

    Map<String,Searcher> searchers = Collections.singletonMap( "", searcher );
    this.init( searchers );
  }

  public Search( Map<String,Searcher> searchers )
  {
    if ( searchers == null ) throw new IllegalArgumentException( "searchers cannot be null" );
    if ( searchers.get( "" ) == null )
      {
        throw new IllegalArgumentException( "Searchers map does not contain a searcher for key \"\"" );
      }
    this.init( searchers );
  }

  private void init( Map<String,Searcher> searchers )
  {
    this.searchers = searchers;
    this.siteCache = new FieldCacheLucene( "site" );
  }

  public FieldCache getSiteCache( )
  {
    return this.siteCache;
  }

  public void setSiteCache( FieldCache siteCache )
  {
    if ( siteCache == null ) throw new IllegalArgumentException( "siteCache cannot be null" );
    this.siteCache = siteCache;
  }

  public boolean hasIndex( String name )
  {
    return this.searchers.containsKey( name );
  }

  public Set<String> getIndexNames( )
  {
    return this.searchers.keySet( );
  }

  public Result search( String query, int maxHits, int hitsPerSite )
    throws Exception
  {
    return this.search( this.searchers.get(""), query, maxHits, hitsPerSite );
  }

  public Result search( String indexName, String query, int maxHits, int hitsPerSite )
    throws Exception
  {
    Searcher searcher = this.searchers.get( indexName );

    if ( searcher == null )  throw new IllegalArgumentException( "Index not found: " + indexName );

    return this.search( searcher, query, maxHits, hitsPerSite );
  }

  public Result search( String indexNames[], String query, int maxHits, int hitsPerSite )
    throws Exception
  {
    Searcher s = buildMultiSearcher( indexNames );

    return this.search( s, query, maxHits, hitsPerSite );
  }

  public Result search( String indexNames[], Query query, int maxHits, int hitsPerSite )
    throws Exception
  {
    Searcher s = buildMultiSearcher( indexNames );

    return this.search( s, query, maxHits, hitsPerSite );
  }

  public Result search( Searcher searcher, String query, int maxHits, int hitsPerSite )
    throws Exception
  {
    Query q = TRANSLATOR.translate( query );

    return this.search( searcher, q, maxHits, hitsPerSite );
  }

  public Result search( Searcher searcher, Query query, int maxHits, int hitsPerSite )
    throws Exception
  {
    if ( searcher == null ) throw new IllegalArgumentException( "searcher cannot be null" );
    if ( query    == null ) throw new IllegalArgumentException( "query cannot be null" );
    if ( maxHits  <= 0    ) throw new IllegalArgumentException( "maxHits must be > 0" );
    if ( hitsPerSite < 0  ) throw new IllegalArgumentException( "hitsPerSite must be >= 0" );

    CollapsingCollector collector = new CollapsingCollector( this.siteCache, maxHits, hitsPerSite );

    searcher.search( query, collector );

    Result result = new Result( );
    result.searcher  = searcher;
    result.numRawHits= collector.getNumUncollapsedHits( );
    result.hits      = collector.getHits( );

    return result;
  }

  public MultiSearcher buildMultiSearcher( String indexNames[] )
    throws IOException
  {
    if ( indexNames == null || indexNames.length == 0 ) throw new IllegalArgumentException( "At least one indexName must be specified" );

    Searchable[] searchables = new Searchable[indexNames.length];
    for ( int i = 0 ; i < indexNames.length ; i++ )
      {
        searchables[i] = this.searchers.get( indexNames[i] );
        if ( searchables[i] == null ) throw new IllegalArgumentException( "Index not found: " + indexNames[i] );
      }

    MultiSearcher searcher = new MultiSearcher( searchables );

    return searcher;
  }

  /**
   * Given a searcher and a docId, find the corresponding name of the
   * corresponding index in the searchers map.  Returns the name of
   * the index, or null if not found.
   */
  public String resolveIndexName( Searchable searcher, int docId )
  {
    if ( searcher instanceof MultiSearcher )
      {
        MultiSearcher ms = (MultiSearcher) searcher;

        Searchable[] subsearchers = ms.getSearchables();

        searcher = subsearchers[ms.subSearcher( docId )];

        return resolveIndexName( searcher, docId );
      }
    if ( searcher instanceof IndexSearcher )
      {
        for ( Map.Entry<String,Searcher> entry : this.searchers.entrySet() )
          {
            // System.err.println( "Considering " + entry.getKey() + " (" + entry.getValue() + " ) for result.searcher: " + searcher );

            if ( entry.getValue() == searcher )
              {
                // System.err.println( "Result " + docId + " from searcher " + entry.getKey() );

                return entry.getKey( );
              }
          }

        // Didn't find the IndexSearcher.
        return null;
      }
    else
      {
        throw new RuntimeException( "Unknown searcher type: " + searcher );
      }
  }

  public static class Result
  {
    public Searcher searcher;
    public int      numRawHits;
    public Hit[]    hits;
  }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_class_44.cpp
Label Definition File: CWE415_Double_Free__new_delete.label.xml
Template File: sources-sinks-44.tmpl.cpp
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using new and Deallocae data using delete
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using delete
 * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE415_Double_Free__new_delete_class_44
{

#ifndef OMITBAD

static void badSink(TwoIntsClass * data)
{
    /* POTENTIAL FLAW: Possibly deleting memory twice */
    delete data;
}

void bad()
{
    TwoIntsClass * data;
    /* define a function pointer */
    void (*funcPtr) (TwoIntsClass *) = badSink;
    /* Initialize data */
    data = NULL;
    data = new TwoIntsClass;
    /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */
    delete data;
    /* use the function pointer */
    funcPtr(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(TwoIntsClass * data)
{
    /* POTENTIAL FLAW: Possibly deleting memory twice */
    delete data;
}

static void goodG2B()
{
    TwoIntsClass * data;
    void (*funcPtr) (TwoIntsClass *) = goodG2BSink;
    /* Initialize data */
    data = NULL;
    data = new TwoIntsClass;
    /* FIX: Do NOT delete data in the source - the bad sink deletes data */
    funcPtr(data);
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink(TwoIntsClass * data)
{
    /* do nothing */
    /* FIX: Don't attempt to delete the memory */
    ; /* empty statement needed for some flow variants */
}

static void goodB2G()
{
    TwoIntsClass * data;
    void (*funcPtr) (TwoIntsClass *) = goodB2GSink;
    /* Initialize data */
    data = NULL;
    data = new TwoIntsClass;
    /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */
    delete data;
    funcPtr(data);
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE415_Double_Free__new_delete_class_44; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package com.troy.xifan.http.request;

/**
 * Created by chenlongfei on 2016/12/29.
 */

public class HttpBodyParams {
}


text:
@interface CellModel : NSObject

@property (nonatomic, copy) NSString *string;

@property (nonatomic, strong) UIColor *color;

@end


text:
<!DOCTYPE html>

    <title>VideoResource Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

 Docs (100% documented)

         Reference

        VideoResource Class Reference

            Classes

                AccessoryResource

                CharacterResource

                CompanyResource

                ConceptResource

                FranchiseResource

                GameReleaseResource

                GameResource

                GenreResource

                LocationResource

                ObjectResource

                PersonResource

                PlatformResource

                StaffReviewResource

                SwiftBomb

                VideoResource

            Enums

                ComingUpItemType

                Gender

                ResourceResponseError

                ResourceType

                SwiftBombRequestError

                SwiftBombRequestResult

            Protocols

                Resource

                ResourceExtendedInfo

                SwiftBombNetworkingDelegate

            Structs

                CharacterExtendedInfo

                ComingUpSchedule

                ComingUpScheduleItem

                CompanyExtendedInfo

                ConceptExtendedInfo

                FranchiseExtendedInfo

                GameExtendedInfo

                GameReleaseExtendedInfo

                ImageURLs

                ObjectExtendedInfo

                PaginatedResults

                PersonExtendedInfo

                SearchResults

                SortDefinition

                – SortDirection

                SwiftBombConfig

                – LoggingLevel

                UnusedExtendedInfo

                VideoURLs

            Typealiases

                PaginationDefinition

                ResourceSummary

VideoResource

final public class VideoResource: ResourceUpdating

A class representing a Video on the Giant Bomb database. This includes quick looks and other Giant Bomb-created content as well as trailers for games amongst others.

To retrieve extended info for a video, call fetchExtendedInfo(_:) upon it.

                    resourceType

The resource type.

Declaration

Swift

public let resourceType = ResourceType.video

                    api_detail_url

URL pointing to the video detail resource.

Declaration

Swift

public fileprivate(set) var api_detail_url: URL?

                    deck

Brief summary of the video.

Declaration

Swift

public fileprivate(set) var deck: String?

                    id

Unique ID of the video.

Declaration

Swift

public let id: Int?

                    length_seconds

Length (in seconds) of the video.

Declaration

Swift

public fileprivate(set) var length_seconds: Int?

                    name

Name of the video.

Declaration

Swift

public fileprivate(set) var name: String?

                    publish_date

Date the video was published on Giant Bomb.

Declaration

Swift

public fileprivate(set) var publish_date: Date?

                    site_detail_url

URL pointing to the video on Giant Bomb.

Declaration

Swift

public fileprivate(set) var site_detail_url: URL?

                    user

Author of the video.

Declaration

Swift

public fileprivate(set) var user: String?

                    video_type

Video category.

Declaration

Swift

public fileprivate(set) var video_type: String?

                    youtube_id

Youtube ID for the video.

Declaration

Swift

public fileprivate(set) var youtube_id: String?

                    url

The video’s filename.

Declaration

Swift

public fileprivate(set) var url: String?

                    image

Container for the video’s image.

Declaration

Swift

public fileprivate(set) var image: ImageURLs?

                    urls

Container for the video’s URLs.

Declaration

Swift

public fileprivate(set) var urls: VideoURLs?

                    extendedInfo

Extended info. Unused for this resource type.

Declaration

Swift

public var extendedInfo: UnusedExtendedInfo?

                    init(json:)

Used to create a VideoResource from JSON.

Declaration

Swift

public init(json: [String : AnyObject])

                    prettyDescription

Pretty description of the video.

Declaration

Swift

public var prettyDescription: String

                    fetchExtendedInfo(_:completion:)

Fetches extended info for this video. Also re-populates base data in the case where this object is a stub from another parent resource.

Declaration

Swift

public func fetchExtendedInfo(_ fields: [String]? = nil, completion: @escaping (_ error: SwiftBombRequestError?) -> Void)

Parameters

                                fields

An optional array of fields to return in the response. See the available options at http://www.giantbomb.com/api/documentation#toc-0-44. Pass nil to return everything.

                                completion

A closure containing an optional SwiftBombRequestError if the request failed.

© 2016 . All rights reserved. (Last updated: 2016-11-05)

Generated by jazzy ♪♫ v0.7.2, a Realm project.


text:
package ec.vector;

import ec.*;
import ec.util.*;
import java.io.*;

/*
 * GeneVectorIndividual.java
 * Created: Thu Mar 22 13:13:20 EST 2001
 */

/**
 * GeneVectorIndividual is a VectorIndividual whose genome is an array of VectorGenes.
 * The default mutation method calls the mutate() method on each gene independently
 * with <tt>species.mutationProbability</tt>.  Initialization calls reset(), which
 * should call reset() on each gene.  Do not expect that the genes will actually
 * exist during initialization -- see the default implementation of reset() as an example
 * for how to handle this.
 *

 *
From ec.Individual:
 *
 *
In addition to serialization for checkpointing, Individuals may read and write themselves to streams in three ways.
 *
 *

 *
writeIndividual(...,DataOutput)/readIndividual(...,DataInput)   This method
 * transmits or receives an individual in binary.  It is the most efficient approach to sending
 * individuals over networks, etc.  These methods write the evaluated flag and the fitness, then
 * call readGenotype/writeGenotype, which you must implement to write those parts of your
 * Individual special to your functions-- the default versions of readGenotype/writeGenotype throw errors.
 * You don't need to implement them if you don't plan on using read/writeIndividual.
 *
 *
printIndividual(...,PrintWriter)/readIndividual(...,LineNumberReader)   This
 * approach transmits or receives an indivdual in text encoded such that the individual is largely readable
 * by humans but can be read back in 100% by ECJ as well.  To do this, these methods will encode numbers
 * using the <tt>ec.util.Code</tt> class.  These methods are mostly used to write out populations to
 * files for inspection, slight modification, then reading back in later on.  readIndividual reads
 * in the fitness and the evaluation flag, then calls parseGenotype to read in the remaining individual.
 * You are responsible for implementing parseGenotype: the Code class is there to help you.
 * printIndividual writes out the fitness and evaluation flag, then calls genotypeToString
 * and printlns the resultant string. You are responsible for implementing the genotypeToString method in such
 * a way that parseGenotype can read back in the individual println'd with genotypeToString.  The default form
 * of genotypeToString simply calls toString, which you may override instead if you like.  The default
 * form of parseGenotype throws an error.  You are not required to implement these methods, but without
 * them you will not be able to write individuals to files in a simultaneously computer- and human-readable fashion.
 *
 *
printIndividualForHumans(...,PrintWriter)   This
 * approach prints an individual in a fashion intended for human consumption only.
 * printIndividualForHumans writes out the fitness and evaluation flag, then calls genotypeToStringForHumans
 * and printlns the resultant string. You are responsible for implementing the genotypeToStringForHumans method.
 * The default form of genotypeToStringForHumans simply calls toString, which you may override instead if you like
 * (though note that genotypeToString's default also calls toString).  You should handle one of these methods properly
 * to ensure individuals can be printed by ECJ.
 *

 *
In general, the various readers and writers do three things: they tell the Fitness to read/write itself,
 * they read/write the evaluated flag, and they read/write the gene array.  If you add instance variables to
 * a VectorIndividual or subclass, you'll need to read/write those variables as well.

Default Base

 vector.gene-vect-ind

 * @author Sean Luke
 * @version 1.0
 */

public class GeneVectorIndividual extends VectorIndividual
    {
    public static final String P_GENEVECTORINDIVIDUAL = "gene-vect-ind";
    public VectorGene[] genome;

    public Parameter defaultBase()
        {
        return VectorDefaults.base().push(P_GENEVECTORINDIVIDUAL);
        }

    public Object clone()
        {
        GeneVectorIndividual myobj = (GeneVectorIndividual) (super.clone());

        // must clone the genome
        myobj.genome = (VectorGene[])(genome.clone());
        for(int x=0;x<genome.length;x++)
            myobj.genome[x] = (VectorGene)(genome[x].clone());

        return myobj;
        }

    public void setup(final EvolutionState state, final Parameter base)
        {
        super.setup(state,base);  // actually unnecessary (Individual.setup() is empty)

        // since VectorSpecies set its constraint values BEFORE it called
        // super.setup(...) [which in turn called our setup(...)], we know that
        // stuff like genomeSize has already been set...

        Parameter def = defaultBase();

        if (!(species instanceof GeneVectorSpecies))
            state.output.fatal("GeneVectorIndividual requires a GeneVectorSpecies", base, def);
        GeneVectorSpecies s = (GeneVectorSpecies) species;

        // note that genome isn't initialized with any genes yet -- they're all null.
        // reset() needs
        genome = new VectorGene[s.genomeSize];
        reset(state,0);
        }

    public void defaultCrossover(EvolutionState state, int thread, VectorIndividual ind)
        {
        GeneVectorSpecies s = (GeneVectorSpecies) species;
        GeneVectorIndividual i = (GeneVectorIndividual) ind;
        VectorGene tmp;
        int point;

        if (genome.length != i.genome.length)
            state.output.fatal("Genome lengths are not the same for fixed-length vector crossover");
        switch(s.crossoverType)
            {
            case VectorSpecies.C_ONE_POINT:
                point = state.random[thread].nextInt((genome.length / s.chunksize)+1);
                for(int x=0;x<point*s.chunksize;x++)
                    {
                    tmp = i.genome[x];
                    i.genome[x] = genome[x];
                    genome[x] = tmp;
                    }
                break;
            case VectorSpecies.C_TWO_POINT:
                int point0 = state.random[thread].nextInt((genome.length / s.chunksize)+1);
                point = state.random[thread].nextInt((genome.length / s.chunksize)+1);
                if (point0 > point) { int p = point0; point0 = point; point = p; }
                for(int x=point0*s.chunksize;x<point*s.chunksize;x++)
                    {
                    tmp = i.genome[x];
                    i.genome[x] = genome[x];
                    genome[x] = tmp;
                    }
                break;
            case VectorSpecies.C_ANY_POINT:
                for(int x=0;x<genome.length/s.chunksize;x++)
                    if (state.random[thread].nextBoolean(s.crossoverProbability))
                        for(int y=x*s.chunksize;y<(x+1)*s.chunksize;y++)
                            {
                            tmp = i.genome[y];
                            i.genome[y] = genome[y];
                            genome[y] = tmp;
                            }
                break;
            }
        }

    /** Splits the genome into n pieces, according to points, which *must* be sorted.
        pieces.length must be 1 + points.length */
    public void split(int[] points, Object[] pieces)
        {
        int point0, point1;
        point0 = 0; point1 = points[0];
        for(int x=0;x<pieces.length;x++)
            {
            pieces[x] = new VectorGene[point1-point0];
            System.arraycopy(genome,point0,pieces[x],0,point1-point0);
            point0 = point1;
            if (x >=pieces.length-2)
                point1 = genome.length;
            else point1 = points[x+1];
            }
        }

    /** Joins the n pieces and sets the genome to their concatenation.*/
    public void join(Object[] pieces)
        {
        int sum=0;
        for(int x=0;x<pieces.length;x++)
            sum += ((VectorGene[])(pieces[x])).length;

        int runningsum = 0;
        VectorGene[] newgenome = new VectorGene[sum];
        for(int x=0;x<pieces.length;x++)
            {
            System.arraycopy(pieces[x], 0, newgenome, runningsum, ((VectorGene[])(pieces[x])).length);
            runningsum += ((VectorGene[])(pieces[x])).length;
            }
        // set genome
        genome = newgenome;
        }

    /** Destructively mutates the individual in some default manner.  The default form
        simply randomizes genes to a uniform distribution from the min and max of the gene values. */
    public void defaultMutate(EvolutionState state, int thread)
        {
        GeneVectorSpecies s = (GeneVectorSpecies) species;
        if (s.mutationProbability>0.0)
            for(int x=0;x<genome.length;x++)
                if (state.random[thread].nextBoolean(s.mutationProbability))
                    genome[x].mutate(state,thread);
        }

    /** Initializes the individual by calling reset(...) on each gene. */
    public void reset(EvolutionState state, int thread)
        {
        GeneVectorSpecies s = (GeneVectorSpecies) species;

        for(int x=0;x<genome.length;x++)
            {
            // first create the gene if it doesn't exist
            if (genome[x]==null) genome[x] = (VectorGene)(s.genePrototype.clone());
            // now reset it
            genome[x].reset(state,thread);
            }

        }

    public int hashCode()
        {
        // stolen from GPIndividual.  It's a decent algorithm.
        int hash = this.getClass().hashCode();

        for(int x=0;x<genome.length;x++)
            hash = ( hash << 1 | hash >>> 31 ) ^ genome[x].hashCode();

        return hash;
        }

    public String genotypeToStringForHumans()
        {
        StringBuffer s = new StringBuffer();
        for( int i = 0 ; i < genome.length ; i++ )
            { s.append(" "); s.append(genome[i].printGeneToStringForHumans()); }
        return s.toString();
        }

    public String genotypeToString()
        {
        StringBuffer s = new StringBuffer();
        for( int i = 0 ; i < genome.length ; i++ )
            { s.append(" "); s.append(genome[i].printGeneToString()); }
        return s.toString();
        }

    protected void parseGenotype(final EvolutionState state,
        final LineNumberReader reader) throws IOException
        {
        // read in the next line.  The first item is the number of genes
        String s = reader.readLine();
        DecodeReturn d = new DecodeReturn(s);
        Code.decode( d );
        int lll = (int)(d.l);

        genome = new VectorGene[ lll ];

        GeneVectorSpecies _species = (GeneVectorSpecies) species;
        for( int i = 0 ; i < genome.length ; i++ )
            {
            genome[i] = (VectorGene)(_species.genePrototype.clone());
            genome[i].readGene(state,reader);
            }
        }

    public boolean equals(Object ind)
        {
        if (!(this.getClass().equals(ind.getClass()))) return false;
        GeneVectorIndividual i = (GeneVectorIndividual)ind;
        if( genome.length != i.genome.length )
            return false;
        for( int j = 0 ; j < genome.length ; j++ )
            if( !(genome[j].equals(i.genome[j])))
                return false;
        return true;
        }

    public Object getGenome()
        { return genome; }
    public void setGenome(Object gen)
        { genome = (VectorGene[]) gen; }
    public int genomeLength()
        { return genome.length; }

    // clone all the genes
    public void cloneGenes(Object piece)
        {
        VectorGene[] genes = (VectorGene[]) piece;
        for(int i = 0 ; i < genes.length; i++)
            {
            if (genes[i] != null) genes[i] = (VectorGene)(genes[i].clone());
            }
        }

    public void writeGenotype(final EvolutionState state,
        final DataOutput dataOutput) throws IOException
        {
        dataOutput.writeInt(genome.length);
        for(int x=0;x<genome.length;x++)
            genome[x].writeGene(state,dataOutput);
        }

    public void setGenomeLength(int len)
        {
        GeneVectorSpecies s = (GeneVectorSpecies) species;
        VectorGene[] newGenome = new VectorGene[len];
        System.arraycopy(genome, 0, newGenome, 0,
            genome.length < newGenome.length ? genome.length : newGenome.length);
        for(int x=genome.length; x< newGenome.length; x++)
            if (genome[x]==null) genome[x] = (VectorGene)(s.genePrototype.clone());  // not reset
        genome = newGenome;
        }

    public void readGenotype(final EvolutionState state,
        final DataInput dataInput) throws IOException
        {
        int len = dataInput.readInt();
        if (genome==null || genome.length != len)
            genome = new VectorGene[len];
        GeneVectorSpecies _species = (GeneVectorSpecies) species;

        for(int x=0;x<genome.length;x++)
            {
            genome[x] = (VectorGene)(_species.genePrototype.clone());
            genome[x].readGene(state,dataInput);
            }
        }

    }


text:
package main

import (
	"bufio"
	"fmt"
	"os"
	"testing"
)

func TestParseFile(t *testing.T) {
	numberOfLines := 100
	// Set up a file
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Encountered an error while getting the current directory to test ParseFile(): %q", err)
	}
	path := pwd + "\\TestParseFile.in"
	outPath := pwd + "\\TestParseFile.out"
	file, err := os.Create(path)
	if err != nil {
		t.Errorf("Encountered an error while creating file to test ParseFile() for path %q. Error: %q", path, err)
	}
	writer := bufio.NewWriter(file)
	for i := 0; i < numberOfLines; i++ {
		if i%2 == 0 {
			fmt.Fprintln(writer, "Talk about beating a dead horse.")
		} else {
			fmt.Fprintln(writer, "I feel sort of loopy...")
		}
		writer.Flush()
	}
	file.Close()
	filters := map[string][]int{"dead": []int{21, 50}}
	ParseFile(path, outPath, filters, 0, 0)
	file, err = os.Open(outPath)
	if err != nil {
		t.Errorf("Encountered an error while opening file to test ParseFile() for path %q. Error: %q", outPath, err)
	}
	scanner := bufio.NewScanner(file)
	outputLineCount := 0
	for scanner.Scan() {
		outputLineCount++
	}
	if outputLineCount != (numberOfLines / 2) {
		t.Errorf("Expected %d lines in output file, but found %d lines.", (numberOfLines / 2), outputLineCount)
	}
	file.Close()
	os.Remove(path)
	os.Remove(outPath)
}

func TestParseLine(t *testing.T) {
	cases := []struct {
		line     string
		filters  map[string][]int
		expected bool
	}{
		// Test edges of startIndex and length filter values
		{"123456789", map[string][]int{"12": []int{0, 10}}, true},
		{"123456789", map[string][]int{"12": []int{0, 9}}, true},
		{"123456789", map[string][]int{"1": []int{0, 2}}, true},
		{"123456789", map[string][]int{"2": []int{0, 2}}, true},
		{"123456789", map[string][]int{"2": []int{0}}, true},
		// Test line shorter than startIndex
		{"abcde", map[string][]int{"abc": []int{9000, 2}}, false},
		// Test empty filter value
		{"123456789", map[string][]int{"": []int{0, 1}}, true},
		// Test unmatched filter value
		{"abcdefg1234567", map[string][]int{"value": []int{0, 1}}, false},
		// Test filter with no endIndex value
		{"SearchEverythingFromStartIndexOn", map[string][]int{"Everything": []int{0}}, true},
		{"SearchEverythingFromStartIndexOn", map[string][]int{"Everything": []int{6}}, true},
		{"SearchEverythingFromStartIndexOn", map[string][]int{"Everything": []int{15}}, false},
	}
	for _, c := range cases {
		got := ParseLine(c.line, c.filters)
		if got != c.expected {
			t.Errorf("ReadLine(%q, %+v) == %t, expected %t", c.line, c.filters, got, c.expected)
		}
	}
}

func BenchmarkParseLine(b *testing.B) {
	// Perform setup
	line := "SearchTheWholeString"
	filter := map[string][]int{"Str": []int{0}}
	// Reset the timer
	b.ResetTimer()
	// Run benchmark
	for i := 0; i < b.N; i++ {
		ParseLine(line, filter)
	}
}

func BenchmarkParseLineParallel(b *testing.B) {
	// Perform setup
	line := "SearchTheWholeString"
	filter := map[string][]int{"Str": []int{0}}
	// Reset the timer
	b.ResetTimer()
	// Run benchmark
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			ParseLine(line, filter)
		}
	})
}


text:
// Copyright (c) Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Microsoft.Xbox.Music.Platform.Contract.DataModel
{
    public interface IPaginatedList<out T>
    {
        IEnumerable<T> ReadOnlyItems { get; }
        string ContinuationToken { get; set; }
        int TotalItemCount { get; set; }
    }

    [DataContract(Namespace = Constants.Xmlns)]
    public class PaginatedList<T> : IPaginatedList<T>
    {
        [DataMember(EmitDefaultValue = false)]
        public List<T> Items { get; set; }

        public IEnumerable<T> ReadOnlyItems { get { return Items; } }

        [DataMember(EmitDefaultValue = false)]
        public string ContinuationToken { get; set; }

        /// <summary>
        /// An estimate count of the total number of items available in the list
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public int TotalItemCount { get; set; }

        public PaginatedList()
        {
            Items = new List<T>();
        }
    }
}


text:
require "spec_helper"

describe "routing to repositories" do
  it "routes / to repositories#index" do
    expect(get: "/").to route_to(
      controller: "repositories",
      action: "index",
    )
  end

  it "routes /:owner_name to repositories#index for owner_name" do
    expect(get: "/henrikhodne").to route_to(
      controller: "repositories",
      action: "index",
      owner_name: "henrikhodne",
    )
  end

  it "routes /:owner_name/:name to repositories#show for repository" do
    expect(get: "/henrikhodne/travis-lite").to route_to(
      controller: "repositories",
      action: "show",
      owner_name: "henrikhodne",
      name: "travis-lite",
    )
  end

  it "doesn't route /javascripts/application.js" do
    expect(get: "/javascripts/application.js").to_not be_routable
  end
end


text:
#ifndef DL_ASSERT_HEADER
#define DL_ASSERT_HEADER

#include "DL_Debug.h"
#include <crtdefs.h>

#ifdef  __cplusplus
extern "C" {
#endif

_CRTIMP void __cdecl _wassert(_In_z_ const wchar_t * _Message, _In_z_ const wchar_t *_File, _In_ unsigned _Line);

#ifdef  __cplusplus
}
#endif

#ifdef assert
#undef assert
#endif
#ifdef NDEBUG
#define assert(x) ((void)0)
#else

#define assert(_Expression) \
  if (! (_Expression)) \
  { \
	DL_ASSERT(#_Expression);\
  }
#endif

/*

#undef  assert

#ifdef  NDEBUG

#define assert(_Expression)     ((void)0)

#else

#ifdef  __cplusplus
extern "C" {
#endif

_CRTIMP void __cdecl _wassert(_In_z_ const wchar_t * _Message, _In_z_ const wchar_t *_File, _In_ unsigned _Line);

#ifdef  __cplusplus
}
#endif

#define assert(_Expression) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), __LINE__), 0) )

#endif  /* NDEBUG */

#endif


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \file DTK_FieldTraits.hpp
 * \author Stuart R. Slattery
 * \brief Traits declaration for field types.
 */
//---------------------------------------------------------------------------//

#ifndef DTK_FIELDTRAITS_HPP
#define DTK_FIELDTRAITS_HPP

#include <iterator>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
 * \brief Dummy struct. If a type does not create a specialization this will
 * not compile.
 */
//---------------------------------------------------------------------------//
template <typename UndefinedFieldType>
struct UndefinedFieldTraits
{
    static inline UndefinedFieldType notDefined()
    {
        return UndefinedFieldType::this_type_is_missing_a_specialization();
    }
};

//---------------------------------------------------------------------------//
/*!
 * \class FieldTraits
 * \brief Field traits definitions.

 In the most general sense, a field refers to the degrees of freedom computed
 by a physics code or the responses derived from those degrees of freedom that
 have been discretized across the domain. The field is implicitly bound to the
 geometric domain through the degrees of freedom and their association with a
 mesh or other geometric components. In a physics simulation, examples of
 degrees of freedom include pressure and velocity distributions and examples
 of computed reponses include heat flux or reaction rates. In order to access
 DTK field services, a subset of information needed to describe the field is
 required. A field has a dimension of arbitrary size. As examples, for scalar
 fields this dimension is 1, for 3-vectors (such as the velocity example above
 in a 3 dimensional computation) the dimension is 3, and for a 3x3 tensor the
 dimension is 9.  All local instances of the field must have the same
 dimension. A field can have an arbitrary number of local degrees of freedom
 and this size can differ from local domain to local domain. No knowledge of
 the global field decomposition is required, however, it must exist on a
 single communicator.

 These traits correlate to the basic concept of a field within DTK. A field
 can contain anything in an array, but it must store its objects in contiguous
 memory that is blocked by dimension and accessible by random access
 iterators. The blocked data storage is arranged as follows:

 The data will have D dimensions \f$ \Big[ f_0, f_1, f_2, ..., f_D \big] \f$

 Each local instance of the field will have N elements in each dimension,
 blocked such that the data layout is: \f$ \Big[ f^0_0, f^1_0, f^2_0, ...,
 f^N_0, f^0_1, f^1_1, f^2_1, ..., f^N_1, ... , f^0_D, f^1_D, f^2_D, ..., f^N_D
 \Big] \f$

 */
//---------------------------------------------------------------------------//
template <typename FieldType>
class FieldTraits
{
  public:
    //! Typedef for field type.
    typedef FieldType field_type;

    //! Typedef for value type.
    typedef typename FieldType::value_type value_type;

    //! Typedef for size type.
    typedef typename FieldType::size_type size_type;

    //{@
    //! Typedefs for field value random access iterators.
    typedef typename std::iterator<std::random_access_iterator_tag, value_type>
        iterator;

    typedef typename std::iterator<std::random_access_iterator_tag,
                                   const value_type>
        const_iterator;
    //@}

    /*!
     * \brief Returns the dimensionality of the field ( i.e. 1 for a scalar, 3
     * for a 3 vector, 9 for a 3x3 tensor, etc. ).
     */
    static inline int dim( const FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }

    /*!
     * \brief Returns the total number of elements in the field.
     */
    static inline size_type size( const FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }

    /*!
     * \brief Returns if the field is empty.
     */
    static inline bool empty( const FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }

    //@{
    /*!
     * \brief Returns the iterator to the beginning of the field. The data is
     * required to be blocked by dimensions.
     */
    static inline iterator begin( FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }

    static inline const_iterator begin( const FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }
    //@}

    //@{
    /*!
     * \brief Returns the iterator to the end of the field. The data is
     * required to be blocked by dimensions.
     */
    static inline iterator end( FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }

    static inline const_iterator end( const FieldType &field )
    {
        return UndefinedFieldTraits<FieldType>::notDefined();
    }
    //@}
};

//---------------------------------------------------------------------------//

} // end namespace DataTransferKit

#endif // end DTK_FIELDTRAITS_HPP

//---------------------------------------------------------------------------//
// end DTK_FieldTraits.hpp
//---------------------------------------------------------------------------//


text:
> **Tags:**
> - [New Feature]
> - [Bug Fix]
> - [Breaking Change]
> - [Documentation]
> - [Internal]
> - [Polish]

**Note**: Gaps between patch versions are faulty/broken releases.

## v0.6.2

- **Bug Fix**
  + handle weird travis error

## v0.6.1

- **New Feature**
  + add error stack trace
- **Bug Fix**
  + handle falsy child

## v0.6

- **Breaking Change**
  + support React v0.14, fix #7

## v0.5

- **Breaking Change** (maybe)
  + treat falsy children same as nully children (thanks @giogonzo)

## v0.4

- **New Feature**
  + Return a generic tag error when an exception is thrown
- **Breaking Change**
  + Compact children for DOM nodes

## v0.3

- **Breaking Change**
  + Drop support for React v0.12
- **Internal**
  + Refactoring
  + Remove tcomb dependency

## v0.2.4

- **New Feature**
  + Support component extending React.Component #4

## v0.2.3

- **Internal**
  + update to tcomb v1.0, fix #2
  + upgrade to React v0.13, fix #3

## v0.2.2

- **Internal**
  - update to tcomb v0.4
  - add keyword react-component for discoverability


text:
<?php

namespace Gmo\Common\Csv;

use Psr\Http\Message\StreamInterface;

class CsvStreamWriter implements CsvWriterInterface
{
    use CsvControlTrait;

    /** @var StreamInterface */
    private $stream;

    /**
     * Constructor.
     *
     * @param StreamInterface $stream The stream to write to
     */
    public function __construct(StreamInterface $stream)
    {
        $this->stream = $stream;
    }

    /**
     * Write a list of rows to the stream.
     *
     * @param iterable $rows
     */
    public function writeRows(iterable $rows): void
    {
        foreach ($rows as $row) {
            $this->writeRow($row);
        }
    }

    /**
     * Write a row to the stream.
     *
     * @param iterable $row
     */
    public function writeRow(iterable $row): void
    {
        $str = Csv::dump($row, $this->delimiter, $this->enclosure, $this->escape);

        try {
            $written = $this->stream->write($str);
        } catch (\Throwable $e) {
            throw new \RuntimeException('Failed to write CSV row.', 0, $e);
        }

        if (strlen($str) !== $written) {
            throw new \RuntimeException('Failed to write CSV row.');
        }
    }
}


text:
		<input type="radio" name="{{option.id}}"
			data-ng-value="item.key"
			data-ng-model="option.selected"
			data-ng-click="onOptionChanged(option, item)">


text:
Hey {{auth.github.displayName}} are you going to the cafe to:

        <form action="">
            <input type="radio" name="reason" value="Code (you got your Mac)">Code (you got your Mac)

            <input type="radio" name="reason" value="Talk (left the Mac home)">Talk (left the Mac home)

            <input type="radio" name="reason" value="Both">Both
        </form>

I like to talk/code about:

        <form action="">
            <input type="radio" name="job" value="Font-end">Front-end

            <input type="radio" name="job" value="Back-end">Back-end

            <input type="radio" name="job" value="Mobile">Mobile

             <input type="radio" name="job" value="Web Design">Web Design

        </form>


text:
rm -rf dist
mkdir dist
rsync -r --exclude /dist --exclude /local-server --exclude /deploy --exclude offline-bundle ./* ./dist/

# Offline bundle build.
cd offline-bundle && npm install && ./build.js
cd ..

# Compress offline package and put it in dist folder that will be deployed by s3_website.
# It will be available at /jsmol-offline.tar.gz.
tar -czf ./dist/jsmol-offline.tar.gz jsmol-offline


text:
import json
from nose.tools import raises
import responses
import requests
import unittest

import uinames
import uinames.models as models
import uinames.utils as utils

class APIFunctionality(unittest.TestCase):
    """
    This testcase tests the end-to-end functionality of the library, ensuring
    that the correct exceptions are thrown for erroneous inputs, and that
    the correct class instances are being returned for successful inputs.
    """

    def test_generate_random_identity(self):
        person = uinames.generate_random_identity()
        self.assertEqual(person.__class__, models.Person)

    def test_generate_random_identities(self):
        people = uinames.generate_random_identities()
        self.assertEqual(people.__class__, models.People)

    # amount parameter

    @raises(requests.exceptions.HTTPError)
    def test_amount_lower_out_of_bound(self):
        uinames.generate_random_identities(0)

    def test_amount_lower_bound(self):
        people = uinames.generate_random_identities(1)
        self.assertEqual(people.__class__, models.People)

    def test_amount_within_bounds(self):
        people = uinames.generate_random_identities(250)
        self.assertEqual(people.__class__, models.People)

    def test_amount_upper_bounds(self):
        people = uinames.generate_random_identities(500)
        self.assertEqual(people.__class__, models.People)

    @raises(requests.exceptions.HTTPError)
    def test_amount_upper_out_of_bound(self):
        uinames.generate_random_identities(501)

    # gender parameter

    def test_gender_male(self):
        person = uinames.generate_random_identities(gender="male")
        self.assertEqual(person.__class__, models.People)

    def test_gender_female(self):
        person = uinames.generate_random_identities(gender="female")
        self.assertEqual(person.__class__, models.People)

    @raises(requests.exceptions.HTTPError)
    def test_gender_invalid(self):
        uinames.generate_random_identities(gender="invalid_gender")

    # region parameter

    def test_region_valid(self):
        person = uinames.generate_random_identities(region="canada")
        self.assertEqual(person.__class__, models.People)

    @raises(requests.exceptions.HTTPError)
    def test_region_invalid(self):
        uinames.generate_random_identities(region="invalid-region")

    # minlen parameter

    def test_minlen_valid(self):
        person = uinames.generate_random_identities(minlen=10)
        self.assertEqual(person.__class__, models.People)

    # maxlen parameter

    def test_maxlen_valid(self):
        person = uinames.generate_random_identities(maxlen=10)
        self.assertEqual(person.__class__, models.People)

    # ext parameter

    def test_ext(self):
        person = uinames.generate_random_identities(ext=True)
        self.assertEqual(person.__class__, models.People)

class BasicWrapperFunctionality(unittest.TestCase):
    """
    This testcase tests the functionality of the generate_random_identity
    function.
    """

    @responses.activate
    def setUp(self):
        url = "https://uinames.com/api/"
        data = json.load(open("tests/fixtures/person.json"))
        response = responses.add(responses.GET, url, json=data, status=200,
                                 content_type="application/json")
        self.person = uinames.generate_random_identity()
        # basic assertions
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, url)

    def test_name(self):
        self.assertEqual(self.person.name, "Aaron")

    def test_surname(self):
        self.assertEqual(self.person.surname, "Carter")

    def test_gender(self):
        self.assertEqual(self.person.gender, "male")

    def test_region(self):
        self.assertEqual(self.person.region, "New Zealand")

    @raises(utils.PropertyUnavailable)
    def test_property_not_present(self):
        self.person.property_not_present

class AdvancedWrapperFunctionality(unittest.TestCase):
    """
    This testcase tests the functionality of the generate_random_identities
    function.
    """

    @responses.activate
    def setUp(self):
        url = "https://uinames.com/api/?amount=10&ext=True"
        data = json.load(open("tests/fixtures/people.json"))
        response = responses.add(responses.GET, url, json=data, status=200,
                                 content_type="application/json",
                                 match_querystring=True)
        self.people = uinames.generate_random_identities(10, ext=True)
        self.person = self.people.data[0]
        # basic assertions
        self.assertEqual(len(responses.calls), 1)

    def test_multiple_results(self):
        self.assertEqual(len(self.people.data), 10)

    def test_name(self):
        self.assertEqual(self.person.name, "Ronja")

    def test_surname(self):
        self.assertEqual(self.person.surname, "Bagge")

    def test_gender(self):
        self.assertEqual(self.person.gender, "female")

    def test_region(self):
        self.assertEqual(self.person.region, "Sweden")

    def test_age(self):
        self.assertEqual(self.person.age, 32)

    def test_title(self):
        self.assertEqual(self.person.title, "mrs")

    def test_phone(self):
        self.assertEqual(self.person.phone, "(656) 718 3112")

    def test_birthday(self):
        self.assertEqual(self.person.birthday, {"dmy": "24/01/1985",
                                                "mdy": "01/24/1985",
                                                "raw": 475431301})

    def test_email(self):
        self.assertEqual(self.person.email, "ronja-bagge@example.com")

    def test_password(self):
        self.assertEqual(self.person.password, "Bagge85_@")

    def test_credit_card(self):
        self.assertEqual(self.person.credit_card, {"expiration": "3/19",
                                                   "number": "2115-8343-4559-1249",
                                                   "pin": 2085, "security": 143})

    def test_photo(self):
        self.assertEqual(self.person.photo,
                         "https://uinames.com/api/photos/female/24.jpg")

    @raises(utils.PropertyUnavailable)
    def test_property_not_present(self):
        self.person.property_not_present


text:
// Copyright 2011-2016 Google LLC
//
// 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.

package com.google.security.zynamics.binnavi.ZyGraph.Settings;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.config.GraphSettingsConfigItem;
import com.google.security.zynamics.zylib.gui.zygraph.layouters.OrthogonalOrientation;
import com.google.security.zynamics.zylib.gui.zygraph.layouters.OrthogonalStyle;

/**
 * Contains graph settings for orthogonal layouts.
 */
public final class ZyGraphOrthogonalSettings {
  /**
   * Orientation of orthogonal layouting operations.
   */
  private OrthogonalOrientation m_orientation;

  /**
   * Style of hierarchical layouting operations.
   */
  private OrthogonalStyle m_style;

  /**
   * Minimum number of pixels between orthogonally layouted nodes.
   */
  private int m_mininmumNodeDistance;

  /**
   * Configuration file object that is synchronized with this settings class.
   */
  private final GraphSettingsConfigItem m_type;

  /**
   * Creates a new settings object backed by graph settings from the configuration file.
   *
   * @param type Graph settings from the configuration file.
   */
  public ZyGraphOrthogonalSettings(final GraphSettingsConfigItem type) {
    Preconditions.checkNotNull(type, "IE02026: Type argument can't be null");

    m_type = type;
  }

  /**
   * Creates a new settings type by copying the settings of another settings type.
   *
   * @param settings The settings type that provides the initial settings.
   */
  public ZyGraphOrthogonalSettings(final ZyGraphOrthogonalSettings settings) {
    m_type = null;

    m_mininmumNodeDistance = settings.getMinimumNodeDistance();
    m_orientation = settings.getOrientation();
    m_style = settings.getStyle();
  }

  /**
   * Converts the numerical value of a configuration file orthogonal orientation to an enumeration
   * value.
   *
   * @param type The configuration file settings type that provides the numerical value.
   *
   * @return The corresponding enumeration value or a default value if the value from the
   *         configuration file is invalid.
   */
  private static OrthogonalOrientation getOrthogonalOrientation(final GraphSettingsConfigItem type) {
    try {
      return OrthogonalOrientation.parseInt(type.getOrthogonalOrientation());
    } catch (final IllegalStateException e) {
      CUtilityFunctions.logException(e);

      return OrthogonalOrientation.VERTICAL;
    }
  }

  /**
   * Converts the numerical value of a configuration file orthogonal layout style to an enumeration
   * value.
   *
   * @param type The configuration file settings type that provides the numerical value.
   *
   * @return The corresponding enumeration value or a default value if the value from the
   *         configuration file is invalid.
   */
  private static OrthogonalStyle getOrthogonalStyle(final GraphSettingsConfigItem type) {
    try {
      return OrthogonalStyle.parseInt(type.getOrthogonalLayoutStyle());
    } catch (final IllegalStateException e) {
      CUtilityFunctions.logException(e);

      return OrthogonalStyle.NORMAL;
    }
  }

  /**
   * Returns the current minimum orthogonal node distance.
   *
   * @return The current minimum orthogonal node distance.
   */
  public int getMinimumNodeDistance() {
    return m_type == null ? m_mininmumNodeDistance : m_type.getOrthogonalMinimumNodeDistance();
  }

  /**
   * Returns the current orthogonal orientation.
   *
   * @return The current orthogonal orientation.
   */
  public OrthogonalOrientation getOrientation() {
    return m_type == null ? m_orientation : getOrthogonalOrientation(m_type);
  }

  /**
   * Returns the current orthogonal layout style.
   *
   * @return The current orthogonal layout style.
   */
  public OrthogonalStyle getStyle() {
    return m_type == null ? m_style : getOrthogonalStyle(m_type);
  }

  /**
   * Changes the current minimum orthogonal node distance setting.
   *
   * @param value The new value of the minimum orthogonal node distance setting.
   */
  public void setMinimumNodeDistance(final int value) {
    Preconditions.checkArgument(value >= 0, "IE00885: Distance argument must not be negative");

    if (value == getMinimumNodeDistance()) {
      return;
    }

    if (m_type == null) {
      m_mininmumNodeDistance = value;
    } else {
      m_type.setOrthogonalMinimumNodeDistance(value);
    }
  }

  /**
   * Changes the current orthogonal orientation setting.
   *
   * @param value The new value of the orthogonal orientation setting.
   */
  public void setOrientation(final OrthogonalOrientation value) {
    Preconditions.checkNotNull(value, "IE00888: Orientation argument must not be negative");

    if (value == getOrientation()) {
      return;
    }

    if (m_type == null) {
      m_orientation = value;
    } else {
      m_type.setOrthogonalOrientation(value.ordinal());
    }
  }

  /**
   * Changes the current orthogonal layout style setting.
   *
   * @param value The new value of the orthogonal layout style setting.
   */
  public void setStyle(final OrthogonalStyle value) {
    Preconditions.checkNotNull(value, "IE00887: Style argument must not be negative");

    if (value == getStyle()) {
      return;
    }

    if (m_type == null) {
      m_style = value;
    } else {
      m_type.setOrthogonalLayoutStyle(value.ordinal());
    }
  }
}


text:
@interface SPTScrollViewScrubberSample_TableViewController : UITableViewController

@end


text:
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
import sys
import logging

import ply.lex

logger = logging.getLogger(__name__)

class JsonPathLexerError(Exception):
    pass

class JsonPathLexer(object):
    '''
    A Lexical analyzer for JsonPath.
    '''

    def __init__(self, debug=False):
        self.debug = debug
        if self.__doc__ == None:
            raise JsonPathLexerError('Docstrings have been removed! By design of PLY, jsonpath-rw requires docstrings. You must not use PYTHONOPTIMIZE=2 or python -OO.')

    def tokenize(self, string):
        '''
        Maps a string to an iterator over tokens. In other words: [char] -> [token]
        '''

        new_lexer = ply.lex.lex(module=self, debug=self.debug, errorlog=logger)
        new_lexer.latest_newline = 0
        new_lexer.string_value = None
        new_lexer.input(string)

        while True:
            t = new_lexer.token()
            if t is None: break
            t.col = t.lexpos - new_lexer.latest_newline
            yield t

        if new_lexer.string_value is not None:
            raise JsonPathLexerError('Unexpected EOF in string literal or identifier')

    # ============== PLY Lexer specification ==================
    #
    # This probably should be private but:
    #   - the parser requires access to `tokens` (perhaps they should be defined in a third, shared dependency)
    #   - things like `literals` might be a legitimate part of the public interface.
    #
    # Anyhow, it is pythonic to give some rope to hang oneself with :-)

    literals = ['*', '.', '[', ']', '(', ')', '$', ',', ':', '|', '&']

    reserved_words = { 'where': 'WHERE' }

    tokens = ['DOUBLEDOT', 'NUMBER', 'ID', 'NAMED_OPERATOR'] + list(reserved_words.values())

    states = [ ('singlequote', 'exclusive'),
               ('doublequote', 'exclusive'),
               ('backquote', 'exclusive') ]

    # Normal lexing, rather easy
    t_DOUBLEDOT = r'\.\.'
    t_ignore = ' \t'

    def t_ID(self, t):
        r'[a-zA-Z_@][a-zA-Z0-9_@\-]*'
        t.type = self.reserved_words.get(t.value, 'ID')
        return t

    def t_NUMBER(self, t):
        r'-?\d+'
        t.value = int(t.value)
        return t

    # Single-quoted strings
    t_singlequote_ignore = ''
    def t_singlequote(self, t):
        r"'"
        t.lexer.string_start = t.lexer.lexpos
        t.lexer.string_value = ''
        t.lexer.push_state('singlequote')

    def t_singlequote_content(self, t):
        r"[^'\\]+"
        t.lexer.string_value += t.value

    def t_singlequote_escape(self, t):
        r'\\.'
        t.lexer.string_value += t.value[1]

    def t_singlequote_end(self, t):
        r"'"
        t.value = t.lexer.string_value
        t.type = 'ID'
        t.lexer.string_value = None
        t.lexer.pop_state()
        return t

    def t_singlequote_error(self, t):
        raise JsonPathLexerError('Error on line %s, col %s while lexing singlequoted field: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0]))

    # Double-quoted strings
    t_doublequote_ignore = ''
    def t_doublequote(self, t):
        r'"'
        t.lexer.string_start = t.lexer.lexpos
        t.lexer.string_value = ''
        t.lexer.push_state('doublequote')

    def t_doublequote_content(self, t):
        r'[^"\\]+'
        t.lexer.string_value += t.value

    def t_doublequote_escape(self, t):
        r'\\.'
        t.lexer.string_value += t.value[1]

    def t_doublequote_end(self, t):
        r'"'
        t.value = t.lexer.string_value
        t.type = 'ID'
        t.lexer.string_value = None
        t.lexer.pop_state()
        return t

    def t_doublequote_error(self, t):
        raise JsonPathLexerError('Error on line %s, col %s while lexing doublequoted field: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0]))

    # Back-quoted "magic" operators
    t_backquote_ignore = ''
    def t_backquote(self, t):
        r'`'
        t.lexer.string_start = t.lexer.lexpos
        t.lexer.string_value = ''
        t.lexer.push_state('backquote')

    def t_backquote_escape(self, t):
        r'\\.'
        t.lexer.string_value += t.value[1]

    def t_backquote_content(self, t):
        r"[^`\\]+"
        t.lexer.string_value += t.value

    def t_backquote_end(self, t):
        r'`'
        t.value = t.lexer.string_value
        t.type = 'NAMED_OPERATOR'
        t.lexer.string_value = None
        t.lexer.pop_state()
        return t

    def t_backquote_error(self, t):
        raise JsonPathLexerError('Error on line %s, col %s while lexing backquoted operator: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0]))

    # Counting lines, handling errors
    def t_newline(self, t):
        r'\n'
        t.lexer.lineno += 1
        t.lexer.latest_newline = t.lexpos

    def t_error(self, t):
        raise JsonPathLexerError('Error on line %s, col %s: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0]))

if __name__ == '__main__':
    logging.basicConfig()
    lexer = JsonPathLexer(debug=True)
    for token in lexer.tokenize(sys.stdin.read()):
        print('%-20s%s' % (token.value, token.type))


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class game.dataAccessLayer.AssetLicense</title>
<meta name="date" content="2015-06-08">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
game.dataAccessLayer.AssetLicense

Packages that use AssetLicense

Package
Description

game.dataAccessLayer

Uses of AssetLicense in game.dataAccessLayer

Fields in game.dataAccessLayer declared as AssetLicense

Modifier and Type
Field and Description

AssetLicense
TypedAssetDescriptor.License

Constructors in game.dataAccessLayer with parameters of type AssetLicense

Constructor and Description

TypedAssetDescriptor(java.lang.String assetName,
                    java.lang.String fileName,
                    TypedAssetDescriptor.AssetTypeEnum assetType,
                    AssetLicense license)

TypedAssetDescriptor(java.lang.String assetName,
                    java.lang.String fileName,
                    TypedAssetDescriptor.AssetTypeEnum assetType,
                    com.badlogic.gdx.assets.AssetLoaderParameters<T> params,
                    AssetLicense license)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
{% extends "base.html" %}

{% block first_column %}

Authorization Error

Permission Denied

Sorry. You are trying to access a web page without proper authorization.

                {% if user %}

You are currently logged in as {{ user.email }}, and this account doesn't have permission to access the information.

If you believe this is a mistake, try logging out and then
                    logging in again.

                {% else %}

You should try to log in with your Google ID if you feel you should have access.

                {% endif %}

After logging in with an authorized account, revisit the desired web page.

{% endblock %}


text:
using Newtonsoft.Json;
using Zencoder.HttpHelpers;

namespace Zencoder.Jobs
{
    /// <summary>
    ///     Implements the job details response.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class JobDetailsResponse : Response<JobDetailsResponse>
    {
        /// <summary>
        ///     Gets or sets the job returned with the response.
        /// </summary>
        [JsonProperty("job")]
        public Job Job { get; set; }
    }
}


text:
package org.jboss.weld.environment.servlet.test.injection.resource;

import static org.jboss.weld.environment.servlet.test.util.Deployments.baseDeployment;

import javax.inject.Inject;

import org.junit.Assert;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class ResourceInjectionTest {

    @Deployment
    public static WebArchive createTestArchive() {
        return baseDeployment().addClasses(ResourceInjectionTest.class, Dolphin.class);
    }

    @Inject
    private Dolphin dolphin;

    @Test
    public void testFieldResourceInjection() {
        Assert.assertEquals("bar", dolphin.getFieldResource());
    }

    @Test
    public void testMethodResourceInjection() {
        Assert.assertEquals("bar", dolphin.getMethodResource());
    }
}


text:
#import "CCActionInterval.h"
#import "CCActionInstant.h"
#import "CCGrid.h"

@class CCGridBase;

/** Base class for Grid actions */
@interface CCGridAction : CCActionInterval
{
	ccGridSize gridSize;
}

/** size of the grid */
@property (nonatomic,readwrite) ccGridSize gridSize;

/** creates the action with size and duration */
+(id) actionWithSize:(ccGridSize)size duration:(ccTime)d;
/** initializes the action with size and duration */
-(id) initWithSize:(ccGridSize)gridSize duration:(ccTime)d;
/** returns the grid */
-(CCGridBase *)grid;

@end

////////////////////////////////////////////////////////////

/** Base class for CCGrid3D actions.
 Grid3D actions can modify a non-tiled grid.
 */
@interface CCGrid3DAction : CCGridAction
{

}

/** returns the vertex than belongs to certain position in the grid */
-(ccVertex3F)vertex:(ccGridSize)pos;
/** returns the non-transformed vertex than belongs to certain position in the grid */
-(ccVertex3F)originalVertex:(ccGridSize)pos;
/** sets a new vertex to a certain position of the grid */
-(void)setVertex:(ccGridSize)pos vertex:(ccVertex3F)vertex;

@end

////////////////////////////////////////////////////////////

/** Base class for CCTiledGrid3D actions */
@interface CCTiledGrid3DAction : CCGridAction
{

}

/** returns the tile that belongs to a certain position of the grid */
-(ccQuad3)tile:(ccGridSize)pos;
/** returns the non-transformed tile that belongs to a certain position of the grid */
-(ccQuad3)originalTile:(ccGridSize)pos;
/** sets a new tile to a certain position of the grid */
-(void)setTile:(ccGridSize)pos coords:(ccQuad3)coords;

@end

////////////////////////////////////////////////////////////

/** CCAccelDeccelAmplitude action */
@interface CCAccelDeccelAmplitude : CCActionInterval
{
	float			rate;
	CCActionInterval *other;
}

/** amplitude rate */
@property (nonatomic,readwrite) float rate;

/** creates the action with an inner action that has the amplitude property, and a duration time */
+(id)actionWithAction:(CCAction*)action duration:(ccTime)d;
/** initializes the action with an inner action that has the amplitude property, and a duration time */
-(id)initWithAction:(CCAction*)action duration:(ccTime)d;

@end

////////////////////////////////////////////////////////////

/** CCAccelAmplitude action */
@interface CCAccelAmplitude : CCActionInterval
{
	float			rate;
	CCActionInterval *other;
}

/** amplitude rate */
@property (nonatomic,readwrite) float rate;

/** creates the action with an inner action that has the amplitude property, and a duration time */
+(id)actionWithAction:(CCAction*)action duration:(ccTime)d;
/** initializes the action with an inner action that has the amplitude property, and a duration time */
-(id)initWithAction:(CCAction*)action duration:(ccTime)d;

@end

////////////////////////////////////////////////////////////

/** CCDeccelAmplitude action */
@interface CCDeccelAmplitude : CCActionInterval
{
	float			rate;
	CCActionInterval *other;
}

/** amplitude rate */
@property (nonatomic,readwrite) float rate;

/** creates the action with an inner action that has the amplitude property, and a duration time */
+(id)actionWithAction:(CCAction*)action duration:(ccTime)d;
/** initializes the action with an inner action that has the amplitude property, and a duration time */
-(id)initWithAction:(CCAction*)action duration:(ccTime)d;

@end

////////////////////////////////////////////////////////////

/** CCStopGrid action.
 Don't call this action if another grid action is active.
 Call if you want to remove the the grid effect. Example:
 [Sequence actions:[Lens ...], [StopGrid action], nil];
 */
@interface CCStopGrid : CCActionInstant
{
}
@end

////////////////////////////////////////////////////////////

/** CCReuseGrid action */
@interface CCReuseGrid : CCActionInstant
{
	int t;
}
/** creates an action with the number of times that the current grid will be reused */
+(id) actionWithTimes: (int) times;
/** initializes an action with the number of times that the current grid will be reused */
-(id) initWithTimes: (int) times;
@end