text:
<!DOCTYPE html>
<title> Table Of Contents </title>

 [
   Tcllib Home
| Keyword Index
| Categories
| Modules
| Applications
 ]

Table Of Contents

tcllib

aes
Implementation of the AES block cipher

ascii85
ascii85-encode/decode binary data

asn
ASN.1 BER encoder/decoder

autoproxy
Automatic HTTP proxy usage and authentication

base32
base32 standard encoding

base32::core
Expanding basic base32 maps

base32::hex
base32 extended hex encoding

base64
base64-encode/decode binary data

bee
BitTorrent Serialization Format Encoder/Decoder

bench
bench - Processing benchmark suites

bench::in
bench::in - Reading benchmark results

bench::out::csv
bench::out::csv - Formatting benchmark results as CSV

bench::out::text
bench::out::text - Formatting benchmark results as human readable text

bench_intro
bench introduction

bench_lang_intro
bench language introduction

bench_lang_spec
bench language specification

bibtex
Parse bibtex files

blowfish
Implementation of the Blowfish block cipher

cache::async
Asynchronous in-memory cache

cksum
Calculate a cksum(1) compatible checksum

clay
A minimalist framework for large scale OO Projects

clock_iso8601
Parsing ISO 8601 dates/times

clock_rfc2822
Parsing RFC 2822 dates/times

cmdline
Procedures to process command lines and options.

comm
A remote communication facility for Tcl (8.5 and later)

comm_wire
The comm wire protocol

control
Procedures for control flow structures.

coroutine
Coroutine based event and IO handling

coroutine::auto
Automatic event and IO coroutine awareness

counter
Procedures for counters and histograms

crc16
Perform a 16bit Cyclic Redundancy Check

crc32
Perform a 32bit Cyclic Redundancy Check

cron
Tool for automating the period callback of commands

csv
Procedures to handle CSV data.

debug
debug narrative - core

debug::caller
debug narrative - caller

debug::heartbeat
debug narrative - heartbeat

debug::timestamp
debug narrative - timestamping

defer
Defered execution

deleg_method
Creation of comm delegates (snit methods)

deleg_proc
Creation of comm delegates (procedures)

des
Implementation of the DES and triple-DES ciphers

dicttool
Dictionary Tools

dns
Tcl Domain Name Service Client

docidx_intro
docidx introduction

docidx_lang_cmdref
docidx language command reference

docidx_lang_faq
docidx language faq

docidx_lang_intro
docidx language introduction

docidx_lang_syntax
docidx language syntax

docidx_plugin_apiref
docidx plugin API reference

docstrip
Docstrip style source code extraction

docstrip_util
Docstrip-related utilities

doctoc_intro
doctoc introduction

doctoc_lang_cmdref
doctoc language command reference

doctoc_lang_faq
doctoc language faq

doctoc_lang_intro
doctoc language introduction

doctoc_lang_syntax
doctoc language syntax

doctoc_plugin_apiref
doctoc plugin API reference

doctools
doctools - Processing documents

doctools2idx_introduction
DocTools - Keyword indices

doctools2toc_introduction
DocTools - Tables of Contents

doctools::changelog
Processing text in Emacs ChangeLog format

doctools::cvs
Processing text in 'cvs log' format

doctools::html::cssdefaults
Default CSS style for HTML export plugins

doctools::idx
docidx - Processing indices

doctools::idx
Holding keyword indices

doctools::idx::export
Exporting keyword indices

doctools::idx::export::docidx
docidx export plugin

doctools::idx::export::html
HTML export plugin

doctools::idx::export::json
JSON export plugin

doctools::idx::export::nroff
nroff export plugin

doctools::idx::export::text
plain text export plugin

doctools::idx::export::wiki
wiki export plugin

doctools::idx::import
Importing keyword indices

doctools::idx::import::docidx
docidx import plugin

doctools::idx::import::json
JSON import plugin

doctools::idx::parse
Parsing text in docidx format

doctools::idx::structure
Docidx serialization utilities

doctools::msgcat
Message catalog management for the various document parsers

doctools::msgcat::idx::c
Message catalog for the docidx parser (C)

doctools::msgcat::idx::de
Message catalog for the docidx parser (DE)

doctools::msgcat::idx::en
Message catalog for the docidx parser (EN)

doctools::msgcat::idx::fr
Message catalog for the docidx parser (FR)

doctools::msgcat::toc::c
Message catalog for the doctoc parser (C)

doctools::msgcat::toc::de
Message catalog for the doctoc parser (DE)

doctools::msgcat::toc::en
Message catalog for the doctoc parser (EN)

doctools::msgcat::toc::fr
Message catalog for the doctoc parser (FR)

doctools::nroff::man_macros
Default CSS style for NROFF export plugins

doctools::tcl::parse
Processing text in 'subst -novariables' format

doctools::toc
Holding tables of contents

doctools::toc
doctoc - Processing tables of contents

doctools::toc::export
Exporting tables of contents

doctools::toc::export::doctoc
doctoc export plugin

doctools::toc::export::html
HTML export plugin

doctools::toc::export::json
JSON export plugin

doctools::toc::export::nroff
nroff export plugin

doctools::toc::export::text
plain text export plugin

doctools::toc::export::wiki
wiki export plugin

doctools::toc::import
Importing keyword indices

doctools::toc::import::doctoc
doctoc import plugin

doctools::toc::import::json
JSON import plugin

doctools::toc::parse
Parsing text in doctoc format

doctools::toc::structure
Doctoc serialization utilities

doctools_intro
doctools introduction

doctools_lang_cmdref
doctools language command reference

doctools_lang_faq
doctools language faq

doctools_lang_intro
doctools language introduction

doctools_lang_syntax
doctools language syntax

doctools_plugin_apiref
doctools plugin API reference

dtplite
Lightweight DocTools Markup Processor

fileutil
Procedures implementing some file utilities

fileutil::magic::cfront
Generator core for compiler of magic(5) files

fileutil::magic::cgen
Generator core for compiler of magic(5) files

fileutil::magic::filetype
Procedures implementing file-type recognition

fileutil::magic::rt
Runtime core for file type recognition engines written in pure Tcl

fileutil::multi
Multi-file operation, scatter/gather, standard object

fileutil::multi::op
Multi-file operation, scatter/gather

fileutil::paths
Manage search path pools

fileutil_traverse
Iterative directory traversal

ftp
Client-side tcl implementation of the ftp protocol

ftp::geturl
Uri handler for ftp urls

ftpd
Tcl FTP server implementation

generator
Procedures for creating and using generators.

gpx
Extracts waypoints, tracks and routes from GPX files

grammar::aycock
Aycock-Horspool-Earley parser generator for Tcl

grammar::fa
Create and manipulate finite automatons

grammar::fa::dacceptor
Create and use deterministic acceptors

grammar::fa::dexec
Execute deterministic finite automatons

grammar::fa::op
Operations on finite automatons

grammar::me::cpu
Virtual machine implementation II for parsing token streams

grammar::me::cpu::core
ME virtual machine state manipulation

grammar::me::cpu::gasm
ME assembler

grammar::me::tcl
Virtual machine implementation I for parsing token streams

grammar::me::util
AST utilities

grammar::me_ast
Various representations of ASTs

grammar::me_intro
Introduction to virtual machines for parsing token streams

grammar::me_vm
Virtual machine for parsing token streams

grammar::peg
Create and manipulate parsing expression grammars

grammar::peg::interp
Interpreter for parsing expression grammars

hook
Hooks

html
Procedures to generate HTML structures

htmlparse
Procedures to parse HTML strings

httpd
A TclOO and coroutine based web server

huddle
Create and manipulate huddle object

ident
Ident protocol client

imap4
imap client-side tcl implementation of imap protocol

inifile
Parsing of Windows INI files

interp
Interp creation and aliasing

irc
Create IRC connection and interface.

javascript
Procedures to generate HTML and Java Script structures.

jpeg
JPEG querying and manipulation of meta data

json
JSON parser

json::write
JSON generation

lambda
Utility commands for anonymous procedures

lazyset
Lazy evaluation

ldap
LDAP client

ldapx
LDAP extended object interface

log
Procedures to log messages of libraries and applications.

logger
System to control logging of events.

logger::appender
Collection of predefined appenders for logger

logger::utils
Utilities for logger

map::geocode::nominatim
Resolving geographical names with a Nominatim service

map::slippy
Common code for slippy based map packages

map::slippy::cache
Management of a tile cache in the local filesystem

map::slippy::fetcher
Accessing a server providing tiles for slippy-based maps

mapproj
Map projection routines

markdown
Converts Markdown text to HTML

math
Tcl Math Library

math::bigfloat
Arbitrary precision floating-point numbers

math::bignum
Arbitrary precision integer numbers

math::calculus
Integration and ordinary differential equations

math::calculus::romberg
Romberg integration

math::calculus::symdiff
Symbolic differentiation for Tcl

math::changepoint
Change point detection methods

math::combinatorics
Combinatorial functions in the Tcl Math Library

math::complexnumbers
Straightforward complex number package

math::constants
Mathematical and numerical constants

math::decimal
General decimal arithmetic

math::exact
Exact Real Arithmetic

math::figurate
Evaluate figurate numbers

math::filters
Digital filters

math::fourier
Discrete and fast fourier transforms

math::fuzzy
Fuzzy comparison of floating-point numbers

math::geometry
Geometrical computations

math::interpolate
Interpolation routines

math::linearalgebra
Linear Algebra

math::machineparameters
Compute double precision machine parameters.

math::numtheory
Number Theory

math::optimize
Optimisation routines

math::PCA
Package for Principal Component Analysis

math::polynomials
Polynomial functions

math::probopt
Probabilistic optimisation methods

math::quasirandom
Quasi-random points for integration and Monte Carlo type methods

math::rationalfunctions
Polynomial functions

math::roman
Tools for creating and manipulating roman numerals

math::special
Special mathematical functions

math::statistics
Basic statistical functions and procedures

math::trig
Trigonometric anf hyperbolic functions

md4
MD4 Message-Digest Algorithm

md5
MD5 Message-Digest Algorithm

md5crypt
MD5-based password encryption

mime
Manipulation of MIME body parts

mkdoc
Source code documentation extractor/converter application

mkdoc
Extracts and optionally converts Markdown comments in source code to HTML

mpexpand
Markup processor

multiplexer
One-to-many communication with sockets.

nameserv
Name service facility, Client

nameserv::auto
Name service facility, Client Extension

nameserv::common
Name service facility, shared definitions

nameserv::protocol
Name service facility, client/server protocol

nameserv::server
Name service facility, Server

namespacex
Namespace utility commands

ncgi
Procedures to manipulate CGI values.

nettool
Tools for networked applications

nmea
Process NMEA data

nns
Name service facility, Commandline Client Application

nns_intro
Name service facility, introduction

nnsd
Name service facility, Commandline Server Application

nnslog
Name service facility, Commandline Logging Client Application

