text:
using System;

namespace Serenity.Data
{
    public static class SqlDialectExtensions
    {
        public static bool IsCaseSensitive(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.Firebird);
        }

        public static bool PrefixUnicodeStringsWithN(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.MsSql);
        }

        public static bool UseReturningIdentity(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.Firebird);
        }

        public static bool UseScopeIdentity(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.MsSql) || dialect.HasFlag(SqlDialect.Sqlite);
        }

        public static string ScopeIdentityExpression(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.MsSql))
            {
                return "SCOPE_IDENTITY()";
            }
            if (dialect.HasFlag(SqlDialect.Sqlite))
            {
                return "last_insert_rowid()";
            }

            throw new NotImplementedException();
        }

        public static bool MultipleResultsets(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.MsSql);
        }

        public static bool CanUseRowNumber(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.MsSql) && dialect >= SqlDialect.MsSql2005;
        }

        public static bool CanUseOffsetFetch(this SqlDialect dialect)
        {
            return (dialect.HasFlag(SqlDialect.MsSql) && dialect >= SqlDialect.MsSql2012) ||
                dialect.HasFlag(SqlDialect.Sqlite);
        }

        public static bool NeedsExecuteBlockStatement(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.Firebird);
        }

        public static string OffsetFormat(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Sqlite))
                return " OFFSET {0}";

            return " OFFSET {0} ROWS";
        }

        public static string OffsetFetchFormat(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Sqlite))
                return " LIMIT {1} OFFSET {0}";

            return " OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY";
        }

        public static string TakeKeyword(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Firebird))
                return "FIRST";

            if (dialect.HasFlag(SqlDialect.MsSql))
                return "TOP";

            if (dialect.HasFlag(SqlDialect.Sqlite))
                return "LIMIT";

            throw new InvalidOperationException();
        }

        public static bool UseTakeAtEnd(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.Sqlite);
        }

        public static bool CanUseSkipKeyword(this SqlDialect dialect)
        {
            return dialect.HasFlag(SqlDialect.Firebird);
        }

        public static string SkipKeyword(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Firebird))
                return "SKIP";

            throw new InvalidOperationException();
        }

        public static string DateFormat(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Firebird))
                return "\\'yyyy'-'MM'-'dd\\'";

            return "\\'yyyyMMdd\\'";
        }

        public static string DateTimeFormat(this SqlDialect dialect)
        {
            if (dialect.HasFlag(SqlDialect.Firebird))
                return "\\'yyyy'-'MM'-'dd HH':'mm':'ss'.'fff\\'";

            return "\\'yyyy'-'MM'-'ddTHH':'mm':'ss'.'fff\\'";
        }

        public static string TimeFormat(this SqlDialect dialect)
        {
            return "\\'HH':'mm':'ss\\'";
        }
    }
}


text:
package com.hevelian.identity.users.api.dto;

import javax.validation.constraints.NotNull;
import com.hevelian.identity.users.model.User;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserRequestDTO extends UserCredentialsRequestDTO {
  @NotNull
  private Boolean enabled;

  @Override
  public User toEntity() {
    User user = new User();
    user.setEnabled(getEnabled());
    user.setName(getName());
    user.setPassword(getPassword());
    user.setDeletable(true);
    return user;
  }

}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Text;

namespace Marklight.Themes
{
    /// <summary>
    /// Parses CSS text into objects.
    /// </summary>
    public class CssParser
    {
        #region Private Fields

        private readonly string _css;
        private int _index;
        private ParseMode _mode;
        private readonly StringBuilder _buffer = new StringBuilder(32);
        private readonly List<Selectors> _selectors = new List<Selectors>(50);

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor.
        /// </summary>
        public CssParser(string css) {
            _css = css;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Parse the CSS text that was passed into the constructor and return the results.
        /// </summary>
        public List<Selectors> ParseCss() {

            Selectors currSelectors = null;
            Property currProperty = null;

            for (_index = 0; _index < _css.Length; _index++)
            {
                SkipWhiteSpace();
                var ch = Char();

                // check for comments
                if (ch == '/')
                {
                    if (Char(1) != '*')
                        throw new CssParseException("Illegal character detected in CSS.");

                    SkipComment();
                }
                // parse selectors
                else if (_mode == ParseMode.None)
                {
                    if (ch == '}')
                        break;

                    currSelectors = ParseSelectors();
                    if (currSelectors == null)
                    {
                        continue;
                    }

                    _mode = ParseMode.ParseProperty;
                }
                // parse property name
                else if (_mode == ParseMode.ParseProperty)
                {
                    currProperty = ParseProperty();

                    if (currProperty.IsLast)
                    {
                        _selectors.Add(currSelectors);
                        currSelectors = null;
                        currProperty = null;
                        _mode = ParseMode.None;
                        continue;
                    }

                    _mode = ParseMode.ParsePropertyValue;
                }
                // parse property value
                else if (_mode == ParseMode.ParsePropertyValue)
                {
                    var property = ParsePropertyValue(currProperty);

                    if (currProperty != null && currSelectors != null)
                    {
                        currSelectors.PropertyList.Add(currProperty);
                        currProperty = null;
                    }

                    if (property.IsLast)
                    {
                        _selectors.Add(currSelectors);
                        currSelectors = null;
                        _mode = ParseMode.None;
                    }
                    else
                    {
                        _mode = ParseMode.ParseProperty;
                    }
                }
            }

            return _selectors;
        }

        private void SkipWhiteSpace() {
            var hasReturn = false;
            for (; _index < _css.Length; _index++)
            {
                var ch = Char();

                if (" \t\n\r".IndexOf(ch) != -1)
                {
                    if (!hasReturn && " \t".IndexOf(ch) == -1)
                        hasReturn = true;
                    continue;
                }
                break;
            }
        }

        private void SkipComment() {
            for (; _index < _css.Length; _index++)
            {
                var ch = Char();

                if (ch == '/' && Char(-1) == '*') {
                    break;
                }
            }
        }

        private char Char(int offset = 0) {
            if (_index + offset < 0 || _index + offset >= _css.Length)
                return (char) 0;

            return _css[_index + offset];
        }

        private void TrimBuffer() {
            while (_buffer.Length > 0
                   && " \r\n\t".IndexOf(_buffer[_buffer.Length - 1]) != -1)
            {
                _buffer.Length = _buffer.Length - 1;
            }
        }

        private Selectors ParseSelectors() {
            _buffer.Length = 0;
            var result = new Selectors();
            var selectors = result.SelectorList;
            var isStarted = false;

            for (; _index < _css.Length; _index++)
            {
                var ch = Char();
                if (ch == '{')
                {
                    TrimBuffer();
                    if (_buffer.Length > 0)
                        selectors.Add(new CssSelector(_buffer.ToString()));
                    return result;
                }

                if (ch == ',')
                {
                    TrimBuffer();
                    selectors.Add(new CssSelector(_buffer.ToString()));
                    _buffer.Length = 0;
                    isStarted = false;
                    continue;
                }

                if (ch == '}')
                    break;

                // don't add leading whitespace
                if (!isStarted && " \r\n\t".IndexOf(ch) != -1)
                    continue;

                isStarted = true;
                _buffer.Append(ch);
            }

            TrimBuffer();
            if (_buffer.Length != 0)
            {
                throw new CssParseException("End of document reached prematurely while parsing css.");
            }

            return null;
        }

        private Property ParseProperty() {

            var property = new Property();
            _buffer.Length = 0;

            for (; _index < _css.Length; _index++)
            {
                var ch = Char();

                if (ch == ':')
                {
                    TrimBuffer();
                    property.Name = _buffer.ToString();
                    return property;
                }

                if (ch == '}')
                {
                    TrimBuffer();
                    if (_buffer.Length != 0)
                    {
                        throw new CssParseException("Premature end while parsing property: " + _buffer);
                    }

                    property.Name = _buffer.ToString();
                    property.IsLast = true;
                    return property;
                }

                _buffer.Append(ch);
            }

            throw new CssParseException("End of document reached prematurely while parsing property: " + _buffer);
        }

        private Property ParsePropertyValue(Property property)
        {
            _buffer.Length = 0;
            var mode = ValueParseMode.Value;
            var quote = (char) 0;
            var ch = (char) 0;

            for (; _index < _css.Length; _index++)
            {
                ch = Char();

                if (ch == '\'' || ch == '"')
                {
                    if (mode == ValueParseMode.Literal && quote == ch)
                    {
                        mode = ValueParseMode.Value;
                        continue;
                    }

                    if (mode == ValueParseMode.Value)
                    {
                        mode = ValueParseMode.Literal;
                        quote = ch;
                        continue;
                    }
                }
                else if ((ch == ';' || ch == '}') && mode == ValueParseMode.Value)
                {
                    break;
                }

                _buffer.Append(ch);
            }

            property.Value = _buffer.ToString();
            property.IsLast = property.IsLast || ch == '}';
            return property;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Get the parse results.
        /// </summary>
        public List<Selectors> ParseResult
        {
            get { return _selectors; }
        }

        #endregion

        #region Enums

        private enum ParseMode
        {
            None,
            ParseProperty,
            ParsePropertyValue
        }

        private enum ValueParseMode
        {
            Value,
            Literal
        }

        #endregion

        #region Classes

        public class Selectors
        {
            public readonly List<CssSelector> SelectorList = new List<CssSelector>();
            public readonly List<Property> PropertyList = new List<Property>();
        }

        public class Property
        {
            public string Name;
            public string Value;
            public bool IsLast;
        }

        #endregion
    }
}


text:
package edn

import (
	"bytes"
	"code.google.com/p/go-uuid/uuid"
	"container/list"
	"encoding"
	"encoding/base64"
	"fmt"
	"math"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode/utf8"
)

// Marshal returns the EDN encoding of v.
//
// Marshal traverses the value v recursively, using the following
// type-dependent default encodings:
// (see https://github.com/edn-format/edn)
func Marshal(v interface{}) ([]byte, error) {
	e := &encodeState{}
	err := e.marshal(v)
	if err != nil {
		return nil, err
	}
	return e.Bytes(), nil
}

// MustMarshal is a panicky version of Marshal.
func MustMarshal(v interface{}) []byte {
	if data, err := Marshal(v); err == nil {
		return data
	} else {
		panic(err)
	}
}

// An UnsupportedTypeError is returned by Marshal when attempting
// to encode an unsupported value type.
type UnsupportedTypeError struct {
	Type reflect.Type
}

func (e *UnsupportedTypeError) Error() string {
	return "edn: unsupported type: " + e.Type.String()
}

type UnsupportedValueError struct {
	Value reflect.Value
	Str   string
}

func (e *UnsupportedValueError) Error() string {
	return "edn: unsupported value: " + e.Str
}

type MarshalerError struct {
	Type reflect.Type
	Err  error
}

func (e *MarshalerError) Error() string {
	return "edn: error calling MarshalEDN for type " + e.Type.String() + ": " + e.Err.Error()
}

// An encodeState encodes EDN into a bytes.Buffer.
type encodeState struct {
	bytes.Buffer // accumulated output
	scratch      [64]byte
}

func (e *encodeState) marshal(v interface{}) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}
			if s, ok := r.(string); ok {
				panic(s)
			}
			err = r.(error)
		}
	}()
	e.reflectValue(reflect.ValueOf(v))
	return nil
}

func (e *encodeState) error(err error) {
	panic(err)
}

func (e *encodeState) reflectValue(v reflect.Value) {
	valueEncoder(v)(e, v)
}