nntp
Tcl client for the NNTP protocol

ntp_time
Tcl Time Service Client

oauth
oauth API base signature

oo::util
Utility commands for TclOO

oo::util
Utility commands for TclOO

oometa
oo::meta A data registry for classess

otp
One-Time Passwords

page
Parser Generator

page_intro
page introduction

page_pluginmgr
page plugin manager

page_util_flow
page dataflow/treewalker utility

page_util_norm_lemon
page AST normalization, LEMON

page_util_norm_peg
page AST normalization, PEG

page_util_peg
page PEG transformation utilities

page_util_quote
page character quoting utilities

picoirc
Small and simple embeddable IRC client.

pkg_dtplite
Lightweight DocTools Markup Processor

pki
Implementation of the public key cipher

pluginmgr
Manage a plugin

png
PNG querying and manipulation of meta data

pop3
Tcl client for POP3 email protocol

pop3d
Tcl POP3 server implementation

pop3d::dbox
Simple mailbox database for pop3d

pop3d::udb
Simple user database for pop3d

practcl
The Practcl Module

processman
Tool for automating the period callback of commands

profiler
Tcl source code profiler

pt
Parser Tools Application

pt::ast
Abstract Syntax Tree Serialization

pt::cparam::configuration::critcl
C/PARAM, Canned configuration, Critcl

pt::cparam::configuration::tea
C/PARAM, Canned configuration, TEA

pt::json_language
The JSON Grammar Exchange Format

pt::param
PackRat Machine Specification

pt::pe
Parsing Expression Serialization

pt::pe::op
Parsing Expression Utilities

pt::peg
Parsing Expression Grammar Serialization

pt::peg::container
PEG Storage

pt::peg::container::peg
PEG Storage. Canned PEG grammar specification

pt::peg::export
PEG Export

pt::peg::export::container
PEG Export Plugin. Write CONTAINER format

pt::peg::export::json
PEG Export Plugin. Write JSON format

pt::peg::export::peg
PEG Export Plugin. Write PEG format

pt::peg::from::container
PEG Conversion. From CONTAINER format

pt::peg::from::json
PEG Conversion. Read JSON format

pt::peg::from::peg
PEG Conversion. Read PEG format

pt::peg::import
PEG Import

pt::peg::import::container
PEG Import Plugin. From CONTAINER format

pt::peg::import::json
PEG Import Plugin. Read JSON format

pt::peg::import::peg
PEG Import Plugin. Read PEG format

pt::peg::interp
Interpreter for parsing expression grammars

pt::peg::to::container
PEG Conversion. Write CONTAINER format

pt::peg::to::cparam
PEG Conversion. Write CPARAM format

pt::peg::to::json
PEG Conversion. Write JSON format

pt::peg::to::param
PEG Conversion. Write PARAM format

pt::peg::to::peg
PEG Conversion. Write PEG format

pt::peg::to::tclparam
PEG Conversion. Write TCLPARAM format

pt::peg_language
PEG Language Tutorial

pt::pegrammar
Introduction to Parsing Expression Grammars

pt::pgen
Parser Generator

pt::rde
Parsing Runtime Support, PARAM based

pt::tclparam::configuration::nx
Tcl/PARAM, Canned configuration, NX

pt::tclparam::configuration::snit
Tcl/PARAM, Canned configuration, Snit

pt::tclparam::configuration::tcloo
Tcl/PARAM, Canned configuration, Tcloo

pt::util
General utilities

pt_export_api
Parser Tools Export API

pt_import_api
Parser Tools Import API

pt_introduction
Introduction to Parser Tools

pt_parse_peg
Parser Tools PEG Parser

pt_parser_api
Parser API

pt_peg_op
Parser Tools PE Grammar Utility Operations

rc4
Implementation of the RC4 stream cipher

rcs
RCS low level utilities

report
Create and manipulate report objects

rest
define REST web APIs and call them inline or asychronously

ripemd128
RIPEMD-128 Message-Digest Algorithm

ripemd160
RIPEMD-160 Message-Digest Algorithm

S3
Amazon S3 Web Service Interface

SASL
Implementation of SASL mechanisms for Tcl

SASL::NTLM
Implementation of SASL NTLM mechanism for Tcl

SASL::SCRAM
Implementation of SASL SCRAM mechanism for Tcl

SASL::XGoogleToken
Implementation of SASL NTLM mechanism for Tcl

sha1
SHA1 Message-Digest Algorithm

sha256
SHA256 Message-Digest Algorithm

simulation::annealing
Simulated annealing

simulation::montecarlo
Monte Carlo simulations

simulation::random
Pseudo-random number generators

smtp
Client-side tcl implementation of the smtp protocol

smtpd
Tcl SMTP server implementation

snit
Snit's Not Incr Tcl

snitfaq
Snit Frequently Asked Questions

soundex
Soundex

stooop
Object oriented extension.

string::token
Regex based iterative lexing

string::token::shell
Parsing of shell command line

stringprep
Implementation of stringprep

stringprep::data
stringprep data tables, generated, internal

struct::disjointset
Disjoint set data structure

struct::graph
Create and manipulate directed graph objects

struct::graph::op
Operation for (un)directed graph objects

struct::graph_v1
Create and manipulate directed graph objects

struct::list
Procedures for manipulating lists

struct::map
Manage key/value maps

struct::matrix
Create and manipulate matrix objects

struct::matrix_v1
Create and manipulate matrix objects

struct::pool
Create and manipulate pool objects (of discrete items)

struct::prioqueue
Create and manipulate prioqueue objects

struct::queue
Create and manipulate queue objects

struct::record
Define and create records (similar to 'C' structures)

struct::set
Procedures for manipulating sets

struct::skiplist
Create and manipulate skiplists

struct::stack
Create and manipulate stack objects

struct::tree
Create and manipulate tree objects

struct::tree_v1
Create and manipulate tree objects

sum
Calculate a sum(1) compatible checksum

switched
switch/option management.

tar
Tar file creation, extraction & manipulation

tcl::chan::cat
Concatenation channel

tcl::chan::core
Basic reflected/virtual channel support

tcl::chan::events
Event support for reflected/virtual channels

tcl::chan::facade
Facade channel

tcl::chan::fifo
In-memory fifo channel

tcl::chan::fifo2
In-memory interconnected fifo channels

tcl::chan::halfpipe
In-memory channel, half of a fifo2

tcl::chan::memchan
In-memory channel

tcl::chan::null
Null channel

tcl::chan::nullzero
Null/Zero channel combination

tcl::chan::random
Random channel

tcl::chan::std
Standard I/O, unification of stdin and stdout

tcl::chan::string
Read-only in-memory channel

tcl::chan::textwindow
Textwindow channel

tcl::chan::variable
In-memory channel using variable for storage

tcl::chan::zero
Zero channel

tcl::randomseed
Utilities for random channels

tcl::transform::adler32
Adler32 transformation

tcl::transform::base64
Base64 encoding transformation

tcl::transform::core
Basic reflected/virtual channel transform support

tcl::transform::counter
Counter transformation

tcl::transform::crc32
Crc32 transformation

tcl::transform::hex
Hexadecimal encoding transformation

tcl::transform::identity
Identity transformation

tcl::transform::limitsize
limiting input

tcl::transform::observe
Observer transformation, stream copy

tcl::transform::otp
Encryption via one-time pad

tcl::transform::rot
rot-encryption

tcl::transform::spacer
Space insertation and removal

tcl::transform::zlib
zlib (de)compression

tcl_community_communication
Tcl Community - Kind Communication

tclDES
Implementation of the DES and triple-DES ciphers

tclDESjr
Implementation of the DES and triple-DES ciphers

tcldocstrip
Tcl-based Docstrip Processor

tcllib_devguide
Tcllib - The Developer's Guide

tcllib_install_guide
Tcllib - The Installer's Guide

tcllib_ip
IPv4 and IPv6 address manipulation

tcllib_license
Tcllib - License

tcllib_releasemgr
Tcllib - The Release Manager's Guide

tcllib_sources
Tcllib - How To Get The Sources

tepam
An introduction into TEPAM, Tcl's Enhanced Procedure and Argument Manager

tepam::argument_dialogbox
TEPAM argument_dialogbox, reference manual

tepam::doc_gen
TEPAM DOC Generation, reference manual

tepam::procedure
TEPAM procedure, reference manual

term
General terminal control

term::ansi::code
Helper for control sequences

term::ansi::code::attr
ANSI attribute sequences

term::ansi::code::ctrl
ANSI control sequences

term::ansi::code::macros
Macro sequences

term::ansi::ctrl::unix
Control operations and queries

term::ansi::send
Output of ANSI control sequences to terminals

term::interact::menu
Terminal widget, menu

term::interact::pager
Terminal widget, paging

term::receive
General input from terminals

term::receive::bind
Keyboard dispatch from terminals

term::send
General output to terminals

textutil
Procedures to manipulate texts and strings.

textutil::adjust
Procedures to adjust, indent, and undent paragraphs

textutil::expander
Procedures to process templates and expand text.

textutil::patch
Application of uni-diff patches to directory trees

textutil::repeat
Procedures to repeat strings.

textutil::split
Procedures to split texts

textutil::string
Procedures to manipulate texts and strings.

textutil::tabify
Procedures to (un)tabify strings

textutil::trim
Procedures to trim strings

throw
throw - Throw an error exception with a message

tie
Array persistence, standard data sources

tie
Array persistence

tiff
TIFF reading, writing, and querying and manipulation of meta data

tool
TclOO Library (TOOL) Framework

tool::dict_ensemble
Dictionary Tools

transfer::connect
Connection setup

transfer::copy
Data transfer foundation

transfer::copy::queue
Queued transfers

transfer::data::destination
Data destination

transfer::data::source
Data source

transfer::receiver
Data source

transfer::transmitter
Data source

treeql
Query tree objects

try
try - Trap and process errors and exceptions

udpcluster
UDP Peer-to-Peer cluster

uevent
User events

uevent::onidle
Request merging and deferal to idle time

unicode
Implementation of Unicode normalization

unicode::data
unicode data tables, generated, internal

units
unit conversion

uri
URI utilities

uri_urn
URI utilities, URN scheme

uuencode
UU-encode/decode binary data

uuid
UUID generation and comparison

valtype::common
Validation, common code

valtype::creditcard::amex
Validation for AMEX creditcard number

valtype::creditcard::discover
Validation for Discover creditcard number

valtype::creditcard::mastercard
Validation for Mastercard creditcard number

valtype::creditcard::visa
Validation for VISA creditcard number

valtype::gs1::ean13
Validation for EAN13

valtype::iban
Validation for IBAN

valtype::imei
Validation for IMEI

valtype::isbn
Validation for ISBN

valtype::luhn
Validation for plain number with a LUHN checkdigit

valtype::luhn5
Validation for plain number with a LUHN5 checkdigit

valtype::usnpi
Validation for USNPI

valtype::verhoeff
Validation for plain number with a VERHOEFF checkdigit