// ensureUtf8 produces a valid utf-8 encoded string. In case its input is
// invalid, all bad characters are replaced with \ufffd (aka "error"
// rune).
func ensureUtf8(s string) string {
	if utf8.ValidString(s) {
		return s
	}
	buf := bytes.Buffer{}
	start := 0
	for i := 0; i < len(s); {
		if s[i] < utf8.RuneSelf {
			i++
			continue
		}
		c, size := utf8.DecodeRuneInString(s[i:])
		if c == utf8.RuneError && size == 1 {
			if start < i {
				buf.WriteString(s[start:i])
			}
			buf.WriteRune(utf8.RuneError)
			i++
			start = i
			continue
		}
		i += size
	}
	if start < len(s) {
		buf.WriteString(s[start:])
	}
	return buf.String()
}

func (e *encodeState) string(s string) (int, error) {
	len0 := e.Len()
	// Quote approximates Java/Clojure string literal representation,
	// but not quite. TODO: follow Java spec exactly.
	e.WriteString(strconv.Quote(ensureUtf8(s)))
	return e.Len() - len0, nil
}

func (e *encodeState) stringBytes(s []byte) (int, error) {
	len0 := e.Len()
	e.WriteString(fmt.Sprintf("%#v", string(s)))
	return e.Len() - len0, nil
}

type encoderFunc func(e *encodeState, v reflect.Value)

var encoderCache struct {
	sync.RWMutex
	m map[reflect.Type]encoderFunc
}

func valueEncoder(v reflect.Value) encoderFunc {
	if !v.IsValid() {
		return invalidValueEncoder
	}
	return typeEncoder(v.Type())
}

func typeEncoder(t reflect.Type) encoderFunc {
	encoderCache.RLock()
	f := encoderCache.m[t]
	encoderCache.RUnlock()
	if f != nil {
		return f
	}

	// To deal with recursive types, populate the map with an
	// indirect func before we build it. This type waits on the
	// real func (f) to be ready and then calls it.  This indirect
	// func is only used for recursive types.
	encoderCache.Lock()
	if encoderCache.m == nil {
		encoderCache.m = make(map[reflect.Type]encoderFunc)
	}
	var wg sync.WaitGroup
	wg.Add(1)
	encoderCache.m[t] = func(e *encodeState, v reflect.Value) {
		wg.Wait()
		f(e, v)
	}
	encoderCache.Unlock()

	// Compute fields without lock.
	// Might duplicate effort but won't hold other computations back.
	f = newTypeEncoder(t, true)
	wg.Done()
	encoderCache.Lock()
	encoderCache.m[t] = f
	encoderCache.Unlock()
	return f
}

var (
	timeType          = reflect.TypeOf(time.Time{})
	textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
	listType          = reflect.TypeOf(list.List{})
	uuidType          = reflect.TypeOf(uuid.UUID{})
)

// newTypeEncoder constructs an encoderFunc for a type.
// The returned encoder only checks CanAddr when allowAddr is true.
func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
	// Special case for time.Time because it already implements
	// TextMarshaler which is not what we want as EDN.
	if t == timeType {
		return timeEncoder
	}
	if t.Kind() == reflect.Ptr && t.Elem() == timeType {
		return newPtrEncoder(t)
	}

	if t.Implements(textMarshalerType) {
		return textMarshalerEncoder
	}
	if t.Kind() != reflect.Ptr && allowAddr {
		if reflect.PtrTo(t).Implements(textMarshalerType) {
			return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
		}
	}

	switch t.Kind() {
	case reflect.Bool:
		return boolEncoder
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return intEncoder
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return uintEncoder
	case reflect.Float32:
		return float32Encoder
	case reflect.Float64:
		return float64Encoder
	case reflect.String:
		return stringEncoder
	case reflect.Interface:
		return interfaceEncoder
	case reflect.Map:
		return newMapEncoder(t)
	case reflect.Slice:
		return newSliceEncoder(t)
	case reflect.Array:
		return newArrayEncoder(t)
	case reflect.Ptr:
		return newPtrEncoder(t)
	default:
		if t == listType {
			return listEncoder
		}
		return unsupportedTypeEncoder
	}
}

func invalidValueEncoder(e *encodeState, v reflect.Value) {
	e.WriteString("nil")
}

func timeEncoder(e *encodeState, v reflect.Value) {
	t := v.Interface().(time.Time)
	e.WriteString("#inst ")
	if _, err := e.string(t.UTC().Format(time.RFC3339Nano)); err != nil {
		e.error(err)
	}
}

func textMarshalerEncoder(e *encodeState, v reflect.Value) {
	if v.Kind() == reflect.Ptr && v.IsNil() {
		e.WriteString("nil")
		return
	}
	m := v.Interface().(encoding.TextMarshaler)
	b, err := m.MarshalText()
	if err == nil {
		_, err = e.stringBytes(b)
	}
	if err != nil {
		e.error(&MarshalerError{v.Type(), err})
	}
}

func addrTextMarshalerEncoder(e *encodeState, v reflect.Value) {
	va := v.Addr()
	if va.IsNil() {
		e.WriteString("nil")
		return
	}
	m := va.Interface().(encoding.TextMarshaler)
	b, err := m.MarshalText()
	if err == nil {
		_, err = e.stringBytes(b)
	}
	if err != nil {
		e.error(&MarshalerError{v.Type(), err})
	}
}

func boolEncoder(e *encodeState, v reflect.Value) {
	if v.Bool() {
		e.WriteString("true")
	} else {
		e.WriteString("false")
	}
}

func intEncoder(e *encodeState, v reflect.Value) {
	b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
	e.Write(b)
}

func uintEncoder(e *encodeState, v reflect.Value) {
	b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
	e.Write(b)
}

type floatEncoder int // number of bits

func (bits floatEncoder) encode(e *encodeState, v reflect.Value) {
	f := v.Float()
	if math.IsInf(f, 0) || math.IsNaN(f) {
		e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
	}
	b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
	e.Write(b)
}

var (
	float32Encoder = (floatEncoder(32)).encode
	float64Encoder = (floatEncoder(64)).encode
)

func stringEncoder(e *encodeState, v reflect.Value) {
	s := v.String()
	switch t := v.Type(); t {
	case symbolType, keywordType:
		if t == keywordType && !strings.HasPrefix(s, ":") {
			e.WriteByte(':')
		}
		e.WriteString(s)
		return
	default:
		e.string(s)
	}
}

func interfaceEncoder(e *encodeState, v reflect.Value) {
	if v.IsNil() {
		e.WriteString("nil")
		return
	}
	e.reflectValue(v.Elem())
}

func unsupportedTypeEncoder(e *encodeState, v reflect.Value) {
	e.error(&UnsupportedTypeError{v.Type()})
}

type mapEncoder struct {
	keyEnc  encoderFunc
	elemEnc encoderFunc
}

func (me *mapEncoder) encode(e *encodeState, v reflect.Value) {
	isSet := v.Type() == setType
	isKMap := v.Type() == keywordMapType
	sep := ", "
	if isSet {
		e.WriteByte('#')
		sep = " "
	}
	if v.IsNil() {
		e.WriteString("{}")
		return
	}
	e.WriteByte('{')
	for i, k := range v.MapKeys() {
		if i > 0 {
			e.WriteString(sep)
		}
		if !isKMap {
			me.keyEnc(e, k)
		} else {
			me.keyEnc(e, reflect.ValueOf(Keyword(k.String())))
		}
		if !isSet {
			e.WriteByte(' ')
			me.elemEnc(e, v.MapIndex(k))
		}
	}
	e.WriteByte('}')
}

func newMapEncoder(t reflect.Type) encoderFunc {
	me := &mapEncoder{typeEncoder(t.Key()), typeEncoder(t.Elem())}
	return me.encode
}

func encodeByteSlice(e *encodeState, v reflect.Value) {
	if v.IsNil() {
		e.WriteString("nil")
		return
	}
	s := v.Bytes()
	e.WriteString("#base64 ")
	e.WriteByte('"')
	if len(s) < 1024 {
		// for small buffers, using Encode directly is much faster.
		dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
		base64.StdEncoding.Encode(dst, s)
		e.Write(dst)
	} else {
		// for large buffers, avoid unnecessary extra temporary
		// buffer space.
		enc := base64.NewEncoder(base64.StdEncoding, e)
		enc.Write(s)
		enc.Close()
	}
	e.WriteByte('"')
}

func encodeUuid(e *encodeState, v reflect.Value) {
	e.WriteString("#uuid ")
	e.string(uuid.UUID(v.Bytes()).String())
}

// sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
type sliceEncoder struct {
	arrayEnc encoderFunc
}

func (se *sliceEncoder) encode(e *encodeState, v reflect.Value) {
	if v.IsNil() {
		e.WriteString("[]")
		return
	}
	se.arrayEnc(e, v)
}

func newSliceEncoder(t reflect.Type) encoderFunc {
	// Byte slices get special treatment; arrays don't.
	if t.Elem().Kind() == reflect.Uint8 {
		if t == uuidType {
			return encodeUuid
		}
		return encodeByteSlice
	}
	enc := &sliceEncoder{newArrayEncoder(t)}
	return enc.encode
}

type arrayEncoder struct {
	elemEnc encoderFunc
}

func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value) {
	e.WriteByte('[')
	n := v.Len()
	for i := 0; i < n; i++ {
		if i > 0 {
			e.WriteByte(' ')
		}
		ae.elemEnc(e, v.Index(i))
	}
	e.WriteByte(']')
}

func newArrayEncoder(t reflect.Type) encoderFunc {
	enc := &arrayEncoder{typeEncoder(t.Elem())}
	return enc.encode
}

type ptrEncoder struct {
	elemEnc encoderFunc
}

func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value) {
	if v.IsNil() {
		e.WriteString("nil")
		return
	}
	pe.elemEnc(e, v.Elem())
}

func newPtrEncoder(t reflect.Type) encoderFunc {
	enc := &ptrEncoder{typeEncoder(t.Elem())}
	return enc.encode
}

type condAddrEncoder struct {
	canAddrEnc, elseEnc encoderFunc
}

func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value) {
	if v.CanAddr() {
		ce.canAddrEnc(e, v)
	} else {
		ce.elseEnc(e, v)
	}
}

// newCondAddrEncoder returns an encoder that checks whether its value
// CanAddr and delegates to canAddrEnc if so, else to elseEnc.
func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
	enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
	return enc.encode
}

func listEncoder(e *encodeState, v reflect.Value) {
	l := v.Interface().(list.List)
	i := 0
	e.WriteByte('(')
	for node := l.Front(); node != nil; node = node.Next() {
		if i > 0 {
			e.WriteByte(' ')
		}
		e.reflectValue(reflect.ValueOf(node.Value))
		i++
	}
	e.WriteByte(')')
}


text:
from builtins import str
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils

def separator_test():
    """Test parsing of csv files having different separator characters."""
    # Test tab separated files by giving separator argument
    path_tab = "smalldata/parser/tabs.tsv"
    tab_test = h2o.import_file(path=pyunit_utils.locate(path_tab), destination_frame="tab_hex", sep="\t")
    assert tab_test.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(tab_test.nrow))
    assert tab_test.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(tab_test.ncol))

    # Test tab separated files by giving NO separator argument
    tab_test_noarg = h2o.import_file(path=pyunit_utils.locate(path_tab), destination_frame="tab_hex")
    assert tab_test_noarg.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(tab_test_noarg.nrow))
    assert tab_test_noarg.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(tab_test_noarg.ncol))

    # Test pipe separated files by giving separator
    path_pipe = "smalldata/parser/pipes.psv"
    pipe_test = h2o.import_file(path=pyunit_utils.locate(path_pipe), destination_frame="pipe_hex", sep="|")
    assert pipe_test.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(pipe_test.nrow))
    assert pipe_test.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(pipe_test.ncol))

    # Test pipe separated files by giving NO separator argument
    pipe_test_noarg = h2o.import_file(path=pyunit_utils.locate(path_pipe), destination_frame="pipe_hex")
    assert pipe_test_noarg.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(pipe_test_noarg.nrow))
    assert pipe_test_noarg.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(pipe_test_noarg.ncol))

    # Test hive files by giving separator
    path_hive = "smalldata/parser/test.hive"
    hive_test = h2o.import_file(path=pyunit_utils.locate(path_hive), destination_frame="hive_hex", sep="\001")
    assert hive_test.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(hive_test.nrow))
    assert hive_test.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(hive_test.ncol))

    # Test hive separated files by giving NO separator argument
    hive_test_noarg = h2o.import_file(path=pyunit_utils.locate(path_hive), destination_frame="hive_hex")
    assert hive_test_noarg.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(hive_test_noarg.nrow))
    assert hive_test_noarg.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(hive_test_noarg.ncol))

    # Test semi colon separated files by giving separator
    path_semi = "smalldata/parser/semi.scsv"
    semi_test = h2o.import_file(path=pyunit_utils.locate(path_semi), destination_frame="semi_hex", sep=";")
    assert semi_test.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(semi_test.nrow))
    assert semi_test.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(semi_test.ncol))

    # Test semi colon separated files by giving NO separator argument
    semi_test_noarg = h2o.import_file(path=pyunit_utils.locate(path_semi), destination_frame="semi_hex")
    assert semi_test_noarg.nrow == 3, "Error: Number of rows are not correct.{0}".format(str(semi_test_noarg.nrow))
    assert semi_test_noarg.ncol == 3, "Error: Number of columns are not correct.{0}".format(str(semi_test_noarg.ncol))

    # Test caret separated files
    path_caret = "smalldata/parser/caret.csv"
    caret_test = h2o.import_file(path=pyunit_utils.locate(path_caret), destination_frame="caret_hex", sep=u"^")
    assert caret_test.nrow == 3 and caret_test.ncol == 3

    # Test asterisk separated files
    path_asterisk = "smalldata/parser/asterisk.asv"
    asterisk_test = h2o.import_file(path=pyunit_utils.locate(path_asterisk), destination_frame="asterisk_hex", sep=u"*")
    assert asterisk_test.nrow == 3 and asterisk_test.ncol == 3

if __name__ == "__main__":
    pyunit_utils.standalone_test(separator_test)
else:
    separator_test()


text:
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;

namespace Ds3.Calls
{
    public class ModifyJobSpectraS3Request : Ds3Request
    {

        public string JobId { get; private set; }

        private DateTime? _createdAt;
        public DateTime? CreatedAt
        {
            get { return _createdAt; }
            set { WithCreatedAt(value); }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { WithName(value); }
        }

        private Priority? _priority;
        public Priority? Priority
        {
            get { return _priority; }
            set { WithPriority(value); }
        }

        public ModifyJobSpectraS3Request WithCreatedAt(DateTime? createdAt)
        {
            this._createdAt = createdAt;
            if (createdAt != null)
            {
                this.QueryParams.Add("created_at", createdAt.ToString());
            }
            else
            {
                this.QueryParams.Remove("created_at");
            }
            return this;
        }

        public ModifyJobSpectraS3Request WithName(string name)
        {
            this._name = name;
            if (name != null)
            {
                this.QueryParams.Add("name", name);
            }
            else
            {
                this.QueryParams.Remove("name");
            }
            return this;
        }

        public ModifyJobSpectraS3Request WithPriority(Priority? priority)
        {
            this._priority = priority;
            if (priority != null)
            {
                this.QueryParams.Add("priority", priority.ToString());
            }
            else
            {
                this.QueryParams.Remove("priority");
            }
            return this;
        }

        public ModifyJobSpectraS3Request(Guid jobId)
        {
            this.JobId = jobId.ToString();

        }

        public ModifyJobSpectraS3Request(string jobId)
        {
            this.JobId = jobId;

        }

        internal override HttpVerb Verb
        {
            get
            {
                return HttpVerb.PUT;
            }
        }

        internal override string Path
        {
            get
            {
                return "/_rest_/job/" + JobId.ToString();
            }
        }
    }
}


text:
require 'spec_helper'

describe "Users Security" do
  describe "Project" do
    before do
      @u1 = Factory :user
    end

    describe "GET /login" do
      it { new_user_session_path.should_not be_404_for :visitor }
    end

    describe "GET /keys" do
      subject { keys_path }

      it { should be_allowed_for @u1 }
      it { should be_allowed_for :admin }
      it { should be_allowed_for :user }
      it { should be_denied_for :visitor }
    end

    describe "GET /profile" do
      subject { profile_path }

      it { should be_allowed_for @u1 }
      it { should be_allowed_for :admin }
      it { should be_allowed_for :user }
      it { should be_denied_for :visitor }
    end

    describe "GET /profile/password" do
      subject { profile_password_path }

      it { should be_allowed_for @u1 }
      it { should be_allowed_for :admin }
      it { should be_allowed_for :user }
      it { should be_denied_for :visitor }
    end
  end
end


text:
local bit = require "bit"

local RNG = {}
RNG.__index = RNG

-- Class(...) works as same as Class.new(...)
setmetatable(RNG, {
  __call = function (klass, ...)
    return klass.new(...)
  end,
})

--- Constructs new RNG object.
-- @param seed Initial random seed (corresponding to $3743-3744)
function RNG.new(seed)
  local self = setmetatable({}, RNG)
  self.seed = seed or 0x7777
  return self
end

--- Generates the next random number.
function RNG.advance(self)
  -- Reimplementation of $8aba-8ad1 (part of jsl $8a9f)
  local seed = self.seed
  for i = 1, 11 do
    local randbit = bit.band(1, bit.bxor(1, seed, bit.rshift(seed, 1), bit.rshift(seed, 15)))
    seed = bit.band(bit.bor(bit.lshift(seed, 1), randbit), 0xffff)
  end
  self.seed = seed
end

--- Returns the next random number.
-- @param bound the upper bound (exclusive). Must be between 1 and 255, or 0 (works as 256).
-- @return the next random number.
function RNG.random(self, bound)
  self:advance()

  -- Reimplementation of $8ad7-8ae9 (part of jsl $8a9f)
  local value = bit.band(self.seed, 0xff)
  if bound and bound ~= 0 then
    value = bit.rshift(value * bound, 8)
  end
  return value
end

return RNG


text:
from ._version import __version__, __version_info__  # noqa
from .utils import find


text:
from __future__ import absolute_import, unicode_literals
from tekton import router

_not_secure_path_set = set()

def is_csrf_secure_by_path(path):
    return path not in _not_secure_path_set

def is_csrf_secure(fcn):
    path = router.to_path(fcn)
    return is_csrf_secure_by_path(path)

def no_csrf(fcn):
    path = router.to_path(fcn)
    _not_secure_path_set.add(path)
    return fcn


text:
{-|
Module      : CSH.Eval.Cacheable.Make
Description : Cacheable Actions to Create Objects
Copyright   : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License     : MIT
Maintainer  : pvals@csh.rit.edu
Stability   : Provisional
Portability : POSIX

CSH.Eval.Cacheable.Make defines 'Cacheable' computations for introducing state
objects.
-}