websocket
Tcl implementation of the websocket protocol

wip
Word Interpreter

xsxp
eXtremely Simple Xml Parser

yaml
YAML Format Encoder/Decoder

yencode
Y-encode/decode binary data

zipfile::decode
Access to zip archives

zipfile::encode
Generation of zip archives

zipfile::mkzip
Build a zip archive


text:
package me.limeglass.skellett.elements;

import org.bukkit.Location;
import org.bukkit.block.data.BlockData;
import org.eclipse.jdt.annotation.Nullable;

import ch.njol.skript.classes.Converter;
import ch.njol.skript.registrations.Converters;
import me.limeglass.skellett.objects.BlockSave;

public class DefaultConverters {

	static {
		Converters.registerConverter(BlockSave.class, BlockData.class, new Converter<BlockSave, BlockData>() {
			@Override
			@Nullable
			public BlockData convert(BlockSave save) {
				return save.getBlockData();
			}
		});
		Converters.registerConverter(BlockSave.class, Location.class, new Converter<BlockSave, Location>() {
			@Override
			@Nullable
			public Location convert(BlockSave save) {
				return save.getLocation();
			}
		});
	}

}

redpajama_set_name: RedPajamaGithub


text:
class Recipes::Spring < Rails::AppBuilder
  def create
    if answer(:spring)
      gather_gems(:development) do
        gather_gem("spring")
      end
    end
  end
end


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0001_initial'),
        ('products', '0018_delete_section'),
        ('ebooks', '0005_auto_20190425_1031'),
    ]

    operations = [
        migrations.CreateModel(
            name='Chapter',
            fields=[
                ('publishablemodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.PublishableModel')),
                ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
                ('modified', models.DateTimeField(auto_now=True, verbose_name='modified')),
                ('icon', models.CharField(max_length=30, verbose_name='icon')),
                ('title', models.CharField(max_length=50, verbose_name='title')),
                ('description', models.TextField(verbose_name='description')),
                ('color', models.CharField(choices=[('info', 'Blue'), ('primary', 'Rose'), ('danger', 'Red'), ('warning', 'Yellow'), ('success', 'Green'), ('default', 'Gray')], default='default', max_length=30, verbose_name='color')),
                ('order_index', models.PositiveIntegerField(verbose_name='order index')),
                ('slug', models.SlugField(unique=True, verbose_name='slug')),
                ('chapter_product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='products.Product', verbose_name='product')),
            ],
            options={
                'verbose_name': 'chapter',
                'verbose_name_plural': 'chapters',
            },
            bases=('core.publishablemodel', models.Model),
        ),
        migrations.RemoveField(
            model_name='section',
            name='product',
        ),
        migrations.AddField(
            model_name='section',
            name='chapter',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='ebooks.Chapter', verbose_name='chapter'),
        ),
    ]


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>No package | YiiWheels</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?260161822" />
	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2015443609" />

				YiiWheels

Package

Class

							Tree

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="" />
			<input type="hidden" name="ie" value="UTF-8" />
			<input type="text" name="q" class="search-query" placeholder="Search" />
		</form>

Packages

None

yiiwheels

behaviors

widgets

widgets

ace

box

datepicker

daterangepicker

datetimepicker

detail

fileupload

fileuploader

gallery

google

grid

behaviors

operations

highcharts

maskInput

maskmoney

modal

multiselect

rangeslider

redactor

select2

sparklines

switch

timeago

timepicker

toggle

typeahead

Classes

WhCountries

WhDatePickerHelper

WhDropDownInputWidget

WhFonts

WhFontSizes

WhGoogleFonts

WhInputWidget

WhLanguages

WhPhone

WhSelectBox

WhStates

WhTimePickerHelper

WhTimezones

No package

Classes summary

	WhCountries

	WhDatePickerHelper

	WhDropDownInputWidget

	WhFonts

	WhFontSizes

	WhGoogleFonts

	WhInputWidget

	WhLanguages

	WhPhone

	WhSelectBox

	WhStates

	WhTimePickerHelper

	WhTimezones

		YiiWheels API documentation generated by ApiGen 2.8.0


text:
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;

using Xunit;
using Xunit.Abstractions;

namespace System.Net.WebSockets.Client.Tests
{
    public class KeepAliveTest : ClientWebSocketTestBase
    {
        public KeepAliveTest(ITestOutputHelper output) : base(output) { }

        [ConditionalFact(nameof(WebSocketsSupported))]
        [OuterLoop] // involves long delay
        public async Task KeepAlive_LongDelayBetweenSendReceives_Succeeds()
        {
            using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(Configuration.WebSockets.RemoteEchoServer, TimeOutMilliseconds, _output, TimeSpan.FromSeconds(10)))
            {
                await cws.SendAsync(new ArraySegment<byte>(new byte[1] { 42 }), WebSocketMessageType.Binary, true, CancellationToken.None);

                await Task.Delay(TimeSpan.FromSeconds(60));

                byte[] receiveBuffer = new byte[1];
                Assert.Equal(1, (await cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None)).Count);
                Assert.Equal(42, receiveBuffer[0]);

                await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "KeepAlive_LongDelayBetweenSendReceives_Succeeds", CancellationToken.None);
            }
        }
    }
}


text:
CREATE TABLE SUBAWARD_TEMPLATE_TYPE (
    SUBAWARD_TEMPLATE_TYPE_CODE NUMBER(3,0) NOT NULL,
	DESCRIPTION VARCHAR2(200) NOT NULL,
	UPDATE_TIMESTAMP DATE NOT NULL,
	UPDATE_USER VARCHAR2(60) NOT NULL,
	VER_NBR NUMBER(8,0) DEFAULT 1 NOT NULL,
	OBJ_ID VARCHAR2(36) NOT NULL)
/

ALTER TABLE SUBAWARD_TEMPLATE_TYPE
ADD CONSTRAINT SUBAWARD_TEMPLATE_TYPES_PK
PRIMARY KEY (SUBAWARD_TEMPLATE_TYPE_CODE)
/