{-# LANGUAGE OverloadedStrings #-}

module CSH.Eval.Cacheable.Make (
    -- * Object Instantiating Functions
    -- ** Member
    mkIntroMember
  , mkExtantMember
    -- ** Event
  , mkEvent
    -- ** Project
  , mkProject
    -- ** Evaluation
  , mkEvaluation
    -- ** Conditional
  , mkConditional
    -- ** FreshmanProject
  , mkFreshmanProject
    -- ** Packet
  , mkPacket
    -- ** Application
  , mkApplication
    -- ** Metric
  , mkMetric
    -- ** Review
  , mkReview
    -- ** Interview
  , mkInterview
    -- ** Question
  , mkQuestion
    -- ** Term
  , mkTerm
    -- * Context Instantiating Functions
    -- ** Eboard
  , grEboard
    -- ** Room
  , grRoom
    -- ** Queue
  , grQueue
    -- ** Membership
  , grMembership
    -- ** EventAttendee
  , grEventAttendee
    -- ** ProjectParticipant
  , grProjectParticipant
    -- ** FreshmanProjectParticipant
  , grFreshmanProjectParticipant
    -- ** Signature
  , grSignature
    -- ** ReviewMetric
  , grReviewMetric
    -- ** InterviewMetric
  , grInterviewMetric
    -- ** Answer
  , grAnswer
    -- ** Dues
  , grDues
    -- * ToRow Functions
  ) where

import Data.Word

import Data.UUID

import Data.Time

import qualified Data.ByteString as B

import qualified Data.Text as T

import CSH.Eval.Model

import CSH.Eval.DB.Statements

import CSH.Eval.Cacheable.Prim
import CSH.Eval.Cacheable.Fetch

mkIntroMember :: UUID         -- ^ Member UUID.
              -> T.Text       -- ^ Username.
              -> T.Text       -- ^ Common name.
              -> B.ByteString -- ^ Passowrd hash.
              -> B.ByteString -- ^ Passowrd salt
              -> Cacheable ()
mkIntroMember uu u cn ph ps c = do
    mid <- liftInsertSingleQ (mkIntroMemberP uu u cn ph ps) c
    let m = Member mid
                   uu
                   u
                   cn
                   Nothing
                   0
                   False
                   (getMemberEboards mid)
                   (getMemberRooms mid)
                   (getMemberMemberships mid)
                   (getMemberEvaluations mid)
                   (getMemberPackets mid)
                   (getMemberQueues mid)
                   (getMemberApplications mid)
                   (getMemberDues mid)
    singletonGhost memberIDCache mid m c

mkExtantMember :: UUID   -- ^ Member UUID.
               -> T.Text -- ^ Username.
               -> T.Text -- ^ Common name.
               -> Int    -- ^ Housing points.
               -> Bool   -- ^ On floor status.
               -> Cacheable ()
mkExtantMember uu u cn hp os c = do
    mid <- liftInsertSingleQ (mkExtantMemberP uu u cn hp os) c
    let m = Member mid
                   uu
                   u
                   cn
                   Nothing
                   hp
                   os
                   (getMemberEboards mid)
                   (getMemberRooms mid)
                   (getMemberMemberships mid)
                   (getMemberEvaluations mid)
                   (getMemberPackets mid)
                   (getMemberQueues mid)
                   (getMemberApplications mid)
                   (getMemberDues mid)
    singletonGhost memberIDCache mid m c

mkEvent :: T.Text    -- ^ Title.
        -> UTCTime   -- ^ Held time.
        -> EventType -- ^ Event type
        -> Committee -- ^ Event Committee
        -> T.Text    -- ^ Description
        -> Cacheable ()
mkEvent t h et ec d c = do
    eid <- liftInsertSingleQ (mkEventP t h (eventTypeToVal et) (committeeToVal ec) d) c
    let e = Event eid
                  t
                  h
                  et
                  ec
                  d
                  (getEventEventAttendees eid)
    singletonGhost eventIDCache eid e c

mkProject :: T.Text      -- ^ Title.
          -> T.Text      -- ^ Description.
          -> UTCTime     -- ^ Submission time.
          -> Committee   -- ^ Project committee.
          -> ProjectType -- ^ Project type.
          -> Cacheable ()
mkProject t d st pc pt c = do
    pid <- liftInsertSingleQ (mkProjectP t d st (committeeToVal pc) (projectTypeToVal pt)) c
    let p = Project pid
                    t
                    d
                    st
                    Nothing
                    pc
                    pt
                    T.empty
                    Pending
                    (getProjectProjectParticipants pid)
    singletonGhost projectIDCache pid p c

mkEvaluation :: Word64         -- ^ Member ID.
             -> UTCTime        -- ^ Evaluation deadline.
             -> EvaluationType -- ^ Evaluation type.
             -> Cacheable ()
mkEvaluation mid t et c = do
    eid <- liftInsertSingleQ (mkEvaluationP mid t (evaluationTypeToVal et)) c
    let e = Evaluation eid
                       T.empty
                       t
                       False
                       Pending
                       et
                       (getMemberID mid)
                       (getEvaluationConditionals eid)
                       (getEvaluationFreshmanProjectParticipants eid)
    singletonGhost evaluationIDCache eid e c

mkConditional :: Word64  -- ^ Evaluation ID.
              -> UTCTime -- ^ Due date.
              -> T.Text  -- ^ Description.
              -> Cacheable ()
mkConditional eid dt d c = do
    cid <- liftInsertSingleQ (mkConditionalP eid dt d) c
    let c' = Conditional cid
                         dt
                         d
                         T.empty
                         (getEvaluationID eid)
    singletonGhost conditionalIDCache cid c' c

mkFreshmanProject :: Word64 -- ^ Term ID.
                  -> Word64 -- ^ Event ID.
                  -> T.Text -- ^ Description.
                  -> Cacheable ()
mkFreshmanProject tid eid d c = do
    fpid <- liftInsertSingleQ (mkFreshmanProjectP tid eid d) c
    let fp = FreshmanProject fpid
                             d
                             (getTermID tid)
                             (getEventID eid)
                             (getFreshmanProjectFreshmanProjectParticipants fpid)
    singletonGhost freshmanProjectIDCache fpid fp c

mkPacket :: Word64  -- ^ Member ID.
         -> UTCTime -- ^ Due date.
         -> Int     -- ^ Percent required.
         -> Cacheable ()
mkPacket mid d p c = do
    pid <- liftInsertSingleQ (mkPacketP mid d p) c
    let p' = Packet pid
                   d
                   p
                   (getMemberID mid)
                   (getPacketSignatures pid)
    singletonGhost packetIDCache pid p' c

mkApplication :: Word64  -- ^ Member ID.
              -> UTCTime -- ^ Creation time.
              -> Cacheable ()
mkApplication mid t c = do
    aid <- liftInsertSingleQ (mkApplicationP mid t) c
    let a = Application aid
                        t
                        Pending
                        (getMemberID mid)
                        (getApplicationReviews aid)
                        (getApplicationInterviews aid)
                        (getApplicationAnswers aid)
    singletonGhost applicationIDCache aid a c

mkMetric :: T.Text -- ^ Description.
         -> Cacheable ()
mkMetric d c = do
    mid <- liftInsertSingleQ (mkMetricP d) c
    let m = Metric mid
                   d
                   True
    singletonGhost metricIDCache mid m c

mkReview :: Word64  -- ^ Member ID(reviewer).
         -> Word64  -- ^ Application ID.
         -> UTCTime -- ^ Start time.
         -> UTCTime -- ^ Submission time.
         -> Cacheable ()
mkReview mid aid st et c = do
    rid <- liftInsertSingleQ (mkReviewP mid aid st et) c
    let r = Review rid
                   st
                   et
                   (getMemberID mid)
                   (getApplicationID aid)
                   (getReviewReviewMetrics rid)
    singletonGhost reviewIDCache rid r c

mkInterview :: Word64  -- ^ Member ID(interviewer).
            -> Word64  -- ^ Application ID.
            -> UTCTime -- ^ Interview time.
            -> Cacheable ()
mkInterview mid aid t c = do
    iid <- liftInsertSingleQ (mkInterviewP mid aid t) c
    let i = Interview iid
                      t
                      (getMemberID mid)
                      (getApplicationID aid)
                      (getInterviewInterviewMetrics iid)
    singletonGhost interviewIDCache iid i c

mkQuestion :: T.Text -- ^ Query.
           -> Cacheable ()
mkQuestion q c = do
    qid <- liftInsertSingleQ (mkQuestionP q) c
    let q' = Question qid
                     q
                     True
    singletonGhost questionIDCache qid q' c

mkTerm :: Day -- ^ Start date.
       -> Cacheable ()
mkTerm s c = do
    tid <- liftInsertSingleQ (mkTermP s) c
    let t = Term tid
                 s
                 Nothing
    singletonGhost termIDCache tid t c

grEboard :: Word64    -- ^ Member ID.
         -> Committee -- ^ Committee.
         -> Day       -- ^ Service start date.
         -> Cacheable ()
grEboard mid cm s c = do
    liftUnitQ (grEboardP mid (committeeToVal cm) s) c
    let e = Eboard cm
                   s
                   Nothing
                   (getMemberID mid)
    appendGhost eboardMemberIDCache mid e c

grRoom :: Word64 -- ^ Member ID.
       -> T.Text -- ^ Room number.
       -> Day    -- ^ Residence start date.
       -> Cacheable ()
grRoom mid rn s c = do
    liftUnitQ (grRoomP mid rn s) c
    let r = Room rn
                 s
                 Nothing
                 (getMemberID mid)
    appendGhost roomMemberIDCache mid r c

grQueue :: Word64  -- ^ Member ID.
        -> UTCTime -- ^ Entrance time.
        -> Cacheable ()
grQueue mid t c = do
    liftUnitQ (grQueueP mid t) c
    let q = Queue t
                  Nothing
                  (getMemberID mid)
    appendGhost queueMemberIDCache mid q c

grMembership :: Word64       -- ^ Member ID.
             -> MemberStatus -- ^ Membership status.
             -> Day          -- ^ Effective date.
             -> Cacheable ()
grMembership mid ms t c = do
    liftUnitQ (grMembershipP mid (memberStatusToVal ms) t) c
    let m = Membership ms
                       t
                       Nothing
                       (getMemberID mid)
    appendGhost membershipMemberIDCache mid m c

grEventAttendee :: Word64 -- ^ Member ID.
                -> Word64 -- ^ Event ID.
                -> Bool   -- ^ Host status.
                -> Cacheable ()
grEventAttendee mid eid h c = do
    liftUnitQ (grEventAttendeeP mid eid h) c
    let e = EventAttendee h
                          (getMemberID mid)
                          (getEventID eid)
    appendGhost eventAttendeeMemberIDCache mid e c
    appendGhost eventAttendeeEventIDCache eid e c

grProjectParticipant :: Word64 -- ^ Member ID.
                     -> Word64 -- ^ Project ID.
                     -> T.Text -- ^ Description.
                     -> Cacheable ()
grProjectParticipant mid pid d c = do
    liftUnitQ (grProjectParticipantP mid pid d) c
    let p = ProjectParticipant d
                               (getMemberID mid)
                               (getProjectID pid)
    appendGhost projectParticipantMemberIDCache mid p c
    appendGhost projectParticipantProjectIDCache pid p c

grFreshmanProjectParticipant :: Word64 -- ^ Freshman Project ID.
                             -> Word64 -- ^ Evaluation ID.
                             -> Cacheable ()
grFreshmanProjectParticipant pid eid c = do
    liftUnitQ (grFreshmanProjectParticipantP pid eid) c
    let f = FreshmanProjectParticipant False
                                       Pending
                                       T.empty
                                       (getFreshmanProjectID pid)
                                       (getEvaluationID eid)
    appendGhost freshProjParticipantProjectIDCache pid f c
    appendGhost freshProjParticipantEvaluationIDCache eid f c

grSignature :: Word64 -- ^ Member ID.
            -> Word64 -- ^ Packet ID.
            -> Bool   -- ^ Required.
            -> Cacheable ()
grSignature mid pid r c = do
    liftUnitQ (grSignatureP mid pid r) c
    let s = Signature r
                      Nothing
                      (getMemberID mid)
                      (getPacketID pid)
    appendGhost signatureMemberIDCache mid s c
    appendGhost signaturePacketIDCache pid s c

grReviewMetric :: Word64 -- ^ Metric ID.
               -> Word64 -- ^ Review ID.
               -> Int    -- ^ Score.
               -> Cacheable ()
grReviewMetric mid rid s c = do
    liftUnitQ (grReviewMetricP mid rid s) c
    let r = ReviewMetric s
                         (getMetricID mid)
                         (getReviewID rid)
    appendGhost reviewMetricMetricIDCache mid r c
    appendGhost reviewMetricReviewIDCache rid r c

grInterviewMetric :: Word64 -- ^ Metric ID.
                  -> Word64 -- ^ Interview ID.
                  -> Int    -- ^ Score.
                  -> Cacheable ()
grInterviewMetric mid iid s c = do
    liftUnitQ (grInterviewMetricP mid iid s) c
    let i = InterviewMetric s
                            (getMetricID mid)
                            (getInterviewID iid)
    appendGhost interviewMetricMetricIDCache mid i c
    appendGhost interviewMetricInterviewIDCache iid i c

grAnswer :: Word64 -- ^ Application ID
         -> Word64 -- ^ Question ID
         -> T.Text -- ^ Response
         -> Cacheable ()
grAnswer aid qid r c = do
    liftUnitQ (grAnswerP aid qid r) c
    let a = Answer r
                   (getQuestionID qid)
                   (getApplicationID aid)
    appendGhost answerQuestionIDCache qid a c
    appendGhost answerApplicationIDCache aid a c

grDues :: Word64     -- ^ Term ID.
       -> Word64     -- ^ Member ID.
       -> DuesStatus -- ^ Dues status.
       -> Cacheable ()
grDues tid mid s c = do
    liftUnitQ (grDuesP tid mid (duesStatusToVal s)) c
    let d = Dues s
                 (getMemberID mid)
                 (getTermID tid)
    appendGhost duesMemberIDCache mid d c
    appendGhost duesTermIDCache tid d c


text:
package com.google.common.base;

import javax.annotation.Nullable;

/**
 * Holder for extra methods of {@code Objects} only in web.
 */
abstract class ExtraObjectsMethodsForWeb {
  public static boolean equal(@Nullable String a, @Nullable String b) {
    return a == b;
  }
}


text: var jsonData = null;


text:
"""add wikiRevisionID to wikipedia_works

Revision ID: 20362f93f52
Revises: f0492b40e6
Create Date: 2014-10-12 12:11:10.685409

"""
from alembic import op
import sqlalchemy as sa

revision = '20362f93f52'
down_revision = 'f0492b40e6'

def upgrade():
    op.add_column(
        'wikipedia_works',
        sa.Column('revision', sa.Integer(), nullable=True)
    )

def downgrade():
    op.drop_column('wikipedia_works', 'revision')


text:
package org.gradle.process.internal.worker.child;

import org.gradle.api.Action;
import org.gradle.api.logging.LogLevel;
import org.gradle.initialization.GradleUserHomeDirProvider;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.concurrent.ExecutorFactory;
import org.gradle.internal.event.DefaultListenerManager;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.io.ClassLoaderObjectInputStream;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.gradle.internal.logging.services.LoggingServiceRegistry;
import org.gradle.internal.remote.MessagingClient;
import org.gradle.internal.remote.ObjectConnection;
import org.gradle.internal.remote.internal.inet.MultiChoiceAddress;
import org.gradle.internal.remote.internal.inet.MultiChoiceAddressSerializer;
import org.gradle.internal.remote.services.MessagingServices;
import org.gradle.internal.serialize.Decoder;
import org.gradle.internal.serialize.InputStreamBackedDecoder;
import org.gradle.internal.service.DefaultServiceRegistry;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.time.Clock;
import org.gradle.internal.time.Time;
import org.gradle.process.internal.health.memory.DefaultJvmMemoryInfo;
import org.gradle.process.internal.health.memory.DefaultMemoryManager;
import org.gradle.process.internal.health.memory.DisabledOsMemoryInfo;
import org.gradle.process.internal.health.memory.JvmMemoryInfo;
import org.gradle.process.internal.health.memory.JvmMemoryStatus;
import org.gradle.process.internal.health.memory.JvmMemoryStatusListener;
import org.gradle.process.internal.health.memory.MemoryManager;
import org.gradle.process.internal.health.memory.OsMemoryInfo;
import org.gradle.process.internal.worker.WorkerJvmMemoryInfoSerializer;
import org.gradle.process.internal.worker.WorkerLoggingSerializer;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.util.concurrent.Callable;

/**
 *
Stage 2 of the start-up for a worker process with the application classes loaded in the system ClassLoader. Takes
 * care of deserializing and invoking the worker action.

 *
 *
 Instantiated in the implementation ClassLoader and invoked from {@link org.gradle.process.internal.worker.GradleWorkerMain}.
 * See {@link ApplicationClassesInSystemClassLoaderWorkerImplementationFactory} for details.

 */
public class SystemApplicationClassLoaderWorker implements Callable<Void> {
    private final DataInputStream configInputStream;

    public SystemApplicationClassLoaderWorker(DataInputStream configInputStream) {
        this.configInputStream = configInputStream;
    }

    public Void call() throws Exception {
        if (System.getProperty("org.gradle.worker.test.stuck") != null) {
            // Simulate a stuck worker. There's probably a way to inject this failure...
            Thread.sleep(30000);
            return null;
        }

        Decoder decoder = new InputStreamBackedDecoder(configInputStream);

        // Read logging config and setup logging
        int logLevel = decoder.readSmallInt();
        LoggingManagerInternal loggingManager = createLoggingManager();
        loggingManager.setLevelInternal(LogLevel.values()[logLevel]).start();

        // Read whether process info should be published
        boolean shouldPublishJvmMemoryInfo = decoder.readBoolean();

        // Read path to Gradle user home
        String gradleUserHomeDirPath = decoder.readString();
        File gradleUserHomeDir = new File(gradleUserHomeDirPath);

        // Read server address and start connecting
        MultiChoiceAddress serverAddress = new MultiChoiceAddressSerializer().read(decoder);
        MessagingServices messagingServices = new MessagingServices();
        final WorkerServices workerServices = new WorkerServices(messagingServices, gradleUserHomeDir);

        ObjectConnection connection = null;
        WorkerLogEventListener workerLogEventListener = null;
        try {
            // Read serialized worker
            byte[] serializedWorker = decoder.readBinary();

            // Deserialize the worker action
            Action<WorkerContext> action;
            try {
                ObjectInputStream instr = new ClassLoaderObjectInputStream(new ByteArrayInputStream(serializedWorker), getClass().getClassLoader());
                action = (Action<WorkerContext>) instr.readObject();
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }

            connection = messagingServices.get(MessagingClient.class).getConnection(serverAddress);
            workerLogEventListener = configureLogging(loggingManager, connection);
            if (shouldPublishJvmMemoryInfo) {
                configureWorkerJvmMemoryInfoEvents(workerServices, connection);
            }

            final ObjectConnection serverConnection = connection;
            action.execute(new WorkerContext() {
                public ClassLoader getApplicationClassLoader() {
                    return ClassLoader.getSystemClassLoader();
                }

                @Override
                public ObjectConnection getServerConnection() {
                    return serverConnection;
                }

                @Override
                public ServiceRegistry getServiceRegistry() {
                    return workerServices;
                }
            });
        } finally {
            if (workerLogEventListener != null) {
                loggingManager.removeOutputEventListener(workerLogEventListener);
            }
            if (connection != null) {
                connection.stop();
            }
            messagingServices.close();
            loggingManager.stop();
        }

        return null;
    }

    private WorkerLogEventListener configureLogging(LoggingManagerInternal loggingManager, ObjectConnection connection) {
        connection.useParameterSerializers(WorkerLoggingSerializer.create());
        WorkerLoggingProtocol workerLoggingProtocol = connection.addOutgoing(WorkerLoggingProtocol.class);
        WorkerLogEventListener workerLogEventListener = new WorkerLogEventListener(workerLoggingProtocol);
        loggingManager.addOutputEventListener(workerLogEventListener);
        return workerLogEventListener;
    }

    private void configureWorkerJvmMemoryInfoEvents(WorkerServices services, ObjectConnection connection) {
        connection.useParameterSerializers(WorkerJvmMemoryInfoSerializer.create());
        final WorkerJvmMemoryInfoProtocol workerJvmMemoryInfoProtocol = connection.addOutgoing(WorkerJvmMemoryInfoProtocol.class);
        services.get(MemoryManager.class).addListener(new JvmMemoryStatusListener() {
            @Override
            public void onJvmMemoryStatus(JvmMemoryStatus jvmMemoryStatus) {
                workerJvmMemoryInfoProtocol.sendJvmMemoryStatus(jvmMemoryStatus);
            }
        });
    }

    LoggingManagerInternal createLoggingManager() {
        LoggingManagerInternal loggingManagerInternal = LoggingServiceRegistry.newEmbeddableLogging().newInstance(LoggingManagerInternal.class);
        loggingManagerInternal.captureSystemSources();
        return loggingManagerInternal;
    }

    private static class WorkerServices extends DefaultServiceRegistry {
        public WorkerServices(ServiceRegistry parent, final File gradleUserHomeDir) {
            super(parent);
            addProvider(new Object() {
                GradleUserHomeDirProvider createGradleUserHomeDirProvider() {
                    return new GradleUserHomeDirProvider() {
                        @Override
                        public File getGradleUserHomeDirectory() {
                            return gradleUserHomeDir;
                        }
                    };
                }
            });
        }

        Clock createClock() {
            return Time.clock();
        }

        ListenerManager createListenerManager() {
            return new DefaultListenerManager();
        }

        OsMemoryInfo createOsMemoryInfo() {
            return new DisabledOsMemoryInfo();
        }

        JvmMemoryInfo createJvmMemoryInfo() {
            return new DefaultJvmMemoryInfo();
        }

        MemoryManager createMemoryManager(OsMemoryInfo osMemoryInfo, JvmMemoryInfo jvmMemoryInfo, ListenerManager listenerManager, ExecutorFactory executorFactory) {
            return new DefaultMemoryManager(osMemoryInfo, jvmMemoryInfo, listenerManager, executorFactory);
        }

        WorkerDirectoryProvider createWorkerDirectoryProvider(GradleUserHomeDirProvider gradleUserHomeDirProvider) {
            return new DefaultWorkerDirectoryProvider(gradleUserHomeDirProvider);
        }
    }
}


text:
"""
Unit tests for the handling of physical types in `astropy.units`.
"""
import pickle

import pytest

from astropy import units as u
from astropy.constants import hbar
from astropy.units import physical
from astropy.utils.exceptions import AstropyDeprecationWarning

unit_physical_type_pairs = [
    (u.m, "length"),
    (u.cm ** 3, "volume"),
    (u.km / u.h, "speed"),
    (u.barn * u.Mpc, "volume"),
    (u.m * u.s ** 8, "unknown"),
    (u.m / u.m, "dimensionless"),
    (hbar.unit, "angular momentum"),
    (u.erg / (u.cm ** 2 * u.s * u.AA), "spectral flux density wav"),
    (u.photon / (u.cm ** 2 * u.s * u.AA), "photon flux density wav"),
    (u.photon / (u.cm ** 2 * u.s * u.Hz), "photon flux density"),
    (u.byte, "data quantity"),
    (u.bit, "data quantity"),
    (u.imperial.mi / u.week, "speed"),
    (u.erg / u.s, "power"),
    (u.C / u.s, "electrical current"),
    (u.C / u.s / u.cm ** 2, "electrical current density"),
    (u.T * u.m ** 2, "magnetic flux"),
    (u.N * u.m, "energy"),
    (u.rad / u.ms, "angular speed"),
    (u.Unit(1), "dimensionless"),
    (u.m ** 2, "area"),
    (u.s, "time"),
    (u.rad, "angle"),
    (u.sr, "solid angle"),
    (u.m / u.s ** 2, "acceleration"),
    (u.Hz, "frequency"),
    (u.g, "mass"),
    (u.mol, "amount of substance"),
    (u.K, "temperature"),
    (u.deg_C, "temperature"),
    (u.imperial.deg_F, "temperature"),
    (u.imperial.deg_R, "temperature"),
    (u.imperial.deg_R / u.m, "temperature_gradient"),
    (u.N, "force"),
    (u.J, "energy"),
    (u.Pa, "pressure"),
    (u.W, "power"),
    (u.kg / u.m ** 3, "mass density"),
    (u.m ** 3 / u.kg, "specific volume"),
    (u.mol / u.m ** 3, "molar concentration"),
    (u.kg * u.m / u.s, "momentum/impulse"),
    (u.kg * u.m ** 2 / u.s, "angular momentum"),
    (u.rad / u.s, "angular speed"),
    (u.rad / u.s ** 2, "angular acceleration"),
    (u.g / (u.m * u.s), "dynamic viscosity"),
    (u.m ** 2 / u.s, "kinematic viscosity"),
    (u.m ** -1, "wavenumber"),
    (u.A, "electrical current"),
    (u.C, "electrical charge"),
    (u.V, "electrical potential"),
    (u.Ohm, "electrical resistance"),
    (u.S, "electrical conductance"),
    (u.F, "electrical capacitance"),
    (u.C * u.m, "electrical dipole moment"),
    (u.A / u.m ** 2, "electrical current density"),
    (u.V / u.m, "electrical field strength"),
    (u.C / u.m ** 2, "electrical flux density"),
    (u.C / u.m ** 3, "electrical charge density"),
    (u.F / u.m, "permittivity"),
    (u.Wb, "magnetic flux"),
    (u.T, "magnetic flux density"),
    (u.A / u.m, "magnetic field strength"),
    (u.H / u.m, "electromagnetic field strength"),
    (u.H, "inductance"),
    (u.cd, "luminous intensity"),
    (u.lm, "luminous flux"),
    (u.lx, "luminous emittance/illuminance"),
    (u.W / u.sr, "radiant intensity"),
    (u.cd / u.m ** 2, "luminance"),
    (u.astrophys.Jy, "spectral flux density"),
    (u.astrophys.R, "photon flux"),
    (u.misc.bit, "data quantity"),
    (u.misc.bit / u.s, "bandwidth"),
    (u.cgs.Franklin, "electrical charge (ESU)"),
    (u.cgs.statampere, "electrical current (ESU)"),
    (u.cgs.Biot, "electrical current (EMU)"),
    (u.cgs.abcoulomb, "electrical charge (EMU)"),
    (u.imperial.btu / (u.s * u.m * u.imperial.deg_F), "thermal conductivity"),
    (u.imperial.cal / u.deg_C, "heat capacity"),
    (u.imperial.cal / u.deg_C / u.g, "specific heat capacity"),
    (u.J * u.m ** -2 * u.s ** -1, "energy flux"),
    (u.W / u.m ** 2, "energy flux"),
    (u.m ** 3 / u.mol, "molar volume"),
    (u.m / u.S, "electrical resistivity"),
    (u.S / u.m, "electrical conductivity"),
    (u.A * u.m ** 2, "magnetic moment"),
    (u.J / u.T, "magnetic moment"),
    (u.yr ** -1 * u.Mpc ** -3, "volumetric rate"),
    (u.m / u.s ** 3, "jerk"),
    (u.m / u.s ** 4, "snap"),
    (u.m / u.s ** 5, "crackle"),
    (u.m / u.s ** 6, "pop"),
    (u.deg_C / u.m, "temperature gradient"),
    (u.imperial.deg_F / u.m, "temperature gradient"),
    (u.imperial.deg_R / u.imperial.ft, "temperature gradient"),
    (u.imperial.Calorie / u.g, "specific energy"),
    (u.mol / u.L / u.s, "reaction rate"),
    (u.imperial.lbf * u.imperial.ft * u.s ** 2, "moment of inertia"),
    (u.mol / u.s, "catalytic activity"),
    (u.imperial.kcal / u.deg_C / u.mol, "molar heat capacity"),
    (u.mol / u.kg, "molality"),
    (u.imperial.inch * u.hr, "absement"),
    (u.imperial.ft ** 3 / u.s, "volumetric flow rate"),
    (u.Hz / u.s, "frequency drift"),
    (u.Pa ** -1, "compressibility"),
    (u.dimensionless_unscaled, "dimensionless"),
]

@pytest.mark.parametrize("unit, physical_type", unit_physical_type_pairs)
def test_physical_type_names(unit, physical_type):
    """
    Test that the `physical_type` attribute of `u.Unit` objects provides
    the expected physical type for various units.

    Many of these tests are used to test backwards compatibility.
    """
    assert unit.physical_type == physical_type, (
        f"{unit!r}.physical_type was expected to return "
        f"{physical_type!r}, but instead returned {unit.physical_type!r}."
    )

length = u.m.physical_type
time = u.s.physical_type
speed = (u.m / u.s).physical_type
area = (u.m ** 2).physical_type
wavenumber = (u.m ** -1).physical_type
dimensionless = u.dimensionless_unscaled.physical_type
pressure = u.Pa.physical_type
momentum = (u.kg * u.m / u.s).physical_type

@pytest.mark.parametrize(
    "physical_type_representation, physical_type_name", [
        (1.0, "dimensionless"),
        (u.m, "length"),
        ("work", "work"),
        (5 * u.m, "length"),
        (length, length),
        (u.Pa, "energy_density"),  # attribute-accessible name
        ("energy_density", "energy_density")  # attribute-accessible name
    ],
)
def test_getting_physical_type(physical_type_representation, physical_type_name):
    """Test different ways of getting a physical type."""
    physical_type = physical.get_physical_type(physical_type_representation)
    assert isinstance(physical_type, physical.PhysicalType)
    assert physical_type == physical_type_name

@pytest.mark.parametrize(
    "argument, exception", [
        ("unknown", ValueError),
        ("not a name of a physical type", ValueError),
        ({"this set cannot be made into a Quantity"}, TypeError),
    ]
)
def test_getting_physical_type_exceptions(argument, exception):
    """
    Test that `get_physical_type` raises appropriate exceptions when
    provided with invalid arguments.
    """
    with pytest.raises(exception):
        physical.get_physical_type(argument)

def test_physical_type_cannot_become_quantity():
    """
    Test that `PhysicalType` instances cannot be cast into `Quantity`
    objects.  A failure in this test could be related to failures
    in subsequent tests.
    """
    with pytest.raises(TypeError):
        u.Quantity(u.m.physical_type, u.m)

# left term, right term, operator, expected value
operation_parameters = [
    (length, length, "__eq__", True),
    (length, area, "__eq__", False),
    (length, "length", "__eq__", True),
    ("length", length, "__eq__", NotImplemented),
    (dimensionless, dimensionless, "__eq__", True),
    (momentum, "momentum/impulse", "__eq__", True),  # test delimiters in names
    (pressure, "energy_density", "__eq__", True),  # test underscores in names
    ((u.m ** 8).physical_type, "unknown", "__eq__", True),
    ((u.m ** 8).physical_type, (u.m ** 9).physical_type, "__eq__", False),
    (length, length, "__ne__", False),
    (speed, time, "__ne__", True),
    (pressure, dimensionless, "__ne__", True),
    (length, u.m, "__eq__", NotImplemented),
    (length, length, "__mul__", area),
    (speed, time, "__mul__", length),
    (speed, time, "__rmul__", length),
    (length, time, "__truediv__", speed),
    (area, length, "__truediv__", length),
    (length, area, "__rtruediv__", length),
    (dimensionless, dimensionless, "__mul__", dimensionless),
    (dimensionless, dimensionless, "__truediv__", dimensionless),
    (length, 2, "__pow__", area),
    (area, 0.5, "__pow__", length),
    (dimensionless, 4, "__pow__", dimensionless),
    (u.m, length, "__mul__", NotImplemented),
    (3.2, length, "__mul__", NotImplemented),
    (u.m, time, "__truediv__", NotImplemented),
    (3.2, length, "__truediv__", NotImplemented),
    (length, u.m, "__mul__", area),
    (length, u.m, "__rmul__", area),
    (speed, u.s, "__mul__", length),
    (length, 1, "__mul__", length),
    (length, 1, "__rmul__", length),
    (length, u.s, "__truediv__", speed),
    (area, 1, "__truediv__", area),
    (time, u.m, "__rtruediv__", speed),
    (length, 1.0, "__rtruediv__", wavenumber),
    (length, 2, "__pow__", area),
    (length, 32, "__mul__", NotImplemented),
    (length, 0, "__rmul__", NotImplemented),
    (length, 3.2, "__truediv__", NotImplemented),
    (length, -1, "__rtruediv__", NotImplemented),
    (length, "length", "__mul__", area),
    (length, "length", "__rmul__", area),
    (area, "length", "__truediv__", length),
    (length, "area", "__rtruediv__", length),
]

@pytest.mark.parametrize("left, right, operator, expected", operation_parameters)
def test_physical_type_operations(left, right, operator, expected):
    """
    Test that `PhysicalType` dunder methods that require another
    argument behave as intended.
    """
    assert getattr(left, operator)(right) == expected

unit_with_physical_type_set = [
    (u.m, {"length"}),
    (u.kg * u.m / u.s, {"impulse", "momentum"}),
    (u.Pa, {"energy density", "pressure", "stress"}),
]

@pytest.mark.parametrize("unit, expected_set", unit_with_physical_type_set)
def test_physical_type_as_set(unit, expected_set):
    """Test making a `physical.PhysicalType` instance into a `set`."""
    resulting_set = set(unit.physical_type)
    assert resulting_set == expected_set

def test_physical_type_iteration():
    """Test iterating through different physical type names."""
    physical_type_names = [physical_type_name for physical_type_name in pressure]
    assert physical_type_names == ["energy density", "pressure", "stress"]

def test_physical_type_in():
    """
    Test that `in` works as expected for `PhysicalType` objects with one
    or multiple names.
    """
    assert "length" in length
    assert "pressure" in pressure

equivalent_unit_pairs = [
    (u.m, u.m),
    (u.m, u.cm),
    (u.N, u.kg * u.m * u.s ** -2),
    (u.barn * u.Mpc, u.cm ** 3),
    (u.K, u.deg_C),
    (u.K, u.imperial.deg_R),
    (u.K, u.imperial.deg_F),
    (u.deg_C, u.imperial.deg_F),
    (u.m ** 18, u.pc ** 18),
]

@pytest.mark.parametrize("unit1, unit2", equivalent_unit_pairs)
def test_physical_type_instance_equality(unit1, unit2):
    """
    Test that `physical.PhysicalType` instances for units of the same
    dimensionality are equal.
    """
    assert (unit1.physical_type == unit2.physical_type) is True
    assert (unit1.physical_type != unit2.physical_type) is False

@pytest.mark.parametrize("unit1, unit2", equivalent_unit_pairs)
def test_get_physical_type_equivalent_pairs(unit1, unit2):
    """
    Test that `get_physical_type` retrieves the same `PhysicalType`
    instances for equivalent physical types, except for unknown types
    which are not cataloged.
    """
    physical_type1 = physical.get_physical_type(unit1)
    physical_type2 = physical.get_physical_type(unit2)
    assert physical_type1 == physical_type2
    if physical_type1 != "unknown":
        assert physical_type1 is physical_type2

nonequivalent_unit_pairs = [
    (u.m, u.s),
    (u.m ** 18, u.m ** 19),
    (u.N, u.J),
    (u.barn, u.imperial.deg_F),
]

@pytest.mark.parametrize("unit1, unit2", nonequivalent_unit_pairs)
def test_physical_type_instance_inequality(unit1, unit2):
    """
    Test that `physical.PhysicalType` instances for units with different
    dimensionality are considered unequal.
    """
    physical_type1 = physical.PhysicalType(unit1, "ptype1")
    physical_type2 = physical.PhysicalType(unit2, "ptype2")
    assert (physical_type1 != physical_type2) is True
    assert (physical_type1 == physical_type2) is False

physical_type_with_expected_str = [
    (length, "length"),
    (speed, "speed/velocity"),
    (pressure, "energy density/pressure/stress"),
    (u.deg_C.physical_type, "temperature"),
    ((u.J / u.K / u.kg).physical_type, "specific entropy/specific heat capacity"),
]

physical_type_with_expected_repr = [
    (length, "PhysicalType('length')"),
    (speed, "PhysicalType({'speed', 'velocity'})"),
    (pressure, "PhysicalType({'energy density', 'pressure', 'stress'})"),
    (u.deg_C.physical_type, "PhysicalType('temperature')"),
    ((u.J / u.K / u.kg).physical_type,
     "PhysicalType({'specific entropy', 'specific heat capacity'})"),
]

@pytest.mark.parametrize("physical_type, expected_str", physical_type_with_expected_str)
def test_physical_type_str(physical_type, expected_str):
    """Test using `str` on a `PhysicalType` instance."""
    assert str(physical_type) == expected_str

@pytest.mark.parametrize(
    "physical_type, expected_repr", physical_type_with_expected_repr
)
def physical_type_repr(physical_type, expected_repr):
    """Test using `repr` on a `PhysicalType` instance."""
    assert repr(physical_type) == expected_repr

def test_physical_type_hash():
    """Test that a `PhysicalType` instance can be used as a dict key."""
    dictionary = {length: 42}
    assert dictionary[length] == 42

@pytest.mark.parametrize("multiplicand", [list(), 42, 0, -1])
def test_physical_type_multiplication(multiplicand):
    """
    Test that multiplication of a physical type returns `NotImplemented`
    when attempted for an invalid type.
    """
    with pytest.raises(TypeError):
        length * multiplicand

def test_unrecognized_unit_physical_type():
    """
    Test basic functionality for the physical type of an unrecognized
    unit.
    """
    unrecognized_unit = u.Unit("parrot", parse_strict="silent")
    physical_type = unrecognized_unit.physical_type
    assert isinstance(physical_type, physical.PhysicalType)
    assert physical_type == "unknown"

invalid_inputs = [(42,), ("valid input", 42)]

@pytest.mark.parametrize("invalid_input", invalid_inputs)
def test_invalid_physical_types(invalid_input):
    """
    Test that `PhysicalType` cannot be instantiated when one of the
    supplied names is not a string, while making sure that the physical
    type for the unit remains unknown.
    """
    obscure_unit = u.s ** 87
    with pytest.raises(ValueError):
        physical.PhysicalType(obscure_unit, invalid_input)
    assert obscure_unit.physical_type == "unknown"

class TestDefPhysType:

    weird_unit = u.m ** 99
    strange_unit = u.s ** 42

    def test_attempt_to_define_unknown_physical_type(self):
        """Test that a unit cannot be defined as unknown."""
        with pytest.raises(ValueError):
            physical.def_physical_type(self.weird_unit, "unknown")
        assert "unknown" not in physical._unit_physical_mapping

    def test_multiple_same_physical_type_names(self):
        """
        Test that `def_physical_type` raises an exception when it tries to
        set the physical type of a new unit as the name of an existing
        physical type.
        """
        with pytest.raises(ValueError):
            physical.def_physical_type(self.weird_unit, {"time", "something"})
        assert self.weird_unit.physical_type == "unknown"

    def test_expanding_names_for_physical_type(self):
        """
        Test that calling `def_physical_type` on an existing physical
        type adds a new physical type name.
        """
        weird_name = "weird name"
        strange_name = "strange name"

        try:
            physical.def_physical_type(self.weird_unit, weird_name)
            assert (
                self.weird_unit.physical_type == weird_name
            ), f"unable to set physical type for {self.weird_unit}"
        except Exception:
            raise
        finally:  # cleanup added name
            physical._attrname_physical_mapping.pop(weird_name.replace(' ', '_'), None)
            physical._name_physical_mapping.pop(weird_name, None)

        # add both strange_name and weird_name
        try:
            physical.def_physical_type(self.weird_unit, strange_name)
            assert set((self.weird_unit).physical_type) == {
                weird_name,
                strange_name,
            }, "did not correctly append a new physical type name."
        except Exception:
            raise
        finally:  # cleanup added names
            physical._attrname_physical_mapping.pop(strange_name.replace(' ', '_'), None)
            physical._name_physical_mapping.pop(strange_name, None)
            physical._attrname_physical_mapping.pop(weird_name.replace(' ', '_'), None)
            physical._name_physical_mapping.pop(weird_name, None)

    def test_redundant_physical_type(self):
        """
        Test that a physical type name already in use cannot be assigned
        for another unit (excluding `"unknown"`).
        """
        with pytest.raises(ValueError):
            physical.def_physical_type(self.weird_unit, "length")

    @staticmethod
    def _undef_physical_type(unit):
        """Reset the physical type of unit to "unknown"."""
        for name in list(unit.physical_type):
            del physical._unit_physical_mapping[name]
        del physical._physical_unit_mapping[unit._get_physical_type_id()]
        assert unit.physical_type == "unknown"

    def teardown_method(self):
        """
        Remove the definitions of the physical types that were added
        using `def_physical_unit` for testing purposes.
        """
        for unit in [self.weird_unit, self.strange_unit]:
            physical_type = physical.get_physical_type(unit)
            if physical_type != "unknown":
                self._undef_physical_type(unit)
            assert unit.physical_type == "unknown", (
                f"the physical type for {unit}, which was added for"
                f"testing, was not deleted."
            )

@pytest.mark.parametrize("method, expected", [
    ("title", 'Length'), ("isalpha", True), ("isnumeric", False), ("upper", 'LENGTH')
])
def test_that_str_methods_work_with_physical_types(method, expected):
    """
    Test that str methods work for `PhysicalType` instances while issuing
    a deprecation warning.
    """
    with pytest.warns(AstropyDeprecationWarning, match="PhysicalType instances"):
        result_of_method_call = getattr(length, method)()
    assert result_of_method_call == expected

def test_missing_physical_type_attribute():
    """
    Test that a missing attribute raises an `AttributeError`.

    This test should be removed when the deprecated option of calling
    string methods on PhysicalType instances is removed from
    `PhysicalType.__getattr__`.
    """
    with pytest.raises(AttributeError):
        length.not_the_name_of_a_str_or_physical_type_attribute

@pytest.mark.parametrize('ptype_name', ['length', 'speed', 'entropy'])
def test_pickling(ptype_name):
    # Regression test for #11685
    ptype = u.get_physical_type(ptype_name)
    pkl = pickle.dumps(ptype)
    other = pickle.loads(pkl)
    assert other == ptype

def test_physical_types_module_access():
    # all physical type names in dir
    assert set(dir(physical)).issuperset(physical._attrname_physical_mapping.keys())
    assert set(dir(physical)).issuperset(physical.__all__)

    # all physical type can be accessed by name
    for pname in physical._attrname_physical_mapping.keys():
        ptype = physical._attrname_physical_mapping[pname]
        assert hasattr(physical, pname)  # make sure works in lazy load
        assert getattr(physical, pname) is ptype

    # a failed access
    with pytest.raises(AttributeError, match="has no attribute"):
        physical.not_a_valid_physical_type_name


text:
{-+
All of the built-in entities that don't contain any recursive parts (mainly
names).
-}
module HsConstants(module HsConstants,module SpecialNames,HsName) where

import HsName
import HsIdent
import SpecialNames

-- The module that is implicitly imported in all modules: ----------------------
prelude_mod_name' = "Prelude"
mod_Prelude'      = plainModule prelude_mod_name'

-- Module names for constructing original names of standard entities: ----------
--{ -
-- For use with PFE libraries:
mod_Prelude      = plainModule "Prelude"
mod_PreludeList  = plainModule "PreludeList"
mod_PreludeText  = plainModule "PreludeText"
mod_Ix	   = plainModule "Ix"
--}

{-
-- For use with Hugs libraries:
mod_Prelude      = plainModule "Hugs.Prelude"
mod_PreludeList  = mod_Prelude
mod_PreludeText  = mod_Prelude
mod_Ix		 = mod_Prelude
--}

--------------------------------------------------------------------------------

--prelude_mod         = mod_Prelude -- retained for backward compatibility

main_mod path       = moduleName path "Main"

--qualify path m v         = Qual (moduleName path m) v
tuple n            = "(" ++ replicate n ',' ++ ")"

unit_con_name       = Qual mod_Prelude "()"
tuple_con_name n    = Qual mod_Prelude $ tuple n

main_name           = UnQual "main"

unit_tycon_name     = unit_con_name

instance HasSpecialNames HsName where
  fun_tycon_name      = Qual mod_Prelude "->"
  list_tycon_name     = Qual mod_Prelude "[]"
  char_tycon_name     = Qual mod_Prelude "Char"
  tuple_tycon_name n  = tuple_con_name n