text:
.tooltipster-sidetip.tooltipster-borderless .tooltipster-box {
	border: none;
	background: #1b1b1b;
	background: rgba(10,10,10,0.90);
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-bottom .tooltipster-box {
	margin-top: 8px;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-left .tooltipster-box {
	margin-right: 8px;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-right .tooltipster-box {
	margin-left: 8px;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-top .tooltipster-box {
	margin-bottom: 8px;
}

.tooltipster-sidetip.tooltipster-borderless .tooltipster-arrow {
	height: 8px;
	margin-left: -8px;
	width: 16px;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-left .tooltipster-arrow,
.tooltipster-sidetip.tooltipster-borderless.tooltipster-right .tooltipster-arrow {
	height: 16px;
	margin-left: 0;
	margin-top: -8px;
	width: 8px;
}

.tooltipster-sidetip.tooltipster-borderless .tooltipster-arrow-background {
	display: none;
}

.tooltipster-sidetip.tooltipster-borderless .tooltipster-arrow-border {
	border: 8px solid transparent;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-bottom .tooltipster-arrow-border {
	border-bottom-color: #1b1b1b;
	border-bottom-color: rgba(10,10,10,0.90);
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-left .tooltipster-arrow-border {
	border-left-color: #1b1b1b;
	border-left-color: rgba(10,10,10,0.90);
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-right .tooltipster-arrow-border {
	border-right-color: #1b1b1b;
	border-right-color: rgba(10,10,10,0.90);
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-top .tooltipster-arrow-border {
	border-top-color: #1b1b1b;
	border-top-color: rgba(10,10,10,0.90);
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-bottom .tooltipster-arrow-uncropped {
	top: -8px;
}

.tooltipster-sidetip.tooltipster-borderless.tooltipster-right .tooltipster-arrow-uncropped {
	left: -8px;
}


text:
package org.rioproject.impl.associations;

import java.io.Serializable;

/**
 * Just a dummy class.
 */
public class DummyImpl implements Dummy, Serializable {
    int index;
    String name;

    DummyImpl(int index) {
        this.index = index;
    }

    DummyImpl(int index, String name) {
        this.index = index;
        this.name = name;
    }

    public int getIndex() {
        return index;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DummyImpl dummy = (DummyImpl) o;

        if (index != dummy.index)
            return false;
        if (name != null ? !name.equals(dummy.name) : dummy.name != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = index;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}


text:
class MailSender():

	_from, _to, _subject, _msg, _smtp = '', [], '', None, None

	def clear(self):
		self._from = ''
		self._to = []
		self._subject = ''
		self._msg = None

	def validateMail(self, mail):
		import re
		regex_mail = re.compile(r"(?:^|\s)[-a-z0-9_.\+]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", re.IGNORECASE)
                if re.match(regex_mail, mail):
                    return True
		return None

	def setBody(self, body):
		from email.mime.text import MIMEText
		self._msg = MIMEText(body)

        def setBodyHTML(self, body):
            from email.mime.text import MIMEText
            self._msg = MIMEText(body, 'html')

	def setFrom(self, _from):
		if(self.validateMail(_from) is None): raise Exception('MailSender.setFrom: _from param is not a valid email --> %s' % _from)
		self._from = _from

	def setTo(self, _to):
		if(self.validateMail(_to) is None): raise Exception('MailSender.setTo: _to param is not a valid email --> %s' % _to)
		self._to.append(_to)

	def setSubject(self, _subject):
		self._subject = _subject

	def opensmtp(self, email_account, pwd, log = False):
            import smtplib
            self._smtp = smtplib.SMTP('smtp.gmail.com', 587)
            self._smtp.ehlo()
            self._smtp.starttls()
            self._smtp.ehlo()
            self._smtp.login(email_account, pwd)
            self._smtp.set_debuglevel(log)

	def send(self):
		if self._msg is None: raise Exception('MailSender.send: mail body not set')
		if self._smtp is None: self.opensmtp()
		self._msg['Subject'] = self._subject
		self._msg['From']    = self._from
		self._msg['To']      = ', '.join(self._to)
		self._smtp.sendmail(self._from, self._to, self._msg.as_string())

	def __del__(self):
		self._smtp.quit()


text:
package com.sixrr.inspectjs.control;

import javax.annotation.Nonnull;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.javascript.psi.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import com.sixrr.inspectjs.*;
import com.sixrr.inspectjs.utils.ControlFlowUtils;

public class UnnecessaryContinueJSInspection extends JavaScriptInspection {
    private final UnnecessaryContinueFix fix = new UnnecessaryContinueFix();

    @Override
	@Nonnull
    public String getDisplayName() {
        return InspectionJSBundle.message("unnecessary.continue.statement.display.name");
    }

    @Override
	@Nonnull
    public String getGroupDisplayName() {
        return JSGroupNames.CONTROL_FLOW_GROUP_NAME;
    }

    @Override
	public boolean isEnabledByDefault() {
        return true;
    }

    @Override
	public String buildErrorString(Object... args) {
        return InspectionJSBundle.message("unnecessary.continue.error.string");
    }

    @Override
	public BaseInspectionVisitor buildVisitor() {
        return new Visitor();
    }

    @Override
	public InspectionJSFix buildFix(PsiElement location) {
        return fix;
    }

    private static class UnnecessaryContinueFix extends InspectionJSFix {
        @Override
		@Nonnull
        public String getName() {
            return InspectionJSBundle.message("remove.unnecessary.continue.fix");
        }

        @Override
		public void doFix(Project project, ProblemDescriptor descriptor)
                throws IncorrectOperationException {
            final PsiElement continueKeywordElement = descriptor.getPsiElement();
            final PsiElement continueStatement =
                    continueKeywordElement.getParent();
            assert continueStatement != null;
            deleteElement(continueStatement);
        }
    }

    private static class Visitor
            extends BaseInspectionVisitor {

        @Override public void visitJSContinueStatement(@Nonnull JSContinueStatement statement) {

            JSStatement continuedStatement =
                    statement.getStatementToContinue();
            if (continuedStatement == null) {
                return;
            }
            if(continuedStatement instanceof JSLabeledStatement)
            {
                continuedStatement = ((JSLabeledStatement)continuedStatement).getStatement();
            }
            if (!(continuedStatement instanceof JSLoopStatement)) {
                return;
            }
            final JSStatement body = ((JSLoopStatement) continuedStatement).getBody();
            if (body == null) {
                return;
            }
            if (body instanceof JSBlockStatement) {
                if (ControlFlowUtils.blockCompletesWithStatement((JSBlockStatement) body,
                        statement)) {
                    registerStatementError(statement);
                }
            } else {
                if (ControlFlowUtils.statementCompletesWithStatement(body,
                        statement)) {
                    registerStatementError(statement);
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using StructureMap.Construction;
using StructureMap.Pipeline;
using StructureMap.TypeRules;
using System.Linq;

namespace StructureMap.Graph
{
    /// <summary>
    /// Represents a concrete class that can be built by StructureMap as an instance of the parent
    /// PluginFamily's PluginType. The properties of a Plugin are the CLR Type of the concrete class,
    /// and the human-friendly concrete key that StructureMap will use to identify the Type.
    /// </summary>
    public class Plugin
    {
        public static readonly string DEFAULT = "DEFAULT";
        private readonly Constructor _constructor;

        private readonly Type _pluggedType;
        private readonly SetterPropertyCollection _setters;

        #region constructors

        public Plugin(Type pluggedType)
        {
            _pluggedType = pluggedType;
            _setters = new SetterPropertyCollection(this);
            _constructor = new Constructor(pluggedType);
        }

        #endregion

        [Obsolete("Temporary only")]
        public IInstanceBuilder CreateBuilder()
        {
            try
            {
                return BuilderCompiler.CreateBuilder(this);
            }
            catch (Exception e)
            {
                throw new StructureMapException(245, e, _pluggedType.AssemblyQualifiedName);
            }
        }

        /// <summary>
        /// The concrete CLR Type represented by the Plugin
        /// </summary>
        public Type PluggedType { get { return _pluggedType; } }

        /// <summary>
        /// Property's that will be filled by setter injection
        /// </summary>
        public SetterPropertyCollection Setters { get { return _setters; } }

        public bool CanBeAutoFilled { get { return _constructor.CanBeAutoFilled() && _setters.CanBeAutoFilled(); } }

        public override string ToString()
        {
            return "Plugin:  " +  PluggedType.AssemblyQualifiedName;
        }

        public string FindArgumentNameForType<T>()
        {
            return FindArgumentNameForType(typeof (T), CannotFindProperty.ThrowException);
        }

        public string FindArgumentNameForEnumerableOf(Type type)
        {
            var enumerableTypes = EnumerableInstance.OpenEnumerableTypes.Select(x => x.MakeGenericType(type)).Union(new []{type.MakeArrayType()});
            return enumerableTypes.Select(t =>
            {
                return _constructor.FindFirstConstructorArgumentOfType(t) ??
                       _setters.FindFirstWriteablePropertyOfType(t);
            }).FirstOrDefault(x => x != null);
        }

        public string FindArgumentNameForType(Type type, CannotFindProperty cannotFind)
        {
            string returnValue =
                _constructor.FindFirstConstructorArgumentOfType(type) ??
                _setters.FindFirstWriteablePropertyOfType(type);

            if (returnValue == null && cannotFind == CannotFindProperty.ThrowException)
            {
                throw new StructureMapException(302, type.FullName, _pluggedType.FullName);
            }

            return returnValue;
        }

        public void VisitArguments(IArgumentVisitor visitor)
        {
            _constructor.Visit(visitor);
            _setters.Visit(visitor);
        }

        public void MergeSetters(Plugin plugin)
        {
            Setters.Merge(plugin.Setters);
        }

        public ConstructorInfo GetConstructor()
        {
            return _constructor.Ctor;
        }

        public void VisitConstructor(IArgumentVisitor arguments)
        {
            _constructor.Visit(arguments);
        }

        public void VisitSetters(IArgumentVisitor arguments)
        {
            _setters.Visit(arguments);
        }

        public bool IsValid()
        {
            return _constructor.IsValid();
        }

        public bool CanBeCreated()
        {
            return Constructor.HasConstructors(_pluggedType);
        }

        public bool HasOptionalSetters()
        {
            return _setters.OptionalCount > 0;
        }

        public Plugin CreateTemplatedClone(Type[] types)
        {
            Type templatedType = _pluggedType.IsGenericType ? _pluggedType.MakeGenericType(types) : _pluggedType;

            var templatedPlugin = new Plugin(templatedType);

            foreach (SetterProperty setter in Setters)
            {
                templatedPlugin.Setters.MarkSetterAsMandatory(setter.Name);
            }

            return templatedPlugin;
        }

        public void UseConstructor(Expression expression)
        {
            _constructor.UseConstructor(expression);
        }

        public void UseSetterRule(Func<PropertyInfo, bool> rule)
        {
            _setters.UseSetterRule(rule);
        }

        public bool IsNotOpenGeneric()
        {
            return !_pluggedType.IsOpenGeneric();
        }

        public Type FindArgumentType(string argumentName)
        {
            return _constructor.FindArgumentType(argumentName) ?? _setters.FindArgumentType(argumentName);
        }
    }
}


text:
package build.pluto.test.build.latexlike;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import build.pluto.stamp.Stamper;
import build.pluto.stamp.ValueStamp;

public class BibtexlikeStamper implements Stamper {

  /**
   *
   */
  private static final long serialVersionUID = 1658120627346161279L;
  public static final BibtexlikeStamper instance = new BibtexlikeStamper();

  private BibtexlikeStamper() {
  }

  @Override
  public ValueStamp<Set<Character>> stampOf(File outFile) {
    try {
      ObjectInputStream outStream = new ObjectInputStream(new FileInputStream(outFile));
      List<Character> replacements = (List<Character>) outStream.readObject();
      outStream.close();
      return new ValueStamp<Set<Character>>(this, new HashSet<>(replacements));
    } catch (IOException e) {
      return new ValueStamp<>(this, null);
    } catch (ClassNotFoundException e) {
      return new ValueStamp<>(this, null);
    }
  }

}


text:
package org.apache.any23.filter;

import org.apache.any23.extractor.ExtractionContext;
import org.apache.any23.writer.TripleHandler;
import org.apache.any23.writer.TripleHandlerException;
import org.junit.Test;
import org.mockito.verification.VerificationMode;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

/**
 * Test case for {@link IgnoreAccidentalRDFa}.
 *
 * @author Michele Mostarda (mostarda@fbk.eu)
 */
public class IgnoreAccidentalRDFaTest {

    @Test
    public void testBlockCSSTriple() throws TripleHandlerException {
        checkTriple("http://www.w3.org/1999/xhtml/vocab#stylesheet", never());
    }

    @Test
    public void testAcceptGenericTriple() throws TripleHandlerException {
        checkTriple("http://www.w3.org/1999/xhtml/vocab#license", times(1));
    }

    private void checkTriple(String predicate, VerificationMode verificationMode)
    throws TripleHandlerException {
        final String DOCUMENT_URI = "http://an.html.page";
        final TripleHandler mockTripleHandler = mock(TripleHandler.class);
        final ValueFactory valueFactory = new ValueFactoryImpl();
        ExtractionContext extractionContext = new ExtractionContext(
                "test-extractor",
                valueFactory.createURI(DOCUMENT_URI)
        );
        final IgnoreAccidentalRDFa ignoreAccidentalRDFa = new IgnoreAccidentalRDFa(mockTripleHandler, true);
        ignoreAccidentalRDFa.openContext(extractionContext);
        ignoreAccidentalRDFa.receiveTriple(
                valueFactory.createURI(DOCUMENT_URI),
                valueFactory.createURI(predicate),
                valueFactory.createURI("http://www.myedu.com/modules/20110519065453/profile.css"),
                valueFactory.createURI(DOCUMENT_URI),
                extractionContext
        );
        ignoreAccidentalRDFa.close();

        verify(
                mockTripleHandler,
                verificationMode
        ).receiveTriple(
                (Resource) any(),
                (URI) any(),
                (Value) any(),
                (URI) any(),
                (ExtractionContext) any()
        );
    }

}


text:
"""
Copyright (c)2012 Daniel Rich <drich@employees.org>

This module will query an squid server via SNMP for metrics
"""

import sys
import os
import re

import time
#import logging
#logging.basicConfig(level=logging.ERROR, format="%(asctime)s - %(name)s - %(levelname)s\t Thread-%(thread)d - %(message)s", filename='/tmp/gmond.log', filemode='w')
#logging.debug('starting up')

last_update = 0
# We get counter values back, so we have to calculate deltas for some stats
squid_stats = {}
squid_stats_last = {}

MIN_UPDATE_INTERVAL = 30          # Minimum update interval in seconds

def collect_stats():
    #logging.debug('collect_stats()')
    global last_update
    global squid_stats, squid_stats_last

    now = time.time()

    if now - last_update < MIN_UPDATE_INTERVAL:
        #logging.debug(' wait ' + str(int(MIN_UPDATE_INTERVAL - (now - last_update))) + ' seconds')
        return True
    else:
        elapsed_time = now - last_update
        last_update = now

    squid_stats = {}

    # Run squidclient mgr:info to get stats
    try:
        stats = {}
        squidclient = os.popen("squidclient mgr:info")
    except IOError,e:
        #logging.error('error running squidclient')
        return False

    # Parse output, splitting everything into key/value pairs
    rawstats = {}
    for stat in squidclient.readlines():
        stat = stat.strip()
        if stat.find(':') >= 0:
            [key,value] = stat.split(':',1)
            if value:     # Toss things with no value
                value = value.lstrip()
                rawstats[key] = value
        else:
            match = re.search("(\d+)\s+(.*)$",stat) # reversed "value key" line
            if match:
                rawstats[match.group(2)] = match.group(1)

    # Use stats_descriptions to convert raw stats to real metrics
    for metric in stats_descriptions:
        if stats_descriptions[metric].has_key('key'):
            if rawstats.has_key(stats_descriptions[metric]['key']):
                rawstat = rawstats[stats_descriptions[metric]['key']]
                if stats_descriptions[metric].has_key('match'):
                    match = re.match(stats_descriptions[metric]['match'],rawstat)
                    if match:
                        rawstat = match.group(1)
                        squid_stats[metric] = rawstat
                else:
                    squid_stats[metric] = rawstat
        if squid_stats.has_key(metric): # Strip trailing non-num text
            if metric != 'cacheVersionId': # version is special case
                match = re.match('([0-9.]+)',squid_stats[metric]);
                squid_stats[metric] = float(match.group(1))
                if stats_descriptions[metric]['type'] == 'integer':
                    squid_stats[metric] = int(squid_stats[metric])

        # Calculate delta for counter stats
        if metric in squid_stats_last:
            if stats_descriptions[metric]['type'] == 'counter32':
                current = squid_stats[metric]
                squid_stats[metric] = (squid_stats[metric] - squid_stats_last[metric]) / float(elapsed_time)
                squid_stats_last[metric] = current
            else:
                squid_stats_last[metric] = squid_stats[metric]
        else:
            if metric in squid_stats:
                squid_stats_last[metric] = squid_stats[metric]

    #logging.debug('collect_stats done')
    #logging.debug('squid_stats: ' + str(squid_stats))

def get_stat(name):
    #logging.info("get_stat(%s)" % name)
    global squid_stats

    ret = collect_stats()

    if ret:
        if name.startswith('squid_'):
            label = name[6:]
        else:
            lable = name

            #logging.debug("fetching %s" % label)
        try:
            #logging.info("got %4.2f" % squid_stats[label])
            return squid_stats[label]
        except:
            #logging.error("failed to fetch %s" % name)
            return 0

    else:
        return 0

def metric_init(params):
    global descriptors
    global squid_stats
    global stats_descriptions   # needed for stats extraction in collect_stat()

    #logging.debug("init: " + str(params))

    stats_descriptions = dict(
        cacheVersionId = {
            'description': 'Cache Software Version',
            'units': 'N/A',
            'type': 'string',
            'key': 'Squid Object Cache',
            },
        cacheSysVMsize = {
            'description': 'Storage Mem size in KB',
            'units': 'KB',
            'type': 'integer',
            'key': 'Storage Mem size',
            },
        cacheMemUsage = {
            'description': 'Total memory accounted for KB',
            'units': 'KB',
            'type': 'integer',
            'key': 'Total accounted',
            },
        cacheSysPageFaults = {
            'description': 'Page faults with physical i/o',
            'units': 'faults/s',
            'type': 'counter32',
            'key': 'Page faults with physical i/o',
            },
        cacheCpuTime = {
            'description': 'Amount of cpu seconds consumed',
            'units': 'seconds',
            'type': 'integer',
            'key': 'CPU Time',
            },
        cacheCpuUsage = {
            'description': 'The percentage use of the CPU',
            'units': 'percent',
            'type': 'float',
            'key': 'CPU Usage',
            },
        cacheCpuUsage_5 = {
            'description': 'The percentage use of the CPU - 5 min',
            'units': 'percent',
            'type': 'float',
            'key': 'CPU Usage, 5 minute avg',
            },
        cacheCpuUsage_60 = {
            'description': 'The percentage use of the CPU - 60 min',
            'units': 'percent',
            'type': 'float',
            'key': 'CPU Usage, 60 minute avg',
            },
        cacheMaxResSize = {
            'description': 'Maximum Resident Size in KB',
            'units': 'KB',
            'type': 'integer',
            'key': 'Maximum Resident Size',
            },
        cacheNumObjCount = {
            'description': 'Number of objects stored by the cache',
            'units': 'objects',
            'type': 'integer',
            'key': 'StoreEntries',
            },
        cacheNumObjCountMemObj = {
            'description': 'Number of memobjects stored by the cache',
            'units': 'objects',
            'type': 'integer',
            'key': 'StoreEntries with MemObjects',
            },
        cacheNumObjCountHot = {
            'description': 'Number of hot objects stored by the cache',
            'units': 'objects',
            'type': 'integer',
            'key': 'Hot Object Cache Items',
            },
        cacheNumObjCountOnDisk = {
            'description': 'Number of objects stored by the cache on-disk',
            'units': 'objects',
            'type': 'integer',
            'key': 'on-disk objects',
            },
        cacheCurrentUnusedFDescrCnt = {
            'description': 'Available number of file descriptors',
            'units': 'file descriptors',
            'type': 'gauge32',
            'key': 'Maximum number of file descriptors',
            },
        cacheCurrentResFileDescrCnt = {
            'description': 'Reserved number of file descriptors',
            'units': 'file descriptors',
            'type': 'gauge32',
            'key': 'Reserved number of file descriptors',
            },
        cacheCurrentFileDescrCnt = {
            'description': 'Number of file descriptors in use',
            'units': 'file descriptors',
            'type': 'gauge32',
            'key': 'Number of file desc currently in use',
            },
        cacheCurrentFileDescrMax = {
            'description': 'Highest file descriptors in use',
            'units': 'file descriptors',
            'type': 'gauge32',
            'key': 'Largest file desc currently in use',
            },
        cacheProtoClientHttpRequests = {
            'description': 'Number of HTTP requests received',
            'units': 'requests/s',
            'type': 'counter32',
            'key': 'Number of HTTP requests received'
            },
        cacheIcpPktsSent = {
            'description': 'Number of ICP messages sent',
            'units': 'messages/s',
            'type': 'counter32',
            'key': 'Number of ICP messages sent',
            },
        cacheIcpPktsRecv = {
            'description': 'Number of ICP messages received',
            'units': 'messages/s',
            'type': 'counter32',
            'key': 'Number of ICP messages received',
            },
        cacheCurrentSwapSize = {
            'description': 'Storage Swap size',
            'units': 'KB',
            'type': 'gauge32',
            'key': 'Storage Swap size',
            },
        cacheClients = {
            'description': 'Number of clients accessing cache',
            'units': 'clients',
            'type': 'gauge32',
            'key': 'Number of clients accessing cache',
            },
        cacheHttpAllSvcTime_5 = {
            'description': 'HTTP all service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'HTTP Requests (All)',
            'match': '([0-9.]+)',
            },
        cacheHttpAllSvcTime_60 = {
            'description': 'HTTP all service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'HTTP Requests (All)',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheHttpMissSvcTime_5 = {
            'description': 'HTTP miss service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Cache Misses',
            'match': '([0-9.]+)',
            },
        cacheHttpMissSvcTime_60 = {
            'description': 'HTTP miss service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Cache Misses',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheHttpNmSvcTime_5 = {
            'description': 'HTTP hit not-modified service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Not-Modified Replies',
            'match': '([0-9.]+)',
            },
        cacheHttpNmSvcTime_60 = {
            'description': 'HTTP hit not-modified service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Not-Modified Replies',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheHttpHitSvcTime_5 = {
            'description': 'HTTP hit service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Cache Hits',
            'match': '([0-9.]+)',
            },
        cacheHttpHitSvcTime_60 = {
            'description': 'HTTP hit service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Cache Hits',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheIcpQuerySvcTime_5 = {
            'description': 'ICP query service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'ICP Queries',
            'match': '([0-9.]+)',
            },
        cacheIcpQuerySvcTime_60 = {
            'description': 'ICP query service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'ICP Queries',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheDnsSvcTime_5 = {
            'description': 'DNS service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'DNS Lookups',
            'match': '([0-9.]+)',
            },
        cacheDnsSvcTime_60 = {
            'description': 'DNS service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'DNS Lookups',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
        cacheRequestHitRatio_5 = {
            'description': 'Request Hit Ratios - 5 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Hit Ratios',
            'match': '5min: ([0-9.]+)%',
            },
        cacheRequestHitRatio_60 = {
            'description': 'Request Hit Ratios - 60 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Hit Ratios',
            'match': '5min: [0-9.]+%,\s+60min: ([0-9.]+)%',
            },
        cacheRequestByteRatio_5 = {
            'description': 'Byte Hit Ratios - 5 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Byte Hit Ratios',
            'match': '5min: ([0-9.]+)%',
            },
        cacheRequestByteRatio_60 = {
            'description': 'Byte Hit Ratios - 60 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Byte Hit Ratios',
            'match': '5min: [0-9.]+%,\s+60min: ([0-9.]+)%',
            },
        cacheRequestMemRatio_5 = {
            'description': 'Memory Hit Ratios - 5 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Memory Hit Ratios',
            'match': '5min: ([0-9.]+)%',
            },
        cacheRequestMemRatio_60 = {
            'description': 'Memory Hit Ratios - 60 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Memory Hit Ratios',
            'match': '5min: [0-9.]+%,\s+60min: ([0-9.]+)%',
            },
        cacheRequestDiskRatio_5 = {
            'description': 'Disk Hit Ratios - 5 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Disk Hit Ratios',
            'match': '5min: ([0-9.]+)%',
            },
        cacheRequestDiskRatio_60 = {
            'description': 'Disk Hit Ratios - 60 min',
            'units': 'percent',
            'type': 'float',
            'key': 'Request Disk Hit Ratios',
            'match': '5min: [0-9.]+%,\s+60min: ([0-9.]+)%',
            },
        cacheHttpNhSvcTime_5 = {
            'description': 'HTTP refresh hit service time - 5 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Near Hits',
            'match': '([0-9.]+)',
            },
        cacheHttpNhSvcTime_60 = {
            'description': 'HTTP refresh hit service time - 60 min',
            'units': 'seconds',
            'type': 'float',
            'key': 'Near Hits',
            'match': '[0-9.]+\s+([0-9.]+)',
            },
    )

    descriptors = []
    collect_stats()

    time.sleep(MIN_UPDATE_INTERVAL)
    collect_stats()

    for label in stats_descriptions:
        if squid_stats.has_key(label):
            if stats_descriptions[label]['type'] == 'string':
                d= {
                    'name': 'squid_' + label,
                    'call_back': get_stat,
                    'time_max': 60,
                    'value_type': "string",
                    'units': '',
                    'slope': "none",
                    'format': '%s',
                    'description': label,
                    'groups': 'squid',
                }
            elif stats_descriptions[label]['type'] == 'counter32':
                d= {
                    'name': 'squid_' + label,
                    'call_back': get_stat,
                    'time_max': 60,
                    'value_type': "float",
                    'units': stats_descriptions[label]['units'],
                    'slope': "positive",
                    'format': '%f',
                    'description': label,
                    'groups': 'squid',
                }
            elif stats_descriptions[label]['type'] == 'integer':
                d= {
                    'name': 'squid_' + label,
                    'call_back': get_stat,
                    'time_max': 60,
                    'value_type': "uint",
                    'units': stats_descriptions[label]['units'],
                    'slope': "both",
                    'format': '%u',
                    'description': label,
                    'groups': 'squid',
                }
            else:
                d= {
                'name': 'squid_' + label,
                'call_back': get_stat,
                'time_max': 60,
                'value_type': "float",
                'units': stats_descriptions[label]['units'],
                'slope': "both",
                'format': '%f',
                'description': label,
                'groups': 'squid',
                }

            d.update(stats_descriptions[label])

            descriptors.append(d)

        #else:
            #logging.error("skipped " + label)

    return descriptors

def metric_cleanup():
    #logging.shutdown()
    pass

#This code is for debugging and unit testing
if __name__ == '__main__':
    metric_init(None)
    for d in descriptors:
        v = d['call_back'](d['name'])
        if d['value_type'] == 'string':
            print 'value for %s is %s %s' % (d['name'],  v, d['units'])
        elif d['value_type'] == 'uint':
            print 'value for %s is %d %s' % (d['name'],  v, d['units'])
        else:
            print 'value for %s is %4.2f %s' % (d['name'],  v, d['units'])


text:
//
//  MissionInfoLayer.m
//  MagicEden
//
//  Created by Jeff Ye on 3/13/11.
//  Copyright 2011 USC Gamepipe. All rights reserved.
//

#import "MissionInfoLayer.h"

@implementation MissionInfoLayer

-(id) init
{
	if ((self = [super init]))
	{
		/*CCSprite* box = [CCSprite spriteWithFile:@"textbox.png"];
		CGSize size = [[CCDirector sharedDirector] winSize];
		box.position = ccp(size.width / 2, size.height / 2);
		[self addChild:box];*/
	}
	return self;
}

-(void) registerWithTouchDispatcher
{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:-1 swallowsTouches:YES];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint touchLoc = [self convertTouchToNodeSpace:touch];
	if (infoBox != nil)
	{
		if (CGRectContainsPoint([infoBox boundingBox], touchLoc))
			{
				[self removeAllChildrenWithCleanup:YES];
				self.isTouchEnabled = NO;
			}
	}
	return NO;
}

-(void) displayMissionResult: (NSString*) resultStr
{
	infoBox = [CCSprite spriteWithFile:@"mission_bg.png"];
	infoBox.vertexZ = 1000;
	CGSize size = [[CCDirector sharedDirector] winSize];
	infoBox.position = ccp(size.width / 2, size.height / 2);
	infoBox.scale = 0.8;
	[self addChild:infoBox z:1000];

	//CCLabelTTF* label = [CCLabelTTF labelWithString:resultStr fontName:@"Marker Felt" fontSize:50];

	CGSize labelSize = CGSizeMake([infoBox contentSize].width * 0.6, [infoBox contentSize].height * 0.6);
	CCLabelTTF* label = [CCLabelTTF labelWithString:resultStr dimensions:labelSize alignment:CCTextAlignmentCenter fontName:@"Marker Felt" fontSize:25];
	label.position = ccp(size.width / 2, size.height / 2 - 30);
	label.vertexZ = 1000;
	label.color = ccc3(93,56,19);
	[self addChild:label z:1000];

	self.isTouchEnabled = true;
}

-(void) dealloc
{
	[infoBox release];
	[super dealloc];
}

@end


text:
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone;

Alloy.Globals.icon = {
    paste: "/images/ic_menu_paste.png",
    archive: "/images/ic_menu_archive.png",
    del: "/images/ic_menu_delete.png",
    add: "/images/ic_menu_add.png",
    find: "/images/ic_menu_find.png",
    info: "/images/ic_menu_info_details.png",
    download: "/images/ic_menu_upload.png",
    settings: "/images/ic_sysbar_quicksettings.png",
    block: "/images/ic_menu_block.png",
    "goto": "/images/ic_menu_goto.png"
};

Alloy.Globals.close = function(win) {
    win && win.close && win.close();
    win = null;
};

Alloy.createController("index");


text:
<?
echo "$rootdir[dirname]

$filenameX   (Edit):             Show the Document

";

?>


text:
from __future__ import print_function

import json
import os
import sys

def print_file_tree(startpath):
    """ Prints a directory and its contents
    """
    for root, dirs, files in os.walk(startpath):

        # skip hidden dirs
        dirs[:] = [d for d in dirs if not d.startswith(".")]

        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)

        print('{}{}/'.format(indent, os.path.basename(root)))

        subindent = ' ' * 4 * (level + 1)
        for f in files:
            if not f.startswith("."):
                print('{}{}'.format(subindent, f))

def generate_lab_from_solution(ipynb_path):
    """ Strictly removes input ant output of code cells prefixed
        with #SOLUTION from a jupyter notebook.

        This is a little hacky, but keeps the nbs in sync easily
    """
    lab_file = ipynb_path.replace('-solution', '-lab')

    raw_nb = json.load(open(ipynb_path))

    def _is_solution_cell(c):
        # source is a list of strings representing each line
        return (c['cell_type'] == 'code' and
                len(c['source']) > 0 and
                c['source'][0].startswith("#SOLUTION"))

    no_sol_cells = [c for c in raw_nb['cells'] if not _is_solution_cell(c)]

    raw_nb["cells"] = no_sol_cells

    with open(lab_file, "w") as lab_out:
        json.dump(raw_nb, lab_out)

if __name__ == "__main__":
    generate_lab_from_solution(sys.argv[1])


text:
using Guitar32.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace TestProject1
{

    ///
    ///This is a test class for DisconnectedExceptionTest and is intended
    ///to contain all DisconnectedExceptionTest Unit Tests
    ///
    [TestClass()]
    public class DisconnectedExceptionTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext {
            get {
                return testContextInstance;
            }
            set {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for DisconnectedException Constructor
        ///
        [TestMethod()]
        public void DisconnectedExceptionConstructorTest() {
            DisconnectedException target = new DisconnectedException();
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
    }
}


text:
"""Natural Language Processing; Chart Parsing and PageRanking (Chapter 22-23)"""

from collections import defaultdict
from utils import weighted_choice
import urllib.request
import re

# ______________________________________________________________________________
# Grammars and Lexicons

def Rules(**rules):
    """Create a dictionary mapping symbols to alternative sequences.
    >>> Rules(A = "B C | D E")
    {'A': [['B', 'C'], ['D', 'E']]}
    """
    for (lhs, rhs) in rules.items():
        rules[lhs] = [alt.strip().split() for alt in rhs.split('|')]
    return rules

def Lexicon(**rules):
    """Create a dictionary mapping symbols to alternative words.
    >>> Lexicon(Article = "the | a | an")
    {'Article': ['the', 'a', 'an']}
    """
    for (lhs, rhs) in rules.items():
        rules[lhs] = [word.strip() for word in rhs.split('|')]
    return rules

class Grammar:

    def __init__(self, name, rules, lexicon):
        """A grammar has a set of rules and a lexicon."""
        self.name = name
        self.rules = rules
        self.lexicon = lexicon
        self.categories = defaultdict(list)
        for lhs in lexicon:
            for word in lexicon[lhs]:
                self.categories[word].append(lhs)

    def rewrites_for(self, cat):
        """Return a sequence of possible rhs's that cat can be rewritten as."""
        return self.rules.get(cat, ())

    def isa(self, word, cat):
        """Return True iff word is of category cat"""
        return cat in self.categories[word]

    def cnf_rules(self):
        """Returns the tuple (X, Y, Z) for rules in the form:
        X -> Y Z"""
        cnf = []
        for X, rules in self.rules.items():
            for (Y, Z) in rules:
                cnf.append((X, Y, Z))

        return cnf

    def generate_random(self, S='S'):
        """Replace each token in S by a random entry in grammar (recursively)."""
        import random

        def rewrite(tokens, into):
            for token in tokens:
                if token in self.rules:
                    rewrite(random.choice(self.rules[token]), into)
                elif token in self.lexicon:
                    into.append(random.choice(self.lexicon[token]))
                else:
                    into.append(token)
            return into

        return ' '.join(rewrite(S.split(), []))

    def __repr__(self):
        return '<Grammar {}>'.format(self.name)

def ProbRules(**rules):
    """Create a dictionary mapping symbols to alternative sequences,
    with probabilities.
    >>> ProbRules(A = "B C [0.3] | D E [0.7]")
    {'A': [(['B', 'C'], 0.3), (['D', 'E'], 0.7)]}
    """
    for (lhs, rhs) in rules.items():
        rules[lhs] = []
        rhs_separate = [alt.strip().split() for alt in rhs.split('|')]
        for r in rhs_separate:
            prob = float(r[-1][1:-1]) # remove brackets, convert to float
            rhs_rule = (r[:-1], prob)
            rules[lhs].append(rhs_rule)

    return rules

def ProbLexicon(**rules):
    """Create a dictionary mapping symbols to alternative words,
    with probabilities.
    >>> ProbLexicon(Article = "the [0.5] | a [0.25] | an [0.25]")
    {'Article': [('the', 0.5), ('a', 0.25), ('an', 0.25)]}
    """
    for (lhs, rhs) in rules.items():
        rules[lhs] = []
        rhs_separate = [word.strip().split() for word in rhs.split('|')]
        for r in rhs_separate:
            prob = float(r[-1][1:-1]) # remove brackets, convert to float
            word = r[:-1][0]
            rhs_rule = (word, prob)
            rules[lhs].append(rhs_rule)

    return rules

class ProbGrammar:

    def __init__(self, name, rules, lexicon):
        """A grammar has a set of rules and a lexicon.
        Each rule has a probability."""
        self.name = name
        self.rules = rules
        self.lexicon = lexicon
        self.categories = defaultdict(list)

        for lhs in lexicon:
            for word, prob in lexicon[lhs]:
                self.categories[word].append((lhs, prob))

    def rewrites_for(self, cat):
        """Return a sequence of possible rhs's that cat can be rewritten as."""
        return self.rules.get(cat, ())

    def isa(self, word, cat):
        """Return True iff word is of category cat"""
        return cat in [c for c, _ in self.categories[word]]

    def cnf_rules(self):
        """Returns the tuple (X, Y, Z, p) for rules in the form:
        X -> Y Z [p]"""
        cnf = []
        for X, rules in self.rules.items():
            for (Y, Z), p in rules:
                cnf.append((X, Y, Z, p))

        return cnf

    def generate_random(self, S='S'):
        """Replace each token in S by a random entry in grammar (recursively).
        Returns a tuple of (sentence, probability)."""
        import random

        def rewrite(tokens, into):
            for token in tokens:
                if token in self.rules:
                    non_terminal, prob = weighted_choice(self.rules[token])
                    into[1] *= prob
                    rewrite(non_terminal, into)
                elif token in self.lexicon:
                    terminal, prob = weighted_choice(self.lexicon[token])
                    into[0].append(terminal)
                    into[1] *= prob
                else:
                    into[0].append(token)
            return into

        rewritten_as, prob = rewrite(S.split(), [[], 1])
        return (' '.join(rewritten_as), prob)

    def __repr__(self):
        return '<Grammar {}>'.format(self.name)

E0 = Grammar('E0',
             Rules(  # Grammar for E_0 [Figure 22.4]
                 S='NP VP | S Conjunction S',
                 NP='Pronoun | Name | Noun | Article Noun | Digit Digit | NP PP | NP RelClause',
                 VP='Verb | VP NP | VP Adjective | VP PP | VP Adverb',
                 PP='Preposition NP',
                 RelClause='That VP'),

             Lexicon(  # Lexicon for E_0 [Figure 22.3]
                 Noun="stench | breeze | glitter | nothing | wumpus | pit | pits | gold | east",
                 Verb="is | see | smell | shoot | fell | stinks | go | grab | carry | kill | turn | feel",  # noqa
                 Adjective="right | left | east | south | back | smelly",
                 Adverb="here | there | nearby | ahead | right | left | east | south | back",
                 Pronoun="me | you | I | it",
                 Name="John | Mary | Boston | Aristotle",
                 Article="the | a | an",
                 Preposition="to | in | on | near",
                 Conjunction="and | or | but",
                 Digit="0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9",
                 That="that"
             ))

E_ = Grammar('E_',  # Trivial Grammar and lexicon for testing
             Rules(
                 S='NP VP',
                 NP='Art N | Pronoun',
                 VP='V NP'),

             Lexicon(
                 Art='the | a',
                 N='man | woman | table | shoelace | saw',
                 Pronoun='I | you | it',
                 V='saw | liked | feel'
             ))

E_NP_ = Grammar('E_NP_',  # Another Trivial Grammar for testing
                Rules(NP='Adj NP | N'),
                Lexicon(Adj='happy | handsome | hairy',
                        N='man'))

E_Prob = ProbGrammar('E_Prob', # The Probabilistic Grammar from the notebook
                     ProbRules(
                         S="NP VP [0.6] | S Conjunction S [0.4]",
                         NP="Pronoun [0.2] | Name [0.05] | Noun [0.2] | Article Noun [0.15] \
                             | Article Adjs Noun [0.1] | Digit [0.05] | NP PP [0.15] | NP RelClause [0.1]",
                         VP="Verb [0.3] | VP NP [0.2] | VP Adjective [0.25] | VP PP [0.15] | VP Adverb [0.1]",
                         Adjs="Adjective [0.5] | Adjective Adjs [0.5]",
                         PP="Preposition NP [1]",
                         RelClause="RelPro VP [1]"
                     ),
                     ProbLexicon(
                         Verb="is [0.5] | say [0.3] | are [0.2]",
                         Noun="robot [0.4] | sheep [0.4] | fence [0.2]",
                         Adjective="good [0.5] | new [0.2] | sad [0.3]",
                         Adverb="here [0.6] | lightly [0.1] | now [0.3]",
                         Pronoun="me [0.3] | you [0.4] | he [0.3]",
                         RelPro="that [0.5] | who [0.3] | which [0.2]",
                         Name="john [0.4] | mary [0.4] | peter [0.2]",
                         Article="the [0.5] | a [0.25] | an [0.25]",
                         Preposition="to [0.4] | in [0.3] | at [0.3]",
                         Conjunction="and [0.5] | or [0.2] | but [0.3]",
                         Digit="0 [0.35] | 1 [0.35] | 2 [0.3]"
                     ))

E_Chomsky = Grammar('E_Prob_Chomsky', # A Grammar in Chomsky Normal Form
                    Rules(
                       S='NP VP',
                       NP='Article Noun | Adjective Noun',
                       VP='Verb NP | Verb Adjective',
                    ),
                    Lexicon(
                       Article='the | a | an',
                       Noun='robot | sheep | fence',
                       Adjective='good | new | sad',
                       Verb='is | say | are'
                    ))

E_Prob_Chomsky = ProbGrammar('E_Prob_Chomsky', # A Probabilistic Grammar in CNF
                             ProbRules(
                                S='NP VP [1]',
                                NP='Article Noun [0.6] | Adjective Noun [0.4]',
                                VP='Verb NP [0.5] | Verb Adjective [0.5]',
                             ),
                             ProbLexicon(
                                Article='the [0.5] | a [0.25] | an [0.25]',
                                Noun='robot [0.4] | sheep [0.4] | fence [0.2]',
                                Adjective='good [0.5] | new [0.2] | sad [0.3]',
                                Verb='is [0.5] | say [0.3] | are [0.2]'
                             ))
E_Prob_Chomsky_ = ProbGrammar('E_Prob_Chomsky_',
                             ProbRules(
                                S='NP VP [1]',
                                NP='NP PP [0.4] | Noun Verb [0.6]',
                                PP='Preposition NP [1]',
                                VP='Verb NP [0.7] | VP PP [0.3]',
                                ),
                             ProbLexicon(
                                Noun='astronomers [0.18] | eyes [0.32] | stars [0.32] | telescopes [0.18]',
                                Verb='saw [0.5] | \'\' [0.5]',
                                Preposition='with [1]'
                                ))

# ______________________________________________________________________________
# Chart Parsing

class Chart:

    """Class for parsing sentences using a chart data structure.
    >>> chart = Chart(E0)
    >>> len(chart.parses('the stench is in 2 2'))
    1
    """

    def __init__(self, grammar, trace=False):
        """A datastructure for parsing a string; and methods to do the parse.
        self.chart[i] holds the edges that end just before the i'th word.
        Edges are 5-element lists of [start, end, lhs, [found], [expects]]."""
        self.grammar = grammar
        self.trace = trace

    def parses(self, words, S='S'):
        """Return a list of parses; words can be a list or string."""
        if isinstance(words, str):
            words = words.split()
        self.parse(words, S)
        # Return all the parses that span the whole input
        # 'span the whole input' => begin at 0, end at len(words)
        return [[i, j, S, found, []]
                for (i, j, lhs, found, expects) in self.chart[len(words)]
                # assert j == len(words)
                if i == 0 and lhs == S and expects == []]

    def parse(self, words, S='S'):
        """Parse a list of words; according to the grammar.
        Leave results in the chart."""
        self.chart = [[] for i in range(len(words)+1)]
        self.add_edge([0, 0, 'S_', [], [S]])
        for i in range(len(words)):
            self.scanner(i, words[i])
        return self.chart

    def add_edge(self, edge):
        """Add edge to chart, and see if it extends or predicts another edge."""
        start, end, lhs, found, expects = edge
        if edge not in self.chart[end]:
            self.chart[end].append(edge)
            if self.trace:
                print('Chart: added {}'.format(edge))
            if not expects:
                self.extender(edge)
            else:
                self.predictor(edge)

    def scanner(self, j, word):
        """For each edge expecting a word of this category here, extend the edge."""
        for (i, j, A, alpha, Bb) in self.chart[j]:
            if Bb and self.grammar.isa(word, Bb[0]):
                self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])

    def predictor(self, edge):
        """Add to chart any rules for B that could help extend this edge."""
        (i, j, A, alpha, Bb) = edge
        B = Bb[0]
        if B in self.grammar.rules:
            for rhs in self.grammar.rewrites_for(B):
                self.add_edge([j, j, B, [], rhs])

    def extender(self, edge):
        """See what edges can be extended by this edge."""
        (j, k, B, _, _) = edge
        for (i, j, A, alpha, B1b) in self.chart[j]:
            if B1b and B == B1b[0]:
                self.add_edge([i, k, A, alpha + [edge], B1b[1:]])

# ______________________________________________________________________________
# CYK Parsing

def CYK_parse(words, grammar):
    """ [Figure 23.5] """
    # We use 0-based indexing instead of the book's 1-based.
    N = len(words)
    P = defaultdict(float)

    # Insert lexical rules for each word.
    for (i, word) in enumerate(words):
        for (X, p) in grammar.categories[word]:
            P[X, i, 1] = p

    # Combine first and second parts of right-hand sides of rules,
    # from short to long.
    for length in range(2, N+1):
        for start in range(N-length+1):
            for len1 in range(1, length):  # N.B. the book incorrectly has N instead of length
                len2 = length - len1
                for (X, Y, Z, p) in grammar.cnf_rules():
                    P[X, start, length] = max(P[X, start, length],
                                              P[Y, start, len1] * P[Z, start+len1, len2] * p)

    return P

# ______________________________________________________________________________
# Page Ranking

# First entry in list is the base URL, and then following are relative URL pages
examplePagesSet = ["https://en.wikipedia.org/wiki/", "Aesthetics", "Analytic_philosophy",
                   "Ancient_Greek", "Aristotle", "Astrology", "Atheism", "Baruch_Spinoza",
                   "Belief", "Betrand Russell", "Confucius", "Consciousness",
                   "Continental Philosophy", "Dialectic", "Eastern_Philosophy",
                   "Epistemology", "Ethics", "Existentialism", "Friedrich_Nietzsche",
                   "Idealism", "Immanuel_Kant", "List_of_political_philosophers", "Logic",
                   "Metaphysics", "Philosophers", "Philosophy", "Philosophy_of_mind", "Physics",
                   "Plato", "Political_philosophy", "Pythagoras", "Rationalism",
                   "Social_philosophy", "Socrates", "Subjectivity", "Theology",
                   "Truth", "Western_philosophy"]

def loadPageHTML(addressList):
    """Download HTML page content for every URL address passed as argument"""
    contentDict = {}
    for addr in addressList:
        with urllib.request.urlopen(addr) as response:
            raw_html = response.read().decode('utf-8')
            # Strip raw html of unnessecary content. Basically everything that isn't link or text
            html = stripRawHTML(raw_html)
            contentDict[addr] = html
    return contentDict

def initPages(addressList):
    """Create a dictionary of pages from a list of URL addresses"""
    pages = {}
    for addr in addressList:
        pages[addr] = Page(addr)
    return pages

def stripRawHTML(raw_html):
    """Remove the <head> section of the HTML which contains links to stylesheets etc.,
    and remove all other unnessecary HTML"""
    # TODO: Strip more out of the raw html
    return re.sub("<head>.*?</head>", "", raw_html, flags=re.DOTALL)  # remove <head> section

def determineInlinks(page):
    """Given a set of pages that have their outlinks determined, we can fill
    out a page's inlinks by looking through all other page's outlinks"""
    inlinks = []
    for addr, indexPage in pagesIndex.items():
        if page.address == indexPage.address:
            continue
        elif page.address in indexPage.outlinks:
            inlinks.append(addr)
    return inlinks

def findOutlinks(page, handleURLs=None):
    """Search a page's HTML content for URL links to other pages"""
    urls = re.findall(r'href=[\'"]?([^\'" >]+)', pagesContent[page.address])
    if handleURLs:
        urls = handleURLs(urls)
    return urls

def onlyWikipediaURLS(urls):
    """Some example HTML page data is from wikipedia. This function converts
    relative wikipedia links to full wikipedia URLs"""
    wikiURLs = [url for url in urls if url.startswith('/wiki/')]
    return ["https://en.wikipedia.org"+url for url in wikiURLs]

# ______________________________________________________________________________
# HITS Helper Functions

def expand_pages(pages):
    """Adds in every page that links to or is linked from one of
    the relevant pages."""
    expanded = {}
    for addr, page in pages.items():
        if addr not in expanded:
            expanded[addr] = page
        for inlink in page.inlinks:
            if inlink not in expanded:
                expanded[inlink] = pagesIndex[inlink]
        for outlink in page.outlinks:
            if outlink not in expanded:
                expanded[outlink] = pagesIndex[outlink]
    return expanded

def relevant_pages(query):
    """Relevant pages are pages that contain all of the query words. They are obtained by
    intersecting the hit lists of the query words."""
    hit_intersection = {addr for addr in pagesIndex}
    query_words = query.split()
    for query_word in query_words:
        hit_list = set()
        for addr in pagesIndex:
            if query_word.lower() in pagesContent[addr].lower():
                hit_list.add(addr)
        hit_intersection = hit_intersection.intersection(hit_list)
    return {addr: pagesIndex[addr] for addr in hit_intersection}

def normalize(pages):
    """Normalize divides each page's score by the sum of the squares of all
    pages' scores (separately for both the authority and hub scores).
    """
    summed_hub = sum(page.hub**2 for _, page in pages.items())
    summed_auth = sum(page.authority**2 for _, page in pages.items())
    for _, page in pages.items():
        page.hub /= summed_hub**0.5
        page.authority /= summed_auth**0.5

class ConvergenceDetector(object):
    """If the hub and authority values of the pages are no longer changing, we have
    reached a convergence and further iterations will have no effect. This detects convergence
    so that we can stop the HITS algorithm as early as possible."""
    def __init__(self):
        self.hub_history = None
        self.auth_history = None

    def __call__(self):
        return self.detect()

    def detect(self):
        curr_hubs = [page.hub for addr, page in pagesIndex.items()]
        curr_auths = [page.authority for addr, page in pagesIndex.items()]
        if self.hub_history is None:
            self.hub_history, self.auth_history = [], []
        else:
            diffsHub = [abs(x-y) for x, y in zip(curr_hubs, self.hub_history[-1])]
            diffsAuth = [abs(x-y) for x, y in zip(curr_auths, self.auth_history[-1])]
            aveDeltaHub  = sum(diffsHub)/float(len(pagesIndex))
            aveDeltaAuth = sum(diffsAuth)/float(len(pagesIndex))
            if aveDeltaHub < 0.01 and aveDeltaAuth < 0.01:  # may need tweaking
                return True
        if len(self.hub_history) > 2:  # prevent list from getting long
            del self.hub_history[0]
            del self.auth_history[0]
        self.hub_history.append([x for x in curr_hubs])
        self.auth_history.append([x for x in curr_auths])
        return False

def getInlinks(page):
    if not page.inlinks:
        page.inlinks = determineInlinks(page)
    return [addr for addr, p in pagesIndex.items() if addr in page.inlinks]

def getOutlinks(page):
    if not page.outlinks:
        page.outlinks = findOutlinks(page)
    return [addr for addr, p in pagesIndex.items() if addr in page.outlinks]

# ______________________________________________________________________________
# HITS Algorithm

class Page(object):
    def __init__(self, address, inlinks=None, outlinks=None, hub=0, authority=0):
        self.address = address
        self.hub = hub
        self.authority = authority
        self.inlinks = inlinks
        self.outlinks = outlinks

pagesContent = {}  # maps Page relative or absolute URL/location to page's HTML content
pagesIndex = {}
convergence = ConvergenceDetector()  # assign function to variable to mimic pseudocode's syntax

def HITS(query):
    """The HITS algorithm for computing hubs and authorities with respect to a query."""
    pages = expand_pages(relevant_pages(query))
    for p in pages.values():
        p.authority = 1
        p.hub = 1
    while not convergence():
        authority = {p: pages[p].authority for p in pages}
        hub = {p: pages[p].hub for p in pages}
        for p in pages:
            # p.authority ← ∑i Inlinki(p).Hub
            pages[p].authority = sum(hub[x] for x in getInlinks(pages[p]))
            # p.hub ← ∑i Outlinki(p).Authority
            pages[p].hub = sum(authority[x] for x in getOutlinks(pages[p]))
        normalize(pages)
    return pages


text:
require 'rails_helper'

RSpec.describe Story, :type => :model do
  #let(:subject) { build(:story_with_project) }
  #it { should belong_to :project }
  #it { should validate_presence_of :title }
  #it { should validate_uniqueness_of(:title).scoped_to(:project_id) }
end


text:
package org.ovirt.engine.ui.uicommon.models.users;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.core.common.*;

import org.ovirt.engine.ui.uicommon.models.tags.*;
import org.ovirt.engine.ui.uicommon.validation.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;

@SuppressWarnings("unused")
public class UserPermissionModel extends Model
{

	private Guid privateId = new Guid();
	public Guid getId()
	{
		return privateId;
	}
	public void setId(Guid value)
	{
		privateId = value;
	}

	private ListModel privateRole;
	public ListModel getRole()
	{
		return privateRole;
	}
	public void setRole(ListModel value)
	{
		privateRole = value;
	}

	private java.util.List<TagModel> tags;
	public java.util.List<TagModel> getTags()
	{
		return tags;
	}
	public void setTags(java.util.List<TagModel> value)
	{
		if (tags != value)
		{
			tags = value;
			OnPropertyChanged(new PropertyChangedEventArgs("Tags"));
		}
	}

	public UserPermissionModel()
	{
		setRole(new ListModel());
	}

	public boolean Validate()
	{
		getRole().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });

		return getRole().getIsValid();
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE RankNTypes #-}
module Web.Stripe.Test.Account where

import           Data.Either
import           Test.Hspec
import           Web.Stripe.Test.Prelude
import           Web.Stripe.Account

accountTests :: StripeSpec
accountTests stripe = do
  describe "Account tests" $ do
    it "Succesfully retrieves account information" $ do
      result <- stripe $ do d <- getAccountDetails
                            return d
      result `shouldSatisfy` isRight


text:
package ds.framework.v4.db;

import java.util.ArrayList;

public class Condition {

	public static final int EQUALS = 0;
	public static final int LOWER = 1;
	public static final int HIGHER = 2;
	public static final int EQUALS_OR_LOWER = 3;
	public static final int EQUALS_OR_HIGHER = 4;

	public static final int IN = 9;
	public static final int BETWEEN = 10;

    public static final int IS = 11;

	String mField;
	int mRelation;
	String mStringRelation;
	String mStrValue;
	Long mLongValue;
	Float mFloatValue;
	int[] mIntArrayValue;
	Object[] mArrayValue;

    /**
     *
     * @param field
     * @param value
     */
	public Condition(String field, String value) {
		this(field, EQUALS, value);
	}

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, String relation, String value) {
		mField = field;
		mStringRelation = relation;
		mStrValue = value;
	}

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, int relation, String value) {
		mField = field;
		mRelation = relation;
		mStringRelation = null;
		mStrValue = value;
	}

    /**
     *
     * @param field
     * @param value
     */
	public Condition(String field, int value) {
		this(field, EQUALS, value);
	}

    /**
     *
     * @param field
     * @param value
     */
    public Condition(String field, long value) {
        this(field, EQUALS, value);
    }

    /**
     *
     * @param field
     * @param value
     */
    public Condition(String field, boolean value) {
        this(field, value ? HIGHER : EQUALS, 0);
    }

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, int relation, int value) {
		this(field, relation, (long) value);
	}

	/**
	 *
	 * @param field
	 * @param relation
	 * @param value
	 */
	public Condition(String field, int relation, long value) {
		mField = field;
		mRelation = relation;
		mStringRelation = null;
		mLongValue = value;
	}

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, String relation, int value) {
        this(field, relation, (long) value);
    }

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
    public Condition(String field, String relation, long value) {
		mField = field;
		mStringRelation = relation;
		mLongValue = value;
	}

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, int relation, float value) {
		mField = field;
		mRelation = relation;
		mStringRelation = null;
		mFloatValue = value;
	}

    /**
     *
     * @param field
     * @param relation
     * @param value
     */
	public Condition(String field, String relation, float value) {
		mField = field;
		mStringRelation = relation;
		mFloatValue = value;
	}

    /**
     *
     * @param field
     * @param values
     */
	public Condition(String field, int[] values) {
		mField = field;
		mRelation = IN;
		mStringRelation = null;
		mIntArrayValue = values;
	}

    /**
     *
     * @param field
     * @param values
     */
	public Condition(String field, ArrayList<Integer> values) {
		final int[] intValues = new int[values.size()];

		int at = 0;
		for(Integer value : values) {
			intValues[at++] = value;
		}

		mField = field;
		mRelation = IN;
		mStringRelation = null;
		mIntArrayValue =intValues;
	}

    /**
     *
     * @param field
     * @param values
     */
	public Condition(String field, Object[] values) {
		mField = field;
		mRelation = IN;
		mStringRelation = null;
		mArrayValue = values;
	}

    /**
     *
     * @return
     */
	@Override
	public String toString() {
		String ret = DbQuery.quoteName(mField);
		if (mStringRelation != null) {
			ret += " " + mStringRelation + " ";
		} else switch(mRelation) {
			case IN:
				ret += " IN ";
				break;

			case LOWER:
				ret += " < ";
				break;

			case HIGHER:
				ret += " > ";
				break;

			case EQUALS_OR_LOWER:
				ret += " <= ";
				break;

			case EQUALS_OR_HIGHER:
				ret += " >= ";
				break;

            case IS:
                ret += " IS ";
                break;

			case EQUALS:
			default:
				ret += " = ";
				break;
		}
		if (mStrValue != null) {
			ret += DbQuery.quoteNameOrValue(mStrValue);
		} else if (mLongValue != null) {
			ret += mLongValue;
		} else if (mFloatValue != null) {
			ret += mFloatValue;
		} else if (mIntArrayValue != null) {
			ret += DbQuery.quoteValue(mIntArrayValue);
		} else if (mArrayValue != null) {
			ret += DbQuery.quoteValue(mArrayValue);
		} else if (mStrValue == null) {
			ret += "NULL";
		}

		return ret;
	}
}


text:
@interface TSDKPartnerPreferences : TSDKCollectionObject

@property (nonatomic, assign) BOOL canDisplayPartner; //Example: 0
@property (nonatomic, strong, nullable) NSString * partnerName; //Example: **NULL**
@property (nonatomic, strong, nullable) NSString * userId; //Example: <null>
@property (nonatomic, assign) BOOL userIsPartner; //Example: 0
@property (nonatomic, strong, nullable) NSString * partnerId; //Example: <null>
@property (nonatomic, copy, nullable) NSURL * reigningChampsMobileUrl;

@end