instance IsSpecialName HsName where
  is_list_tycon_name  = std_is_list_tycon_name
  is_fun_tycon_name   = std_is_fun_tycon_name
  is_char_tycon_name  = std_is_char_tycon_name
  is_tuple_tycon_name = std_is_tuple_tycon_name

is_unit_tycon_name n = n==unit_tycon_name


text:
// Copyright (C) 2011  Carl Rogers
// Released under MIT License
// license available in LICENSE file, or at http://www.opensource.org/licenses/mit-license.php

#ifndef LIBCNPY_H_
#define LIBCNPY_H_

/**
 *
 */
#include <array/DataType.h>
#include <assert.h>
#include <system/op_boilerplate.h>

#include <algorithm>
#include <complex>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <unordered_map>
#include <vector>

namespace cnpy {

/**
 * The numpy array
 */
struct NpyArray {
  char *data;
  std::vector<unsigned int> shape;
  unsigned int wordSize;
  bool fortranOrder;
  void destruct() { delete[] data; }
};

struct SD_LIB_EXPORT npz_t : public std::map<std::string, NpyArray> {
  void destruct() {
    npz_t::iterator it = this->begin();
    for (; it != this->end(); ++it) (*it).second.destruct();
  }
};

/**
 *
 * @param path
 * @return
 */
SD_LIB_EXPORT char *loadFile(const char *path);

/**
 *
 * @return
 */
char BigEndianTest();

/**
 *
 * @param t
 * @return
 */
SD_LIB_EXPORT char mapType(const std::type_info &t);

template <typename T>
SD_LIB_EXPORT char mapType();

/**
 *
 * @param T the type of the ndarray
 * @param data the data for the ndarray
 * @param shape the shape of the ndarray
 * @param ndims the rank of the ndarray
 * @return
 */
template <typename T>
SD_LIB_EXPORT std::vector<char> createNpyHeader(const void *data, const unsigned int *shape, const unsigned int ndims,
                                                unsigned int wordSize = 4);
/**
 * Parse the numpy header from
 * the given file
 * based on the pointers passed in
 * @param fp the file to parse from
 * @param wordSize the size of
 * the individual elements
 * @param shape
 * @param ndims
 * @param fortranOrder
 */
SD_LIB_EXPORT void parseNpyHeader(FILE *fp, unsigned int &wordSize, unsigned int *&shape, unsigned int &ndims,
                                  bool &fortranOrder);

/**
 * Parse the numpy header from
 * the given file
 * based on the pointers passed in
 * @param header the file to parse from
 * @param word_size the size of
 * the individual elements
 * @param shape
 * @param ndims
 * @param fortran_order
 */
SD_LIB_EXPORT void parseNpyHeaderPointer(const char *header, unsigned int &word_size, unsigned int *&shape,
                                         unsigned int &ndims, bool &fortran_order);
/**
 *
 * @param fp
 * @param nrecs
 * @param global_header_size
 * @param global_header_offset
 */
SD_LIB_EXPORT void parseZipFooter(FILE *fp, unsigned short &nrecs, unsigned int &global_header_size,
                                  unsigned int &global_header_offset);

/**
 *
 * @param fname
 * @param varname
 * @return
 */
SD_LIB_EXPORT NpyArray npzLoad(std::string fname, std::string varname);

/**
 *
 * @param fname
 * @return
 */
SD_LIB_EXPORT NpyArray npyLoad(std::string fname);

/**
 * Parse the numpy header from
 * the given file
 * based on the pointers passed in
 * @param fp the file to parse from
 * @param wordSize the size of
 * the individual elements
 * @param shape
 * @param ndims
 * @param fortranOrder
 */
SD_LIB_EXPORT void parseNpyHeaderStr(std::string header, unsigned int &wordSize, unsigned int *&shape,
                                     unsigned int &ndims, bool &fortranOrder);

/**
 *
 * @param fp
 * @return
 */
SD_LIB_EXPORT int *shapeFromFile(FILE *fp);

/**
 *
 * @param data
 * @return
 */
SD_LIB_EXPORT int *shapeFromPointer(char *data);

/**
 * Load the numpy array from the given file.
 * @param fp the file to load
 * @return the loaded array
 */
SD_LIB_EXPORT NpyArray loadNpyFromFile(FILE *fp);

/**
 * Load the numpy array archive from the given file.
 * @param fp the file to load
 * @return the loaded archive
 */
SD_LIB_EXPORT npz_t npzLoad(FILE *fp);
/**
 *
 * @param data
 * @return
 */
SD_LIB_EXPORT NpyArray loadNpyFromPointer(char *data);

/**
 *
 * @param data
 * @return
 */
SD_LIB_EXPORT NpyArray loadNpyFromHeader(char *data);

SD_LIB_EXPORT npz_t npzLoad(std::string fname);

SD_LIB_EXPORT sd::DataType dataTypeFromHeader(char *data);
/**
 * Parse the numpy header from
 * the given file
 * based on the pointers passed in
 * @param fp the file to parse from
 * @param word_size the size of
 * the individual elements
 * @param shape
 * @param ndims
 * @param fortran_order
 */
SD_LIB_EXPORT void parseNpyHeader(std::string header, unsigned int &word_size, unsigned int *&shape,
                                  unsigned int &ndims, bool &fortran_order);

/**
 *
 * @tparam T
 * @param i
 * @param pad
 * @param padval
 * @return
 */
template <typename T>
SD_INLINE std::string tostring(T i, int pad = 0, char padval = ' ') {
  std::stringstream s;
  s << i;
  return s.str();
}

template <typename T>
SD_LIB_EXPORT void npy_save(std::string fname, const T *data, const unsigned int *shape, const unsigned int ndims,
                            std::string mode = "w");

}  // namespace cnpy

/**
 *
 * @tparam T
 * @param lhs
 * @param rhs
 * @return
 */
template <typename T>
SD_LIB_EXPORT std::vector<char> &operator+=(std::vector<char> &lhs, const T rhs);

#endif


text:
package io.github.greyp9.arwo.lib.interop.dcom.command.core;

import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;

import java.net.UnknownHostException;

public class WshShell {
    private final IJIDispatch dispatch;

    public WshShell(final IJIDispatch dispatch) {
        this.dispatch = dispatch;
    }

    public final IJIDispatch getDispatch() {
        return dispatch;
    }

    public final String getCurrentDirectory() throws JIException {
        final JIVariant variant = dispatch.get("CurrentDirectory");  // i18n
        return variant.getObjectAsString().getString();
    }

    public final WshScriptExec exec(final String command) throws JIException {
        final String commandLine = "%COMSPEC% /c " + command;  // i18n lib
        final Object[] params = { new JIString(commandLine) };
        final JIVariant[] variants = dispatch.callMethodA("Exec", params);  // i18n lib
        return WshScriptExec.Factory.create(variants);
    }

    public static final class Factory {
        private Factory() {
        }

        public static JISession createSession(final String domain, final String user, final String password) {
            JISystem.setAutoRegisteration(true);
            final JISession session = JISession.createSession(domain, user, password);
            session.useSessionSecurity(true);
            return session;
        }

        public static void destroySession(final JISession session) throws JIException {
            JISession.destroySession(session);
        }

        public static WshShell createShell(
                final String host, final JISession session) throws JIException, UnknownHostException {
            final JIProgId progId = JIProgId.valueOf("WScript.Shell");
            final JIComServer comServer = new JIComServer(progId, host, session);
            final IJIComObject unknown = comServer.createInstance();
            final IJIComObject comObject = unknown.queryInterface(IJIDispatch.IID);
            final IJIDispatch dispatch = (IJIDispatch) JIObjectFactory.narrowObject(comObject);
            return new WshShell(dispatch);
        }

        public static void releaseShell(final WshShell shell) throws JIException {
            shell.getDispatch().release();
        }
    }
}


text:
module.exports = function(grunt) {
  var path = require("path");

  grunt.registerTask("npm-install", "Runs npm install.", function() {
    var done    = this.async();
    var fs      = require("fs");
    var npm     = require("npm");
    var options = this.options({
      dest: "./out"
    });

    // Only install npm if modules are not installed in src.
    var skipInstall = fs.existsSync(path.join(options.dest, "node_modules"));
    if (skipInstall) {
      grunt.log.writeln("Skipping npm install.");
      grunt.log.writeln(
          "A 'node_modules' directory was found.");
      grunt.log.writeln(
          "If the tests fail due to dependencies issues try delating it and");
      grunt.log.writeln("let me install the dependencies from scretch.");
      return done();
    }

    npm.load({
      prefix: options.dest
    }, function(err) {
      if (err) { return done(err); }

      npm.commands.install(function (err, data) {
        done(err);
      });
      npm.on("log", grunt.log.write.bind(grunt.log));
    });
  });
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Contact UF Admissions</title>

	  <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0">

    <link href="style.css" rel="stylesheet">

    Home /

    Contact Us /

						<form action="" id="contact-form" class="form-horizontal">
						  <fieldset>
						    <legend>Contact UF Admissions</legend>

						      Your Name

                                <input class="input-xlarge" type="text" placeholder="First Name" style="margin-bottom: 5px;">

						  <input type="text" class="input-xlarge " placeholder="Last Name" name="last" id="last">

						      Email Address

						        <input type="email" class="input-xlarge" name="email" placeholder="name@domain.com" id="email">

						      Birthdate

                                  <input class="input-large" type="text" name="date" id="date">

                                Admission Status:
                                <select class="span4" name="select-choice-0" id="select-choice-0">
                        <option value="first">First-Time Freshman</option>
                        <option value="transfer">Transfer Student</option>
                        <option value="grad">Graduate Student</option>
                        <option value="intl">International Student</option>
                        </select>

						      Comments

						        <textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>

			            <button type="submit" class="btn btn-primary btn-large">Submit</button>
	    			      <button type="reset" class="btn-large">Cancel</button>

						  </fieldset>
						</form>


text:
""" Модуль с классом `CopyAction`

"""

import logging
import os
import shutil

from action import OutDirCreatingAction

class CopyAction(OutDirCreatingAction):
    """ Действие, в котором входной файл копируется в выходную папку

    """

    def run(self, input_url: str, action_params: dict, out_dir_path: str, simulate: bool) -> None:
        super().run(input_url, action_params, out_dir_path, simulate)
        out_path = os.path.join(out_dir_path, os.path.split(input_url)[1])
        if os.path.exists(out_path):
            msg = 'Output file "{}" already exists'.format(out_path)
            logging.error(msg)
            raise FileExistsError(msg)
        logging.info('Copying file from "{}" to "{}"...'.format(input_url, out_path))
        if not simulate:
            shutil.copy(input_url, out_path)
        logging.info('Done')


text:
class AddUserToItem < ActiveRecord::Migration
  def self.up
    add_column :items, :user_id, :integer
  end

  def self.down
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;

namespace IncludeDay.Services
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

        }
    }
}


text:
#ifndef _GENERIC_LIST_H_
#define _GENERIC_LIST_H_

#include "fsl_common.h"
/*!
 * @addtogroup GenericList
 * @{
 */

/*!*********************************************************************************
*************************************************************************************
* Include
*************************************************************************************
********************************************************************************** */

/*! *********************************************************************************
*************************************************************************************
* Public macro definitions
*************************************************************************************
********************************************************************************** */
#ifndef GENERIC_LIST_LIGHT
#define GENERIC_LIST_LIGHT (0)
#endif
/*! *********************************************************************************
*************************************************************************************
* Public type definitions
*************************************************************************************
********************************************************************************** */
/*! @brief The list status */
typedef enum _list_status
{
    kLIST_Ok             = kStatus_Success,                   /*!< Success */
    kLIST_DuplicateError = MAKE_STATUS(kStatusGroup_LIST, 1), /*!< Duplicate Error */
    kLIST_Full           = MAKE_STATUS(kStatusGroup_LIST, 2), /*!< FULL */
    kLIST_Empty          = MAKE_STATUS(kStatusGroup_LIST, 3), /*!< Empty */
    kLIST_OrphanElement  = MAKE_STATUS(kStatusGroup_LIST, 4), /*!< Orphan Element */
    kLIST_NotSupport     = MAKE_STATUS(kStatusGroup_LIST, 5), /*!< Not Support  */
} list_status_t;

/*! @brief The list structure*/
typedef struct list_label
{
    struct list_element_tag *head; /*!< list head */
    struct list_element_tag *tail; /*!< list tail */
    uint16_t size;                 /*!< list size */
    uint16_t max;                  /*!< list max number of elements */
} list_label_t, *list_handle_t;
#if (defined(GENERIC_LIST_LIGHT) && (GENERIC_LIST_LIGHT > 0U))
/*! @brief The list element*/
typedef struct list_element_tag
{
    struct list_element_tag *next; /*!< next list element   */
    struct list_label *list;       /*!< pointer to the list */
} list_element_t, *list_element_handle_t;
#else
/*! @brief The list element*/
typedef struct list_element_tag
{
    struct list_element_tag *next; /*!< next list element   */
    struct list_element_tag *prev; /*!< previous list element */
    struct list_label *list;       /*!< pointer to the list */
} list_element_t, *list_element_handle_t;
#endif
/*! *********************************************************************************
*************************************************************************************
* Public prototypes
*************************************************************************************
********************************************************************************** */
/*******************************************************************************
 * API
 ******************************************************************************/

#if defined(__cplusplus)
extern "C" {
#endif /* _cplusplus */
/*!
 * @brief Initialize the list.
 *
 * This function initialize the list.
 *
 * @param list - List handle to initialize.
 * @param max - Maximum number of elements in list. 0 for unlimited.
 */
void LIST_Init(list_handle_t list, uint32_t max);

/*!
 * @brief Gets the list that contains the given element.
 *
 *
 * @param element - Handle of the element.
 * @retval NULL if element is orphan, Handle of the list the element is inserted into.
 */
list_handle_t LIST_GetList(list_element_handle_t element);

/*!
 * @brief Links element to the head of the list.
 *
 * @param list - Handle of the list.
 * @param element - Handle of the element.
 * @retval kLIST_Full if list is full, kLIST_Ok if insertion was successful.
 */
list_status_t LIST_AddHead(list_handle_t list, list_element_handle_t element);

/*!
 * @brief Links element to the tail of the list.
 *
 * @param list - Handle of the list.
 * @param element - Handle of the element.
 * @retval kLIST_Full if list is full, kLIST_Ok if insertion was successful.
 */
list_status_t LIST_AddTail(list_handle_t list, list_element_handle_t element);

/*!
 * @brief Unlinks element from the head of the list.
 *
 * @param list - Handle of the list.
 *
 * @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
 */
list_element_handle_t LIST_RemoveHead(list_handle_t list);

/*!
 * @brief Gets head element handle.
 *
 * @param list - Handle of the list.
 *
 * @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
 */
list_element_handle_t LIST_GetHead(list_handle_t list);

/*!
 * @brief Gets next element handle for given element handle.
 *
 * @param element - Handle of the element.
 *
 * @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
 */
list_element_handle_t LIST_GetNext(list_element_handle_t element);

/*!
 * @brief Gets previous element handle for given element handle.
 *
 * @param element - Handle of the element.
 *
 * @retval NULL if list is empty, handle of removed element(pointer) if removal was successful.
 */
list_element_handle_t LIST_GetPrev(list_element_handle_t element);

/*!
 * @brief Unlinks an element from its list.
 *
 * @param element - Handle of the element.
 *
 * @retval kLIST_OrphanElement if element is not part of any list.
 * @retval kLIST_Ok if removal was successful.
 */
list_status_t LIST_RemoveElement(list_element_handle_t element);

/*!
 * @brief Links an element in the previous position relative to a given member of a list.
 *
 * @param list - Handle of the list.
 * @param element - Handle of the element.
 * @param newElement - New element to insert before the given member.
 *
 * @retval kLIST_OrphanElement if element is not part of any list.
 * @retval kLIST_Ok if removal was successful.
 */
list_status_t LIST_AddPrevElement(list_element_handle_t element, list_element_handle_t newElement);

/*!
 * @brief Gets the current size of a list.
 *
 * @param list - Handle of the list.
 *
 * @retval Current size of the list.
 */
uint32_t LIST_GetSize(list_handle_t list);

/*!
 * @brief Gets the number of free places in the list.
 *
 * @param list - Handle of the list.
 *
 * @retval Available size of the list.
 */
uint32_t LIST_GetAvailableSize(list_handle_t list);

/* @} */

#if defined(__cplusplus)
}
#endif
/*! @}*/
#endif /*_GENERIC_LIST_H_*/