text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using DAO;
using Entities;
using Internal;

namespace Controllers
{
	public class CtrSignUp : IController
    {
		/// <summary>
		/// The data layer to use
		/// </summary>
        DAO_BD_Users data = DAO_BD_Users.Instance();

		/// <summary>
		/// Check if a mail address is valid or not
		/// </summary>
		/// <param name="mail">Mail to validate</param>
		private bool ValidMail(string mail)
		{
			/// Regular expression that validates an e-mail address (someone@example.com)
			/// see http://msdn.microsoft.com/en-us/library/ff650303.aspx
			Regex reg = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");

			/// Returns True if the mail is valid
			return reg.IsMatch(mail);
		}

		/// <summary>
		/// Check if a string is valid to use as a person name.
		/// <para>It is NOT valid if:</para>
		/// <para>- Contains a number or</para>
		/// <para>- A special character or</para>
		/// <para>- Only white spaces</para>
		/// </summary>
		/// <param name="name">The name to check</param>
		/// <returns>True if valid, else False</returns>
		public bool ValidName(string name)
		{
			// Check that the name doesn't has only spaces nor numbers
			return (!String.IsNullOrWhiteSpace(name) && !Regex.IsMatch(name, @"\d"));
		}

		/// <summary>
		/// Check if a string is valid to use as user name.
		/// It is not valid if its empty
		/// </summary>
		/// <param name="username">User name to chack</param>
		/// <returns>True if it is valid, otherwise False</returns>
		public bool ValidUserName(string username)
		{
			return !String.IsNullOrWhiteSpace(username);
		}

		/// <summary>
		/// Check if a password is valid.
		/// <para>It is NOT valid if:</para>
		/// <para>- It is empty or</para>
		/// <para>- It has only white spaces or</para>
		/// <para>- has less than 8 characters or more than 2000</para>
		/// </summary>
		/// <param name="password">The password in plain text to check</param>
		/// <returns>True if the password is valid, otherwise False</returns>
		public bool ValidPassword(string password)
		{
			return (!String.IsNullOrWhiteSpace(password) && password.Length >= 8 && password.Length < 2000);
		}

		/// <summary>
		/// Create a new user and store it
		/// </summary>
		/// <param name="name">Name of the user</param>
		/// <param name="lastname">Last name of the user</param>
		/// <param name="username">User name to use</param>
		/// <param name="mail">Mail of the user</param>
		/// <param name="passwords">An array of two strings with the same password in plain text</param>
		/// <param name="birthdate">Birthdate of the user</param>
		/// <param name="avatar">Path of the avatar picture</param>
        public void AddNewUser(string name, string lastname, string username,
									string mail, string password,
									DateTime birthdate)
        {
            if (!ValidUserName(username))
                throw new Exception("El nombre de usuario no puede estar vacío");

            // Check if the user name is already in use
            if (data.Exist(username))
                throw new Exception("El nombre de usuario ya existe.");

			if (!ValidName(name))
				throw new Exception("El nombre ingresado contiene caracteres invalidos o esta vacío.");

			if (!ValidName(lastname))
				throw new Exception("El apellido ingresado contiene caracteres invalidos o esta vacío.");

			if (!ValidMail(mail))
				throw new Exception("El mail ingresado no es valido.");

			// Check if the password is valid and secure
			if (!ValidPassword(password))
				throw new Exception("La contraseña no puede estar vacía ni tener menos de 8 caracteres ni mas de 2000");

            // Check if birthdate is on the past
            if (birthdate.Date > DateTime.Now.Date)
                throw new Exception("La fecha de nacimiento no puede estar en tiempo futuro.");

            // Encrypt the password using Bcrypt
            const int workFactor = 13;
            var password_hashed = BCrypt.Net.BCrypt.HashPassword(password, workFactor);

			// If all the information was valid, create the new user without an avatar
            User user = new User(name, lastname, username, mail, birthdate, password_hashed, null);

			// Save the user
            data.Add(user);
        }

        /// <summary>
        /// Change the avatar attribute of a user.
        /// </summary>
        /// <param name="u">User that will change his avatar</param>
        /// <param name="fileName">The name of the file in the local server.</param>
        public void SetAvatar(User u, string fileName)
        {
            if (u == null)
                throw new Exception("El usuario no pudo ser identificado.");

            if (fileName == null)
                throw new Exception("La imagen no se ha podido ser accedido para su almacenamiento.");

            data.SetAvatar(u, fileName);
        }

        /// <summary>
        /// Get a user with the a specific user name
        /// </summary>
        /// <param name="username">The username to find</param>
        /// <returns>The user that has the entered username</returns>
        public User GetUserByUserName(string username)
        {
            return data.GetElementByUserName(username);
        }
    }
}


text:
FROM node:8-alpine as builder
MAINTAINER tribou

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install npm/yarn dependencies
RUN apk update && apk upgrade && \
    apk add --no-cache git openssh

# Install all dependencies
ADD package.json /usr/src/app/
ADD yarn.lock /usr/src/app/
ADD .npm-packages-offline-cache /usr/src/app/.npm-packages-offline-cache/
ADD bin /usr/src/app/bin/
RUN npm run yarn

# Add app
ADD . /usr/src/app/

# Build app
RUN npm run build

# Remove all but runtime dependencies
RUN npm run yarn -- --prod

# Remove build-related files
RUN rm -rf .npm-packages-offline-cache

# Create application image
FROM node:8-alpine
COPY --from=builder /usr/src/app /usr/src/app/
WORKDIR /usr/src/app

EXPOSE 8000

ENTRYPOINT ["npm", "run"]
CMD ["start"]

redpajama_set_name: RedPajamaGithub


text:
import pylcmodel

def test_integer():
    assert 1 == pylcmodel.namelist.parser("1").number()

def test_float():
    assert 2.3 == pylcmodel.namelist.parser("2.3").number()

def test_exponent():
    assert 1.2e4 == pylcmodel.namelist.parser("1.2e4").number()

def test_negative():
    assert -7.9 == pylcmodel.namelist.parser("-7.9").number()

def test_numberlist():
    assert [1, 2, 3.4] == pylcmodel.namelist.parser("1 2 3.4").numberlist()

def test_strings():
    assert "hello world" == pylcmodel.namelist.parser("'hello world'").string()

def test_unquoted_string():
    assert "helloworld" == pylcmodel.namelist.parser("helloworld\n").string()

def test_string_list():
    assert ["hello", "world"] == pylcmodel.namelist.parser("'hello' 'world'").stringlist()

def test_truth():
    assert pylcmodel.namelist.parser("T").truth()

def test_falsehood():
    assert not pylcmodel.namelist.parser("F").falsehood()

def test_key_value_pair():
    assert ("KEY", "value") == pylcmodel.namelist.parser("key = 'value'").pair()

def test_pairlist():
    assert [("KEY", "value")] == pylcmodel.namelist.parser("key = 'value'").pairlist()

def test_namelist():
    namelist_string = """
    $name
     key='value'
     unquoted = test,
     other=2.3
    $END
    """.strip()
    target = ("name",
              {"KEY": "value", "OTHER": 2.3, "UNQUOTED": "test"})
    assert target == pylcmodel.namelist.parser(namelist_string).namelist()

def test_namelist_two():
    namelist_string = """
    $name
     SPTYPE = liver-11 ,
    $END
    """.strip()
    assert ("name", {"SPTYPE": "liver-11"}) == pylcmodel.namelist.parser(namelist_string).namelist()

def test_control_file():
    with open("tests/test_data/lcm.control") as fin:
        control_file_text = fin.read()
    assert ("LCMODL", {
        "KEY": 123456789,
        "LCSV": 11,
        "OWNER": "",
        "FILTAB": "test_data/svs_97.TABLE",
        "DELTAT": 0.000833,
        "NUNFIL": 1024,
        "HZPPPM": 123.226103,
        "LCOORD": 9,
        "TITLE": "SVS_97",
        "FILRAW": "test_data/svs_97.RAW",
        "LTABLE" :7,
        "FILCSV": "test_data/svs_97.CSV",
        "FILBAS": "/media/mrs_proc/ben/97ms demo/LCModel files/97_basis_set.basis",
        "FILPS": "test_data/svs_97.PS",
        "FILCOO": "test_data/svs_97.COORD"
    }) == pylcmodel.namelist.reads(control_file_text.strip())

def test_write_number():
    target = """ $LCMODL
 NUM = 4,
 $END
"""
    assert target == pylcmodel.namelist.dumps("LCMODL", {"NUM": 4})

def test_write_string():
    target = """ $LCMODL
 STR = 'test',
 $END
"""
    assert target == pylcmodel.namelist.dumps("LCMODL", {"STR": "test"})

def test_write_truth():
    target = """ $LCMODL
 TRUE = T,
 $END
"""
    assert target == pylcmodel.namelist.dumps("LCMODL", {"TRUE": True})

def test_write_falsehood():
    target = """ $LCMODL
 FALSE = F,
 $END
"""
    assert target == pylcmodel.namelist.dumps("LCMODL", {"FALSE": False})


text:
class Solution:
	matrix=[]
	xlimit=0
	ylimit=0
	stack=[]
	total_covered=[]
	current_covered=[]
	result=[]

	Q=[]

	def findarea(self,matrix):
		self.matrix = matrix
		self.xlimit=len(matrix) #8
		self.ylimit=len(matrix[0])#5

		for y in range(self.ylimit):
			for x in range(self.xlimit):
				if matrix[x][y]==1 and [x,y] not in self.total_covered:
					self.current_covered = [[x,y]]
					self.stack=[[x,y]]

					self.DFS(x,y)

					if len(self.current_covered) > 1:
						self.result.append(self.current_covered)
						for pair in self.current_covered:
							 self.total_covered.append(pair)
		return self.result

	def DFS(self,x,y):
		#go right
		if x+1<self.xlimit and self.matrix[x+1][y]==1 and [x+1,y] not in self.stack:#can go: (check limit, value is 1, not in stack)
			self.stack.append([x+1,y])#push future node to stack
			self.current_covered.append([x+1,y])# push future node to current coverage list
			self.DFS(x+1,y)#move forward
			self.stack.pop()

		#go left
		if x>0 and self.matrix[x-1][y]==1 and [x-1,y] not in self.stack:#can go: (check limit, value is 1, not in stack)
			self.stack.append([x-1,y])#push future node to stack
			self.current_covered.append([x-1,y])# push future node to current coverage list
			self.DFS(x-1,y)#move forward
			self.stack.pop()

		#go down
		if y+1<self.ylimit and self.matrix[x][y+1]==1 and [x,y+1] not in self.stack:#can go: (check limit, value is 1, not in stack)
			self.stack.append([x,y+1])#push future node to stack
			self.current_covered.append([x,y+1])# push future node to current coverage list
			self.DFS(x,y+1)#move forward
			self.stack.pop()

		#go up
		if y>0 and self.matrix[x][y-1]==1 and [x,y-1] not in self.stack:#can go: (check limit, value is 1, not in stack)
			self.stack.append([x,y-1])#push future node to stack
			self.current_covered.append([x,y-1])# push future node to current coverage list
			self.DFS(x,y-1)#move forward
			self.stack.pop()
		return

		def BFS(x,y):
			pass

matrix=[[0 for y in range(5)] for x in range(8)]
matrix[7][0]=1
matrix[7][1]=1
matrix[4][1]=1
matrix[3][2]=1
matrix[1][3]=1
matrix[2][3]=1
matrix[3][3]=1
matrix[4][3]=1
matrix[4][4]=1

s=Solution()
result=s.findarea(matrix)

for i in result:
	print i


text:
package com.mistraltech.bog.examples.extended;

import com.mistraltech.bog.examples.model.AccountManager;
import org.junit.Test;

import static com.mistraltech.bog.examples.extended.builder.AccountManagerBuilder.anAccountManager;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class AccountManagerTest {
    @Test
    public void canCreateAccountManagerWithDefaultName() {
        AccountManager steve = anAccountManager().build();
        assertThat(steve.getName(), is(equalTo("Steve")));
    }

    @Test
    public void canCreateAccountManagerWithSpecifiedName() {
        AccountManager george = anAccountManager().withName("George").build();
        assertThat(george.getName(), is(equalTo("George")));
    }
}


text:
package fs

import (
	"fmt"
	"hash"
	"io"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"github.com/pkg/xattr"
)

// boolTrueHashValue is used when we need to write something indicating a bool in the input.
var boolTrueHashValue = []byte{2}

// A PathHasher is responsible for hashing & remembering paths.
type PathHasher struct {
	new       func() hash.Hash
	memo      map[string][]byte
	wait      map[string]*pendingHash
	mutex     sync.RWMutex
	root      string
	xattrName string
	useXattrs bool
	algo      string
}

type pendingHash struct {
	Ch   chan struct{}
	Hash []byte
	Err  error
}

// NewPathHasher returns a new PathHasher based on the given root directory.
func NewPathHasher(root string, useXattrs bool, hash func() hash.Hash, algo string) *PathHasher {
	var hashSuffix string
	if algo != "sha1" {
		hashSuffix = fmt.Sprintf("_%s", algo)
	}
	return &PathHasher{
		new:       hash,
		memo:      map[string][]byte{},
		wait:      map[string]*pendingHash{},
		root:      root,
		useXattrs: useXattrs,
		xattrName: "user.plz_hash" + hashSuffix,
		algo:      algo,
	}
}

// Size returns the size of the hash this hasher will return, in bytes.
func (hasher *PathHasher) Size() int {
	return hasher.new().Size()
}

// NewHash returns a new hash.Hash instance from this hasher.
func (hasher *PathHasher) NewHash() hash.Hash {
	return hasher.new()
}

// DisableXattrs turns off xattr support, which bypasses using them to record file hashes.
func (hasher *PathHasher) DisableXattrs() {
	hasher.useXattrs = false
}

// AlgoName returns the name of the algorithm. Used to aid with better error messages.
func (hasher *PathHasher) AlgoName() string {
	return hasher.algo
}

// Hash hashes a single path.
// It is memoised and so will only hash each path once, unless recalc is true which will
// then force a recalculation of it.
// If store is true then the hash may be stored permanently; this should not be set for files that
// are user-controlled.
// TODO(peterebden): ensure that xattrs are marked correctly on cache retrieval.
func (hasher *PathHasher) Hash(path string, recalc, store, timestamp bool) ([]byte, error) {
	path = hasher.ensureRelative(path)
	if !recalc {
		hasher.mutex.RLock()
		cached, present := hasher.memo[path]
		hasher.mutex.RUnlock()
		if present {
			return cached, nil
		}
	}
	// This check is important; if the file doesn't exist now, we don't want that
	// recorded forever in hasher.wait since it might get created later.
	if !PathExists(path) {
		return nil, fmt.Errorf("cannot calculate hash for %s: %s", path, os.ErrNotExist)
	}
	hasher.mutex.Lock()
	if pending, present := hasher.wait[path]; present {
		hasher.mutex.Unlock()
		<-pending.Ch
		return pending.Hash, pending.Err
	}
	pending := &pendingHash{Ch: make(chan struct{})}
	hasher.wait[path] = pending
	hasher.mutex.Unlock()
	result, err := hasher.hash(path, store, !recalc, timestamp)
	hasher.mutex.Lock()
	if err == nil {
		hasher.memo[path] = result
	}
	delete(hasher.wait, path)
	hasher.mutex.Unlock()
	pending.Hash = result
	pending.Err = err
	close(pending.Ch)
	return result, err
}

// MustHash is as Hash but panics on error.
func (hasher *PathHasher) MustHash(path string, timestamp bool) []byte {
	// TODO(jpoole): should this print the timestamp hash
	hash, err := hasher.Hash(path, false, false, timestamp)
	if err != nil {
		panic(err)
	}
	return hash
}

// MoveHash is used when we move files from tmp to out and there was one there before; that's
// the only case in which the hash of a filepath could change.
func (hasher *PathHasher) MoveHash(oldPath, newPath string, copy bool) {
	oldPath = hasher.ensureRelative(oldPath)
	newPath = hasher.ensureRelative(newPath)
	hasher.mutex.Lock()
	defer hasher.mutex.Unlock()
	if oldHash, present := hasher.memo[oldPath]; present {
		hasher.memo[newPath] = oldHash
		// If the path is in plz-out/tmp we aren't ever going to use it again, so free some space.
		if !copy && strings.HasPrefix(oldPath, "plz-out/tmp") {
			delete(hasher.memo, oldPath)
		}
	}
}

// SetHash is used to directly set a hash for a path.
// This is used for remote files where we download them & therefore know the hash as they come in.
// TODO(peterebden): We should probably use this more for things like caches and so forth...
func (hasher *PathHasher) SetHash(path string, hash []byte) {
	hasher.mutex.Lock()
	hasher.memo[path] = hash
	hasher.mutex.Unlock()
	hasher.storeHash(path, hash)
}

func (hasher *PathHasher) hash(path string, store, read, timestamp bool) ([]byte, error) {
	// Try to read xattrs first so we don't have to hash the whole thing.
	if read && strings.HasPrefix(path, "plz-out/") && hasher.useXattrs {
		if b, err := xattr.LGet(path, hasher.xattrName); err == nil {
			return b, nil
		}
	}
	h := hasher.new()
	info, err := os.Lstat(path)
	if err == nil && info.Mode()&os.ModeSymlink != 0 {
		// Handle symlinks specially (don't attempt to read their contents).
		dest, err := os.Readlink(path)
		if err != nil {
			return nil, err
		}
		// Write something arbitrary indicating this is a symlink.
		// This isn't quite perfect - it could potentially get mixed up with a file with the
		// appropriate contents, but that is not really likely.
		h.Write(boolTrueHashValue)
		if rel := hasher.ensureRelative(dest); (rel != dest || !filepath.IsAbs(dest)) && !filepath.IsAbs(path) {
			// Inside the root of our repo so it's something we manage - just hash its (relative) destination
			h.Write([]byte(rel))
		} else {
			// Outside the repo; it's a system tool, so we hash its contents.
			err := hasher.fileHash(h, path)
			return h.Sum(nil), err
		}
		return h.Sum(nil), nil
	} else if err == nil && info.IsDir() {
		err = WalkMode(path, func(p string, mode Mode) error {
			if mode.IsSymlink() {
				// Is a symlink, must verify that it's not absolute.
				deref, err := os.Readlink(p)
				if err != nil {
					return err
				}
				if filepath.IsAbs(deref) {
					log.Warning("Symlink %s has an absolute target %s, that will likely be broken later", p, deref)
				}
				// Deliberately do not attempt to read it. We will read the contents later since
				// it is a link within the temp dir anyway, and if it's a link to a directory
				// it can introduce a cycle.
				// Just write something to the hash indicating that we found something here,
				// otherwise rules might be marked as unchanged if they added additional symlinks.
				h.Write(boolTrueHashValue)
			} else if !mode.IsDir() {
				return hasher.fileHash(h, p)
			}
			return nil
		})
	} else {
		if timestamp {
			err = hasher.timestampHash(h, path) // hash using the last modified timestamp instead
		} else {
			err = hasher.fileHash(h, path) // let this handle any other errors
		}
	}
	hash := h.Sum(nil)
	if err != nil {
		return hash, err
	} else if store && hasher.useXattrs {
		hasher.storeHash(path, hash)
	}
	return hash, err
}

// storeHash stores the hash of a file on it as an xattr.
// This is best-effort since if it fails we can always fall back to a slower but reliable rehash.
func (hasher *PathHasher) storeHash(path string, hash []byte) {
	// Only ever store hashes on output files.
	if !strings.HasPrefix(path, "plz-out/") {
		return
	}
	if err := xattr.LSet(path, hasher.xattrName, hash); err != nil && os.IsPermission(err) {
		// If we get a permission denied, that may be because the output file was readonly.
		// Cheekily attempt to chmod it into submission.
		if info, err := os.Lstat(path); err == nil {
			if err := os.Chmod(path, info.Mode()|0220); err == nil {
				xattr.LSet(path, hasher.xattrName, hash)
				os.Chmod(path, info.Mode())
			}
		}
	}
}

// Calculate the hash of a single file based on it's content
func (hasher *PathHasher) fileHash(h hash.Hash, filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	_, err = io.Copy(h, file)
	file.Close()
	return err
}

// Calculate the hash of a single file based on it's last modified timestamp
func (hasher *PathHasher) timestampHash(h hash.Hash, filename string) error {
	file, err := os.Lstat(filename)
	if err != nil {
		return err
	}
	// This doesn't account for the last changed time on macos which is set when modifying permissions etc.
	h.Write([]byte(file.ModTime().UTC().String()))
	return err
}

// ensureRelative ensures a path is relative to the repo root.
// This is important for getting best performance from memoizing the path hashes.
func (hasher *PathHasher) ensureRelative(path string) string {
	if strings.HasPrefix(path, hasher.root) {
		return strings.TrimLeft(strings.TrimPrefix(path, hasher.root), "/")
	}
	return path
}


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

namespace MongoDB.Bson.Serialization.Serializers
{
    /// <summary>
    /// Represents a serializer for three-dimensional arrays.
    /// </summary>
    /// <typeparam name="TItem">The type of the elements.</typeparam>
    public class ThreeDimensionalArraySerializer<TItem> :
        SealedClassSerializerBase<TItem[,,]>,
        IChildSerializerConfigurable
    {
        // private fields
        private readonly IBsonSerializer<TItem> _itemSerializer;

        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ThreeDimensionalArraySerializer{TItem}"/> class.
        /// </summary>
        public ThreeDimensionalArraySerializer()
            : this(BsonSerializer.LookupSerializer<TItem>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ThreeDimensionalArraySerializer{TItem}"/> class.
        /// </summary>
        /// <param name="itemSerializer">The item serializer.</param>
        public ThreeDimensionalArraySerializer(IBsonSerializer<TItem> itemSerializer)
        {
            _itemSerializer = itemSerializer;
        }

        // public properties
        /// <summary>
        /// Gets the item serializer.
        /// </summary>
        /// <value>
        /// The item serializer.
        /// </value>
        public IBsonSerializer<TItem> ItemSerializer
        {
            get { return _itemSerializer; }
        }

        // public methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <returns>An object.</returns>
        protected override TItem[,,] DeserializeValue(BsonDeserializationContext context)
        {
            var bsonReader = context.Reader;
            EnsureBsonTypeEquals(bsonReader, BsonType.Array);

            bsonReader.ReadStartArray();
            var outerList = new List<List<List<TItem>>>();
            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                bsonReader.ReadStartArray();
                var middleList = new List<List<TItem>>();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.ReadStartArray();
                    var innerList = new List<TItem>();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var item = context.DeserializeWithChildContext(_itemSerializer);
                        innerList.Add(item);
                    }
                    bsonReader.ReadEndArray();
                    middleList.Add(innerList);
                }
                bsonReader.ReadEndArray();
                outerList.Add(middleList);
            }
            bsonReader.ReadEndArray();

            var length1 = outerList.Count;
            var length2 = (length1 == 0) ? 0 : outerList[0].Count;
            var length3 = (length2 == 0) ? 0 : outerList[0][0].Count;
            var array = new TItem[length1, length2, length3];
            for (int i = 0; i < length1; i++)
            {
                var middleList = outerList[i];
                if (middleList.Count != length2)
                {
                    var message = string.Format("Middle list {0} is of length {1} but should be of length {2}.", i, middleList.Count, length2);
                    throw new FileFormatException(message);
                }
                for (int j = 0; j < length2; j++)
                {
                    var innerList = middleList[j];
                    if (innerList.Count != length3)
                    {
                        var message = string.Format("Inner list {0} is of length {1} but should be of length {2}.", j, innerList.Count, length3);
                        throw new FileFormatException(message);
                    }
                    for (int k = 0; k < length3; k++)
                    {
                        array[i, j, k] = innerList[k];
                    }
                }
            }

            return array;
        }

        /// <summary>
        /// Serializes a value.
        /// </summary>
        /// <param name="context">The serialization context.</param>
        /// <param name="value">The object.</param>
        protected override void SerializeValue(BsonSerializationContext context, TItem[,,] value)
        {
            var bsonWriter = context.Writer;

            var length1 = value.GetLength(0);
            var length2 = value.GetLength(1);
            var length3 = value.GetLength(2);

            bsonWriter.WriteStartArray();
            for (int i = 0; i < length1; i++)
            {
                bsonWriter.WriteStartArray();
                for (int j = 0; j < length2; j++)
                {
                    bsonWriter.WriteStartArray();
                    for (int k = 0; k < length3; k++)
                    {
                        context.SerializeWithChildContext(_itemSerializer, value[i, j, k]);
                    }
                    bsonWriter.WriteEndArray();
                }
                bsonWriter.WriteEndArray();
            }
            bsonWriter.WriteEndArray();
        }

        /// <summary>
        /// Returns a serializer that has been reconfigured with the specified item serializer.
        /// </summary>
        /// <param name="itemSerializer">The item serializer.</param>
        /// <returns>The reconfigured serializer.</returns>
        public ThreeDimensionalArraySerializer<TItem> WithItemSerializer(IBsonSerializer<TItem> itemSerializer)
        {
            if (itemSerializer == _itemSerializer)
            {
                return this;
            }
            else
            {
                return new ThreeDimensionalArraySerializer<TItem>(itemSerializer);
            }
        }

        // explicit interface implementations
        IBsonSerializer IChildSerializerConfigurable.ChildSerializer
        {
            get { return _itemSerializer; }
        }

        IBsonSerializer IChildSerializerConfigurable.WithChildSerializer(IBsonSerializer childSerializer)
        {
            return WithItemSerializer((IBsonSerializer<TItem>)childSerializer);
        }
    }
}


text:
package com.yakami.light.bean;

import com.yakami.light.bean.base.Entity;

import java.util.List;

/**
 * Created by Yakami on 2016/6/6, enjoying it!
 */

public class RawTimeRankContainer extends Entity {

    private String name;
    private int id;
    private long time;
    private String title;
    private List<RawDiscRank> discs;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<RawDiscRank> getDiscs() {
        return discs;
    }

    public void setDiscs(List<RawDiscRank> discs) {
        this.discs = discs;
    }
}


text:
Количество изделий на складе: {{ concrete_product.number }}

{{ product.description }}

        Материал

            <select class="form-control"
                    id="material_selector"
                    data-url="{% url 'ajax_update_for_material' product.id %}">
                {% for m in materials %}
                    {% if material == m %}
                        <option selected="selected">{{ m.name }}</option>
                    {% else %}
                        <option>{{ m.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>

        Размер

            <select class="form-control"
                    id="size_selector"
                    data-url="{% url 'ajax_update_for_sizes' product.id %}">
                {% for s in sizes %}
                    {% if s == size %}
                        <option selected="selected">{{ s.width }}x{{ s.height }}x{{ s.length }}</option>
                    {% else %}
                        <option>{{ s.width }}x{{ s.height }}x{{ s.length }}</option>
                    {% endif %}
                {% endfor %}
            </select>

        Покрытие

            <select class="form-control"
                    id="coating_selector"
                    data-url="{% url 'ajax_update_for_coatings' product.id %}">
                {% for c in coatings %}
                    {% if c == coating %}
                        <option selected="selected">{{ c.name }}</option>
                    {% else %}
                        <option>{{ c.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>

Цена: {{ concrete_product.price }}

        {% if not user.is_superuser %}

                <button id="add" class="btn btn-primary"
                        data-id="{{ concrete_product.id }}"
                        data-url="{% url 'ajax_add_to_cart' %}"
                        type="button">
                    Добавить в корзину
                </button>

        {% endif %}


text:
#ifndef __typedefs_hpp__
#define __typedefs_hpp__

namespace typedefs{

struct item_t{};

typedef item_t Item;

}

#endif//__typedefs_hpp__


text:
/*
 This program sends some data to qgroundcontrol using the mavlink protocol.  The sent packets
 cause qgroundcontrol to respond with heartbeats.  Any settings or custom commands sent from
 qgroundcontrol are printed by this program along with the heartbeats.

 I compiled this program sucessfully on Ubuntu 10.04 with the following command

 gcc -I ../../pixhawk/mavlink/include -o udp-server udp.c

 the rt library is needed for the clock_gettime on linux
 */
/* These headers are for QNX, but should all be standard on unix/linux */
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#if (defined __QNX__) | (defined __QNXNTO__)
/* QNX specific headers */
#include <unix.h>
#else
/* Linux / MacOS POSIX timer headers */
#include <sys/time.h>
#include <time.h>
#include <arpa/inet.h>
#endif

/* FIRST: MAVLink setup */
//#define MAVLINK_CONFIGURED
//#define MAVLINK_NO_DATA
//#define MAVLINK_WPM_VERBOSE

/* 0: Include MAVLink types */
#include "mavlink_types.h"

/* 1: Define mavlink system storage */
mavlink_system_t mavlink_system;

/* 2: Include actual protocol, REQUIRES mavlink_system */
#include "mavlink.h"

/* 3: Define waypoint helper functions */
void mavlink_wpm_send_message(mavlink_message_t* msg);
void mavlink_wpm_send_gcs_string(const char* string);
uint64_t mavlink_wpm_get_system_timestamp();
void mavlink_missionlib_send_message(mavlink_message_t* msg);
void mavlink_missionlib_send_gcs_string(const char* string);
uint64_t mavlink_missionlib_get_system_timestamp();

/* 4: Include waypoint protocol */
#include "waypoints.h"
mavlink_wpm_storage wpm;

#include "mavlink_missionlib_data.h"
#include "mavlink_parameters.h"

mavlink_pm_storage pm;

/**
 * @brief reset all parameters to default
 * @warning DO NOT USE THIS IN FLIGHT!
 */
void mavlink_pm_reset_params(mavlink_pm_storage* pm)
{
	pm->size = MAVLINK_PM_MAX_PARAM_COUNT;
	// 1) MAVLINK_PM_PARAM_SYSTEM_ID
	pm->param_values[MAVLINK_PM_PARAM_SYSTEM_ID] = 12;
	strcpy(pm->param_names[MAVLINK_PM_PARAM_SYSTEM_ID], "SYS_ID");
	// 2) MAVLINK_PM_PARAM_ATT_K_D
	pm->param_values[MAVLINK_PM_PARAM_ATT_K_D] = 0.3f;
	strcpy(pm->param_names[MAVLINK_PM_PARAM_ATT_K_D], "ATT_K_D");
}

#define BUFFER_LENGTH 2041 // minimum buffer size that can be used with qnx (I don't know why)

char help[] = "--help";

char target_ip[100];

float position[6] = {};
int sock;
struct sockaddr_in gcAddr;
struct sockaddr_in locAddr;
uint8_t buf[BUFFER_LENGTH];
ssize_t recsize;
socklen_t fromlen;
int bytes_sent;
mavlink_message_t msg;
uint16_t len;
int i = 0;
unsigned int temp = 0;

uint64_t microsSinceEpoch();

/* Provide the interface functions for the waypoint manager */

/*
 *  @brief Sends a MAVLink message over UDP
 */

void mavlink_missionlib_send_message(mavlink_message_t* msg)
{
	uint8_t buf[MAVLINK_MAX_PACKET_LEN];
	uint16_t len = mavlink_msg_to_send_buffer(buf, msg);
	uint16_t bytes_sent = sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof (struct sockaddr_in));

	printf("SENT %d bytes\n", bytes_sent);
}

void mavlink_missionlib_send_gcs_string(const char* string)
{
	const int len = 50;
	mavlink_statustext_t status;
	int i = 0;
	while (i < len - 1)
	{
		status.text[i] = string[i];
		if (string[i] == '\0')
			break;
		i++;
	}
	status.text[i] = '\0'; // Enforce null termination
	mavlink_message_t msg;

	mavlink_msg_statustext_encode(mavlink_system.sysid, mavlink_system.compid, &msg, &status);
	mavlink_missionlib_send_message(&msg);
}

uint64_t mavlink_missionlib_get_system_timestamp()
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return ((uint64_t)tv.tv_sec) * 1000000 + tv.tv_usec;
}

float roll, pitch, yaw;
uint32_t latitude, longitude, altitude;
uint16_t speedx, speedy, speedz;
float rollspeed, pitchspeed, yawspeed;
bool hilEnabled = false;

int main(int argc, char* argv[])
{
	// Initialize MAVLink
	mavlink_wpm_init(&wpm);
	mavlink_system.sysid = 5;
	mavlink_system.compid = 20;
	mavlink_pm_reset_params(&pm);

	int32_t ground_distance;
	uint32_t time_ms;

	// Create socket
	sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

	// Check if --help flag was used
	if ((argc == 2) && (strcmp(argv[1], help) == 0))
    {
		printf("\n");
		printf("\tUsage:\n\n");
		printf("\t");
		printf("%s", argv[0]);
		printf(" <ip address of QGroundControl>\n");
		printf("\tDefault for localhost: udp-server 127.0.0.1\n\n");
		exit(EXIT_FAILURE);
    }

	// Change the target ip if parameter was given
	strcpy(target_ip, "127.0.0.1");
	if (argc == 2)
    {
		strcpy(target_ip, argv[1]);
    }

	memset(&locAddr, 0, sizeof(locAddr));
	locAddr.sin_family = AF_INET;
	locAddr.sin_addr.s_addr = INADDR_ANY;
	locAddr.sin_port = htons(14551);

	/* Bind the socket to port 14551 - necessary to receive packets from qgroundcontrol */
	if (-1 == bind(sock,(struct sockaddr *)&locAddr, sizeof(struct sockaddr)))
    {
		perror("error bind failed");
		close(sock);
		exit(EXIT_FAILURE);
    }

	/* Attempt to make it non blocking */
	if (fcntl(sock, F_SETFL, O_NONBLOCK | FASYNC) < 0)
    {
		fprintf(stderr, "error setting nonblocking: %s\n", strerror(errno));
		close(sock);
		exit(EXIT_FAILURE);
    }

	memset(&gcAddr, 0, sizeof(gcAddr));
	gcAddr.sin_family = AF_INET;
	gcAddr.sin_addr.s_addr = inet_addr(target_ip);
	gcAddr.sin_port = htons(14550);

	printf("MAVLINK MISSION LIBRARY EXAMPLE PROCESS INITIALIZATION DONE, RUNNING..\n");

	for (;;)
    {
		bytes_sent = 0;

		/* Send Heartbeat */
		mavlink_msg_heartbeat_pack(mavlink_system.sysid, 200, &msg, MAV_TYPE_HELICOPTER, MAV_AUTOPILOT_GENERIC, 0, 0, 0);
		len = mavlink_msg_to_send_buffer(buf, &msg);
		bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof(struct sockaddr_in));

		/* Send Status */
		mavlink_msg_sys_status_pack(1, 200, &msg, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE, 500, 7500, 0, 0, 0, 0, 0, 0, 0, 0);
		len = mavlink_msg_to_send_buffer(buf, &msg);
		bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof (struct sockaddr_in));

		/* Send Local Position */
		mavlink_msg_local_position_ned_pack(mavlink_system.sysid, 200, &msg, microsSinceEpoch(),
										position[0], position[1], position[2],
										position[3], position[4], position[5]);
		len = mavlink_msg_to_send_buffer(buf, &msg);
		bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof(struct sockaddr_in));

		/* Send global position */
		if (hilEnabled)
		{
			mavlink_msg_global_position_int_pack(mavlink_system.sysid, 200, &msg, time_ms, latitude, longitude, altitude, ground_distance, speedx, speedy, speedz, (yaw/M_PI)*180*100);
			len = mavlink_msg_to_send_buffer(buf, &msg);
			bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof(struct sockaddr_in));
		}

		/* Send attitude */
		mavlink_msg_attitude_pack(mavlink_system.sysid, 200, &msg, microsSinceEpoch(), roll, pitch, yaw, rollspeed, pitchspeed, yawspeed);
		len = mavlink_msg_to_send_buffer(buf, &msg);
		bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof(struct sockaddr_in));

		/* Send HIL outputs */
		float roll_ailerons = 0;   // -1 .. 1
		float pitch_elevator = 0.2;  // -1 .. 1
		float yaw_rudder = 0.1;      // -1 .. 1
		float throttle = 0.9;      //  0 .. 1
		mavlink_msg_hil_controls_pack_chan(mavlink_system.sysid, mavlink_system.compid, MAVLINK_COMM_0, &msg, microsSinceEpoch(), roll_ailerons, pitch_elevator, yaw_rudder, throttle, mavlink_system.mode, mavlink_system.nav_mode, 0, 0, 0, 0);
		len = mavlink_msg_to_send_buffer(buf, &msg);
		bytes_sent += sendto(sock, buf, len, 0, (struct sockaddr*)&gcAddr, sizeof(struct sockaddr_in));

		memset(buf, 0, BUFFER_LENGTH);
		recsize = recvfrom(sock, (void *)buf, BUFFER_LENGTH, 0, (struct sockaddr *)&gcAddr, &fromlen);
		if (recsize > 0)
      	{
			// Something received - print out all bytes and parse packet
			mavlink_message_t msg;
			mavlink_status_t status;

			printf("Bytes Received: %d\nDatagram: ", (int)recsize);
			for (i = 0; i < recsize; ++i)
			{
				temp = buf[i];
				printf("%02x ", (unsigned char)temp);
				if (mavlink_parse_char(MAVLINK_COMM_0, buf[i], &msg, &status))
				{
					// Packet received
					printf("\nReceived packet: SYS: %d, COMP: %d, LEN: %d, MSG ID: %d\n", msg.sysid, msg.compid, msg.len, msg.msgid);

					// Handle packet with waypoint component
					mavlink_wpm_message_handler(&msg);

					// Handle packet with parameter component
					mavlink_pm_message_handler(MAVLINK_COMM_0, &msg);

					// Print HIL values sent to system
					if (msg.msgid == MAVLINK_MSG_ID_HIL_STATE)
					{
						mavlink_hil_state_t hil;
						mavlink_msg_hil_state_decode(&msg, &hil);
						printf("Received HIL state:\n");
						printf("R: %f P: %f Y: %f\n", hil.roll, hil.pitch, hil.yaw);
						roll = hil.roll;
						pitch = hil.pitch;
						yaw = hil.yaw;
						rollspeed = hil.rollspeed;
						pitchspeed = hil.pitchspeed;
						yawspeed = hil.yawspeed;
						speedx = hil.vx;
						speedy = hil.vy;
						speedz = hil.vz;
						latitude = hil.lat;
						longitude = hil.lon;
						altitude = hil.alt;
						hilEnabled = true;
					}
				}
			}
			printf("\n");
		}
		memset(buf, 0, BUFFER_LENGTH);
		usleep(10000); // Sleep 10 ms

		// Send one parameter
		mavlink_pm_queued_send();
    }
}

/* QNX timer version */
#if (defined __QNX__) | (defined __QNXNTO__)
uint64_t microsSinceEpoch()
{

	struct timespec time;

	uint64_t micros = 0;

	clock_gettime(CLOCK_REALTIME, &time);
	micros = (uint64_t)time.tv_sec * 100000 + time.tv_nsec/1000;

	return micros;
}
#else
uint64_t microsSinceEpoch()
{

	struct timeval tv;

	uint64_t micros = 0;

	gettimeofday(&tv, NULL);
	micros =  ((uint64_t)tv.tv_sec) * 1000000 + tv.tv_usec;

	return micros;
}
#endif


text:
package org.apache.flink.table.plan.schema

import org.apache.flink.table.plan.stats.FlinkStatistic
import org.apache.flink.table.sources.TableSource

/**
  * Abstract class which define the interfaces required to convert a [[TableSource]] to
  * a Calcite Table
  */
abstract class TableSourceTable[T](
    val tableSource: TableSource[T],
    val statistic: FlinkStatistic = FlinkStatistic.UNKNOWN)
  extends FlinkTable {

  /**
    * Returns statistics of current table.
    */
  override def getStatistic: FlinkStatistic = statistic

  /**
    * Replaces table source with the given one, and create a new table source table.
    *
    * @param tableSource tableSource to replace.
    * @return new TableSourceTable
    */
  def replaceTableSource(tableSource: TableSource[T]): TableSourceTable[T]
}


text:
#ifndef TENSORFLOW_CORE_IR_IMPORTEXPORT_CONVERT_TENSOR_H_
#define TENSORFLOW_CORE_IR_IMPORTEXPORT_CONVERT_TENSOR_H_

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/IR/Attributes.h"  // from @llvm-project
#include "mlir/IR/Builders.h"  // from @llvm-project
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/ir/dialect.h"
#include "tensorflow/core/ir/types/dialect.h"
#include "tensorflow/core/platform/statusor.h"

namespace mlir {
namespace tfg {

// Converts an TensorFlow tensor proto into an MLIR elements attribute.
tensorflow::StatusOr<ElementsAttr> ConvertTensorProto(
    const tensorflow::TensorProto& input_tensor, Builder builder);

// Converts an TensorFlow tensor into an MLIR elements attribute.
tensorflow::StatusOr<ElementsAttr> ConvertTensor(
    const tensorflow::Tensor& input_tensor, Builder builder);

// Converts a shape from MLIR to a TensorFlow tensor shape proto.
void ConvertToTensorShapeProto(ArrayRef<int64_t> shape,
                               tensorflow::TensorShapeProto* output_shape);

// Converts an MLIR type to a TensorFlow tensor shape.
tensorflow::PartialTensorShape ConvertTypeToTensorShape(const Type& type);

// Converts a TensorFlow shape attribute to an MLIR shape attribute.
tensorflow::StatusOr<ShapeAttr> ConvertTensorShapeProto(
    const tensorflow::TensorShapeProto& shape, MLIRContext* context);

// Fill in the contents of TensorShapeProto for the given shape.
// ShapeContainerT is any type with the following methods:
//   bool hasRank()
//   ArrayRef<int64_t> getShape()
// This includes TF::ShapeAttr and ShapedType.
template <typename ShapeContainerT>
void SetTensorShapeProto(ShapeContainerT shape,
                         tensorflow::TensorShapeProto* proto) {
  if (shape.hasRank()) {
    for (int64_t dim : shape.getShape()) {
      // TODO(hinsu): Use tensorflow::kTFDynamicSize instead of -1 without
      // depending on tensorflow/compiler
      proto->add_dim()->set_size(mlir::ShapedType::isDynamic(dim) ? -1 : dim);
    }
  } else {
    proto->set_unknown_rank(true);
  }
}

// Converts an MLIR elements attribute to a TensorFlow tensor proto.
tensorflow::Status ConvertToTensorProto(ElementsAttr attr,
                                        tensorflow::TensorProto* output_tensor);

// Converts an MLIR elements attribute to a TensorFlow tensor.
tensorflow::Status ConvertToTensor(ElementsAttr attr,
                                   tensorflow::Tensor* output_tensor);

// Converts a TF shape to MLIR shape, i.e. -1 becomes kDynamicSize.
llvm::SmallVector<int64_t> ConvertTFShapeToMlir(llvm::ArrayRef<int64_t> shape);

// Converts an MLIR shape to TF shape, i.e. kDynamicSize becomes -1.
llvm::SmallVector<int64_t> ConvertMlirShapeToTF(llvm::ArrayRef<int64_t> shape);

// Creates a TF TensorShape using MLIR shape, element type and encoding.
mlir::RankedTensorType GetTypeFromTFTensorShape(llvm::ArrayRef<int64_t> shape,
                                                mlir::Type elementType,
                                                mlir::Attribute encoding = {});

}  // namespace tfg
}  // namespace mlir

#endif  // TENSORFLOW_CORE_IR_IMPORTEXPORT_CONVERT_TENSOR_H_


text:
moveup() {
  local file dest=$1 searchstr=$2 dir=$3
  cd "$dir" || return
  for file in .* *; do
    # skip current/previous dirs and unresolved wildcards
    case "$file" in
    "." | ".." | ".*" | "*" ) continue ;;
    esac

    if [[ "$file" = $searchstr ]]; then
      fcounter=0
      newname="$file"

      #As long as the file exists in the future home it runs through the do loop
      #changing the potential name and incrementing the counter
      while [[ -e "$dest$newname" ]]; do
        newname="$fcounter.$file"
        ((fcounter++))
      done
      mv "$file" "$dest$newname"
    fi
    # recursively traverse/indent directories that are not symlinks
    if [[ -d "$file" && ! -L "$file" ]]; then
      moveup "$dest" "$searchstr" "$file"
    fi
  done
  cd ..
}

#Add a slash to the end of the $1 variable for two reasons:
#   1. many people will not add a / to the end of the folder name and it needs to be there
#   2. if the variable is empty, that can affect tests.
dest="$1/"

#Check and see if we added an extra / at the end of the destination. if we did: remove it.
[[ "$dest" = *// ]] && dest="${dest#?}"

#if the dest = / that indicates that it was not passed to the script
#so we assume that the $PWD is the desired location.
#we also change relative links to absolute links using the readlinks command.
if [[ "$dest" = / ]]; then dest="$PWD/"; else dest="$(readlink -m $dest)/"; fi
if [[ -z "$3" ]]; then startloc=$PWD; else startloc="$(readlink -m $3)"; fi

echo "I intend to move files that match the pattern"
echo "${2:-*.txt}"
echo "recursively from"
echo "$startloc"
echo "into"
echo "$dest"
read -p "do you want to continue?" -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
  then
    moveup "$dest" "${2:-*.txt}" "$startloc"
    # calls the function "moveup" with three paramaters.
    # 1 is set it uses that as the directory to place the files in
    # 2 look for files that match the pattern. if not set look for *.txt files
    # 3 start directory. If not set it will start in the current working directory
fi


text:
package org.apache.sshd.common.session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.sshd.common.Channel;
import org.apache.sshd.common.Cipher;
import org.apache.sshd.common.Compression;
import org.apache.sshd.common.service.ConnectionService;
import org.apache.sshd.common.Digest;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.KeyExchange;
import org.apache.sshd.common.Mac;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.Random;
import org.apache.sshd.common.Session;
import org.apache.sshd.common.SessionListener;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.TcpipForwarder;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.DefaultCloseFuture;
import org.apache.sshd.common.util.Buffer;
import org.apache.sshd.common.util.BufferUtils;
import org.apache.sshd.common.service.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The AbstractSession handles all the basic SSH protocol such as key exchange, authentication,
 * encoding and decoding. Both server side and client side sessions should inherit from this
 * abstract class. Some basic packet processing methods are defined but the actual call to these
 * methods should be done from the {@link #handleMessage(org.apache.sshd.common.util.Buffer)}
 * method, which is dependant on the state and side of this session.
 *
 * TODO: if there is any very big packet, decoderBuffer and uncompressBuffer will get quite big
 *        and they won't be resized down at any time. Though the packet size is really limited
 *        by the channel max packet size
 *
 * @author Apache MINA SSHD Project
 */
public abstract class AbstractSession<S extends Service> implements Session {

    /**
     * Name of the property where this session is stored in the attributes of the
     * underlying MINA session. See {@link #getSession(IoSession, boolean)}
     * and {@link #attachSession(IoSession, AbstractSession)}.
     */
    public static final String SESSION = "org.apache.sshd.session";
    /** Our logger */
    protected final Logger log = LoggerFactory.getLogger(getClass());
    /** The factory manager used to retrieve factories of Ciphers, Macs and other objects */
    protected final FactoryManager factoryManager;
    /** The underlying MINA session */
    protected final IoSession ioSession;
    /** The pseudo random generator */
    protected final Random random;
    /** Lock object for this session state */
    protected final Object lock = new Object();
    /**
     * A future that will be set 'closed' when the connection is closed.
     */
    protected final CloseFuture closeFuture = new DefaultCloseFuture(lock);
    /** The session is being closed */
    protected volatile boolean closing;
    private boolean closingIoSession;
    /** Boolean indicating if this session has been authenticated or not */
    protected boolean authed;

    /** Session listener */
    protected final List<SessionListener> listeners = new ArrayList<SessionListener>();

    /**
     * The service that is currently up-and-running, null until the service is started.
     */
    protected S currentService;

    //
    // Key exchange support
    //
    protected byte[] sessionId;
    protected String serverVersion;
    protected String clientVersion;
    protected String[] serverProposal;
    protected String[] clientProposal;
    protected String[] negociated;
    protected byte[] I_C; // the payload of the client's SSH_MSG_KEXINIT
    protected byte[] I_S; // the payload of the factoryManager's SSH_MSG_KEXINIT
    protected KeyExchange kex;

    //
    // SSH packets encoding / decoding support
    //
    protected Cipher outCipher;
    protected Cipher inCipher;
    protected int outCipherSize = 8;
    protected int inCipherSize = 8;
    protected Mac outMac;
    protected Mac inMac;
    protected byte[] inMacResult;
    protected Compression outCompression;
    protected Compression inCompression;
    protected long seqi;
    protected long seqo;
    protected Buffer decoderBuffer = new Buffer();
    protected Buffer uncompressBuffer;
    protected int decoderState;
    protected int decoderLength;
    protected final Object encodeLock = new Object();
    protected final Object decodeLock = new Object();
    protected final Map<AttributeKey<?>, Object> attributes = new ConcurrentHashMap<AttributeKey<?>, Object>();
    protected String username;

    private State state = State.ReceiveKexInit;

    /**
     * Create a new session.
     *
     * @param factoryManager the factory manager
     * @param ioSession the underlying MINA session
     */
    public AbstractSession(FactoryManager factoryManager, IoSession ioSession) {
        this.factoryManager = factoryManager;
        this.ioSession = ioSession;
        this.random = factoryManager.getRandomFactory().create();
    }

    /**
     * Retrieve the session from the MINA session.
     * If the session has not been attached, an IllegalStateException
     * will be thrown
     *
     * @param ioSession the MINA session
     * @return the session attached to the MINA session
     */
    public static final AbstractSession getSession(IoSession ioSession) {
        return getSession(ioSession, false);
    }

    /**
     * Retrieve the session from the MINA session.
     * If the session has not been attached and allowNull is false,
     * an IllegalStateException will be thrown, else a null will
     * be returned
     *
     * @param ioSession the MINA session
     * @param allowNull if true, a null value may be
     *        returned if no session is attached
     * @return the session attached to the MINA session or null
     */
    public static final AbstractSession getSession(IoSession ioSession, boolean allowNull) {
        AbstractSession session = (AbstractSession) ioSession.getAttribute(SESSION);
        if (!allowNull && session == null) {
            throw new IllegalStateException("No session available");
        }
        return session;
    }

    /**
     * Attach a session to the MINA session
     *
     * @param ioSession the MINA session
     * @param session the session to attach
     */
    public static final void attachSession(IoSession ioSession, AbstractSession session) {
        ioSession.setAttribute(SESSION, session);
    }

    public State getState() {
        return state;
    }

    protected void setState(State state) {
        this.state = state;
        final ArrayList<SessionListener> l = new ArrayList<SessionListener>(listeners);
        for (SessionListener sl : l) {
            sl.sessionChanged(this);
        }
    }

    /**
     * Retrieve the mina session
     *
     * @return the mina session
     */
    public IoSession getIoSession() {
        return ioSession;
    }

    /**
     * Retrieve the factory manager
     *
     * @return the factory manager for this session
     */
    public FactoryManager getFactoryManager() {
        return factoryManager;
    }

    /**
     * Main input point for the MINA framework.
     *
     * This method will be called each time new data is received on
     * the socket and will append it to the input buffer before
     * calling the {@link #decode()} method.
     *
     * @param buffer the new buffer received
     * @throws Exception if an error occurs while decoding or handling the data
     */
    public void messageReceived(IoBuffer buffer) throws Exception {
        synchronized (decodeLock) {
            decoderBuffer.putBuffer(buffer);
            // One of those property will be set by the constructor and the other
            // one should be set by the readIdentification method
            if (clientVersion == null || serverVersion == null) {
                if (readIdentification(decoderBuffer)) {
                    decoderBuffer.compact();
                } else {
                    return;
                }
            }
            decode();
        }
    }

    /**
     * Abstract method for processing incoming decoded packets.
     * The given buffer will hold the decoded packet, starting from
     * the command byte at the read position.
     * Packets must be processed within this call or be copied because
     * the given buffer is meant to be changed and updated when this
     * method returns.
     *
     * @param buffer the buffer containing the packet
     * @throws Exception if an exeption occurs while handling this packet.
     */
    protected abstract void handleMessage(Buffer buffer) throws Exception;

    /**
     * Handle any exceptions that occured on this session.
     * The session will be closed and a disconnect packet will be
     * sent before if the given exception is an
     * {@link org.apache.sshd.common.SshException}.
     *
     * @param t the exception to process
     * @throws IOException
     */
    public void exceptionCaught(Throwable t) {
        log.warn("Exception caught", t);
        try {
            if (t instanceof SshException) {
                int code = ((SshException) t).getDisconnectCode();
                if (code > 0) {
                    disconnect(code, t.getMessage());
                    return;
                }
            }
        } catch (Throwable t2) {
            // Ignore
        }
        close(true);
    }

    /**
     * Shutdown the entire session including anything like channels.
     */
    public CloseFuture close(boolean immediately) {
        synchronized (lock) {
            if (currentService != null) {
                currentService.close(immediately);
                return closeFuture;
            } else {
                return closeIoSession(immediately);
            }
        }
    }

    /**
     * Close this session; its assumed that the caller has already closed any thing
     * like channels.
     */
    public CloseFuture closeIoSession(boolean immediately) {
        class IoSessionCloser implements IoFutureListener {
            public void operationComplete(IoFuture future) {
                synchronized (lock) {
                    log.debug("IoSession closed");
                    closeFuture.setClosed();
                    state = State.Closed;
                    lock.notifyAll();
                }
                log.info("Session {}@{} closed", getUsername(), getIoSession().getRemoteAddress());
                // Fire 'close' event
                final ArrayList<SessionListener> l = new ArrayList<SessionListener>(listeners);
                for (SessionListener sl : l) {
                    sl.sessionClosed(AbstractSession.this);
                }
            }
        }
        synchronized (lock) {
            if (!closingIoSession) {
                closingIoSession = true;
                log.debug("Closing IoSession");
                ioSession.close(immediately).addListener(new IoSessionCloser());
            }
        }
        return closeFuture;
    }

    /**
     * Encode and send the given buffer.
     * The buffer has to have 5 bytes free at the beginning to allow the encoding to take place.
     * Also, the write position of the buffer has to be set to the position of the last byte to write.
     *
     * @param buffer the buffer to encode and send
     * @return a future that can be used to check when the packet has actually been sent
     * @throws java.io.IOException if an error occured when encoding sending the packet
     */
    public WriteFuture writePacket(Buffer buffer) throws IOException {
        // Synchronize all write requests as needed by the encoding algorithm
        // and also queue the write request in this synchronized block to ensure
        // packets are sent in the correct order
        synchronized (encodeLock) {
            encode(buffer);
            IoBuffer bb = IoBuffer.wrap(buffer.array(), buffer.rpos(), buffer.available());
            return ioSession.write(bb);
        }
    }

    /**
     * Create a new buffer for the specified SSH packet and reserve the needed space
     * (5 bytes) for the packet header.
     *
     * @param cmd the SSH command
     * @param len estimated number of bytes the buffer will hold, 0 if unknown.
     * @return a new buffer ready for write
     */
    public Buffer createBuffer(SshConstants.Message cmd, int len) {
        Buffer buffer;
        if (len <= 0) {
            buffer = new Buffer();
        } else {
            // Since the caller claims to know how many bytes they will need
            // increase their request to account for our headers/footers if
            // they actually send exactly this amount.
            //
            int bsize = outCipherSize;
            int oldLen = len;
            len += 5;
            int pad = (-len) & (bsize - 1);
            if (pad < bsize) {
                pad += bsize;
            }
            len = len + pad - 4;
            if (outMac != null) {
                len += outMac.getBlockSize();
            }
            buffer = new Buffer(new byte[Math.max(len, Buffer.DEFAULT_SIZE)], false);
        }
        buffer.rpos(5);
        buffer.wpos(5);
        buffer.putByte(cmd.toByte());
        return buffer;
    }

    /**
     * Encode a buffer into the SSH protocol.
     * This method need to be called into a synchronized block around encodeLock
     *
     * @param buffer the buffer to encode
     * @throws IOException if an exception occurs during the encoding process
     */
    private void encode(Buffer buffer) throws IOException {
        try {
            // Check that the packet has some free space for the header
            if (buffer.rpos() < 5) {
                log.warn("Performance cost: when sending a packet, ensure that "
                           + "5 bytes are available in front of the buffer");
                Buffer nb = new Buffer();
                nb.wpos(5);
                nb.putBuffer(buffer);
                buffer = nb;
            }
            // Grab the length of the packet (excluding the 5 header bytes)
            int len = buffer.available();
            int off = buffer.rpos() - 5;
            // Debug log the packet
            if (log.isTraceEnabled()) {
                log.trace("Sending packet #{}: {}", seqo, buffer.printHex());
            }
            // Compress the packet if needed
            if (outCompression != null && (authed || !outCompression.isDelayed())) {
                log.trace("compress output - delayed {} authed {}", outCompression.isDelayed(), authed);
                outCompression.compress(buffer);
                len = buffer.available();
            }
            // Compute padding length
            int bsize = outCipherSize;
            int oldLen = len;
            len += 5;
            int pad = (-len) & (bsize - 1);
            if (pad < bsize) {
                pad += bsize;
            }
            len = len + pad - 4;
            // Write 5 header bytes
            buffer.wpos(off);
            buffer.putInt(len);
            buffer.putByte((byte) pad);
            // Fill padding
            buffer.wpos(off + oldLen + 5 + pad);
            random.fill(buffer.array(), buffer.wpos() - pad, pad);
            // Compute mac
            if (outMac != null) {
                int macSize = outMac.getBlockSize();
                int l = buffer.wpos();
                buffer.wpos(l + macSize);
                outMac.updateUInt(seqo);
                outMac.update(buffer.array(), off, l);
                outMac.doFinal(buffer.array(), l);
            }
            // Encrypt packet, excluding mac
            if (outCipher != null) {
                outCipher.update(buffer.array(), off, len + 4);
            }
            // Increment packet id
            seqo = (seqo + 1) & 0xffffffffL;
            // Make buffer ready to be read
            buffer.rpos(off);
        } catch (SshException e) {
            throw e;
        } catch (Exception e) {
            throw new SshException(e);
        }
    }

    /**
     * Decode the incoming buffer and handle packets as needed.
     *
     * @throws Exception
     */
    protected void decode() throws Exception {
        // Decoding loop
        for (;;) {
            // Wait for beginning of packet
            if (decoderState == 0) {
                // The read position should always be 0 at this point because we have compacted this buffer
                assert decoderBuffer.rpos() == 0;
                // If we have received enough bytes, start processing those
                if (decoderBuffer.available() > inCipherSize) {
                    // Decrypt the first bytes
                    if (inCipher != null) {
                        inCipher.update(decoderBuffer.array(), 0, inCipherSize);
                    }
                    // Read packet length
                    decoderLength = decoderBuffer.getInt();
                    // Check packet length validity
                    if (decoderLength < 5 || decoderLength > (256 * 1024)) {
                        log.info("Error decoding packet (invalid length) {}", decoderBuffer.printHex());
                        throw new SshException(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
                                               "Invalid packet length: " + decoderLength);
                    }
                    // Ok, that's good, we can go to the next step
                    decoderState = 1;
                } else {
                    // need more data
                    break;
                }
            // We have received the beinning of the packet
            } else if (decoderState == 1) {
                // The read position should always be 4 at this point
                assert decoderBuffer.rpos() == 4;
                int macSize = inMac != null ? inMac.getBlockSize() : 0;
                // Check if the packet has been fully received
                if (decoderBuffer.available() >= decoderLength + macSize) {
                    byte[] data = decoderBuffer.array();
                    // Decrypt the remaining of the packet
                    if (inCipher != null){
                        inCipher.update(data, inCipherSize, decoderLength + 4 - inCipherSize);
                    }
                    // Check the mac of the packet
                    if (inMac != null) {
                        // Update mac with packet id
                        inMac.updateUInt(seqi);
                        // Update mac with packet data
                        inMac.update(data, 0, decoderLength + 4);
                        // Compute mac result
                        inMac.doFinal(inMacResult, 0);
                        // Check the computed result with the received mac (just after the packet data)
                        if (!BufferUtils.equals(inMacResult, 0, data, decoderLength + 4, macSize)) {
                            throw new SshException(SshConstants.SSH2_DISCONNECT_MAC_ERROR,
                                                   "MAC Error");
                        }
                    }
                    // Increment incoming packet sequence number
                    seqi = (seqi + 1) & 0xffffffffL;
                    // Get padding
                    byte pad = decoderBuffer.getByte();
                    Buffer buf;
                    int wpos = decoderBuffer.wpos();
                    // Decompress if needed
                    if (inCompression != null && (authed || !inCompression.isDelayed())) {
                        log.trace("uncompress input - delayed {} authed {}", inCompression.isDelayed(), authed);
                        if (uncompressBuffer == null) {
                            uncompressBuffer = new Buffer();
                        } else {
                            uncompressBuffer.clear();
                        }
                        decoderBuffer.wpos(decoderBuffer.rpos() + decoderLength - 1 - pad);
                        inCompression.uncompress(decoderBuffer, uncompressBuffer);
                        buf = uncompressBuffer;
                    } else {
                        decoderBuffer.wpos(decoderLength + 4 - pad);
                        buf = decoderBuffer;
                    }
                    if (log.isTraceEnabled()) {
                        log.trace("Received packet #{}: {}", seqi, buf.printHex());
                    }
                    // Process decoded packet
                    handleMessage(buf);
                    // Set ready to handle next packet
                    decoderBuffer.rpos(decoderLength + 4 + macSize);
                    decoderBuffer.wpos(wpos);
                    decoderBuffer.compact();
                    decoderState = 0;
                } else {
                    // need more data
                    break;
                }
            }
        }
    }

    /**
     * Send our identification.
     *
     * @param ident our identification to send
     */
    protected void sendIdentification(String ident) {
        IoBuffer buffer = IoBuffer.allocate(32);
        buffer.setAutoExpand(true);
        buffer.put((ident + "\r\n").getBytes());
        buffer.flip();
        ioSession.write(buffer);
    }

    /**
     * Read the other side identification.
     * This method is specific to the client or server side, but both should call
     * {@link #doReadIdentification(org.apache.sshd.common.util.Buffer)} and
     * store the result in the needed property.
     *
     * @param buffer the buffer containing the remote identification
     * @return true if the identification has been fully read or
     *         false if more data is needed
     * @throws IOException if an error occurs such as a bad protocol version
     */
    protected abstract boolean readIdentification(Buffer buffer) throws IOException;

    /**
     * Read the remote identification from this buffer.
     * If more data is needed, the buffer will be reset to its original state
     * and a null value will be returned.  Else the identification
     * string will be returned and the data read will be consumed from the buffer.
     *
     * @param buffer the buffer containing the identification string
     * @return the remote identification or null if more data is needed
     */
    protected String doReadIdentification(Buffer buffer) {
        byte[] data = new byte[256];
        for (;;) {
            int rpos = buffer.rpos();
            int pos = 0;
            boolean needLf = false;
            for (;;) {
                if (buffer.available() == 0) {
                    // Need more data, so undo reading and return null
                    buffer.rpos(rpos);
                    return null;
                }
                byte b = buffer.getByte();
                if (b == '\r') {
                    needLf = true;
                    continue;
                }
                if (b == '\n') {
                    break;
                }
                if (needLf) {
                    throw new IllegalStateException("Incorrect identification: bad line ending");
                }
                if (pos >= data.length) {
                    throw new IllegalStateException("Incorrect identification: line too long");
                }
                data[pos++] = b;
            }
            String str = new String(data, 0, pos);
            if (str.startsWith("SSH-")) {
                return str;
            }
            if (buffer.rpos() > 16 * 1024) {
                throw new IllegalStateException("Incorrect identification: too many header lines");
            }
        }
    }

    /**
     * Create our proposal for SSH negociation
     *
     * @param hostKeyTypes the list of supported host key types
     * @return an array of 10 strings holding this proposal
     */
    protected String[] createProposal(String hostKeyTypes) {
        return new String[] {
                NamedFactory.Utils.getNames(factoryManager.getKeyExchangeFactories()),
                hostKeyTypes,
                NamedFactory.Utils.getNames(factoryManager.getCipherFactories()),
                NamedFactory.Utils.getNames(factoryManager.getCipherFactories()),
                NamedFactory.Utils.getNames(factoryManager.getMacFactories()),
                NamedFactory.Utils.getNames(factoryManager.getMacFactories()),
                NamedFactory.Utils.getNames(factoryManager.getCompressionFactories()),
                NamedFactory.Utils.getNames(factoryManager.getCompressionFactories()),
                "",
                ""
        };
    }

    /**
     * Send the key exchange initialization packet.
     * This packet contains random data along with our proposal.
     *
     * @param proposal our proposal for key exchange negociation
     * @return the sent packet which must be kept for later use
     * @throws IOException if an error occured sending the packet
     */
    protected byte[] sendKexInit(String[] proposal) throws IOException {
        Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_KEXINIT, 0);
        int p = buffer.wpos();
        buffer.wpos(p + 16);
        random.fill(buffer.array(), p, 16);
        for (String s : proposal) {
            buffer.putString(s);
        }
        buffer.putByte((byte) 0);
        buffer.putInt(0);
        byte[] data = buffer.getCompactData();
        writePacket(buffer);
        return data;
    }

    /**
     * Receive the remote key exchange init message.
     * The packet data is returned for later use.
     *
     * @param buffer the buffer containing the key exchange init packet
     * @param proposal the remote proposal to fill
     * @return the packet data
     */
    protected byte[] receiveKexInit(Buffer buffer, String[] proposal) {
        // Recreate the packet payload which will be needed at a later time
        int size = 22;
        byte[] d = buffer.array();
        byte[] data = new byte[buffer.available() + 1];
        data[0] = SshConstants.Message.SSH_MSG_KEXINIT.toByte();
        System.arraycopy(d, buffer.rpos(), data, 1, data.length - 1);
        // Skip 16 bytes of random data
        buffer.rpos(buffer.rpos() + 16);
        // Read proposal
        for (int i = 0; i < proposal.length; i++) {
            size += 4;
            proposal[i] = buffer.getString();
            size += proposal[i].length();
        }
        // Skip 5 bytes
        buffer.getByte();
        buffer.getInt();
        // Return data
        byte[] dataShrinked = new byte[size];
        System.arraycopy(data, 0, dataShrinked, 0, size);
        return dataShrinked;
    }

    /**
     * Send a message to put new keys into use.
     *
     * @throws IOException if an error occurs sending the message
     */
    protected void sendNewKeys() throws IOException {
        log.debug("Send SSH_MSG_NEWKEYS");
        Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_NEWKEYS, 0);
        writePacket(buffer);
    }

    /**
     * Put new keys into use.
     * This method will intialize the ciphers, digests, macs and compression
     * according to the negociated server and client proposals.
     *
     * @param isServer boolean indicating if this session is on the server or the client side
     * @throws Exception if an error occurs
     */
    protected void receiveNewKeys(boolean isServer) throws Exception {
        byte[] IVc2s;
        byte[] IVs2c;
        byte[] Ec2s;
        byte[] Es2c;
        byte[] MACc2s;
        byte[] MACs2c;
        byte[] K = kex.getK();
        byte[] H = kex.getH();
        Digest hash = kex.getHash();
        Cipher s2ccipher;
        Cipher c2scipher;
        Mac s2cmac;
        Mac c2smac;
        Compression s2ccomp;
        Compression c2scomp;

        if (sessionId == null) {
            sessionId = new byte[H.length];
            System.arraycopy(H, 0, sessionId, 0, H.length);
        }

        Buffer buffer = new Buffer();
        buffer.putMPInt(K);
        buffer.putRawBytes(H);
        buffer.putByte((byte) 0x41);
        buffer.putRawBytes(sessionId);
        int pos = buffer.available();
        byte[] buf = buffer.array();
        hash.update(buf, 0, pos);
        IVc2s = hash.digest();

        int j = pos - sessionId.length - 1;

        buf[j]++;
        hash.update(buf, 0, pos);
        IVs2c = hash.digest();

        buf[j]++;
        hash.update(buf, 0, pos);
        Ec2s = hash.digest();

        buf[j]++;
        hash.update(buf, 0, pos);
        Es2c = hash.digest();

        buf[j]++;
        hash.update(buf, 0, pos);
        MACc2s = hash.digest();

        buf[j]++;
        hash.update(buf, 0, pos);
        MACs2c = hash.digest();

        s2ccipher = NamedFactory.Utils.create(factoryManager.getCipherFactories(), negociated[SshConstants.PROPOSAL_ENC_ALGS_STOC]);
        Es2c = resizeKey(Es2c, s2ccipher.getBlockSize(), hash, K, H);
        s2ccipher.init(isServer ? Cipher.Mode.Encrypt : Cipher.Mode.Decrypt, Es2c, IVs2c);

        s2cmac = NamedFactory.Utils.create(factoryManager.getMacFactories(), negociated[SshConstants.PROPOSAL_MAC_ALGS_STOC]);
        s2cmac.init(MACs2c);

        c2scipher = NamedFactory.Utils.create(factoryManager.getCipherFactories(), negociated[SshConstants.PROPOSAL_ENC_ALGS_CTOS]);
        Ec2s = resizeKey(Ec2s, c2scipher.getBlockSize(), hash, K, H);
        c2scipher.init(isServer ? Cipher.Mode.Decrypt : Cipher.Mode.Encrypt, Ec2s, IVc2s);

        c2smac = NamedFactory.Utils.create(factoryManager.getMacFactories(), negociated[SshConstants.PROPOSAL_MAC_ALGS_CTOS]);
        c2smac.init(MACc2s);

        s2ccomp = NamedFactory.Utils.create(factoryManager.getCompressionFactories(), negociated[SshConstants.PROPOSAL_COMP_ALGS_STOC]);
        c2scomp = NamedFactory.Utils.create(factoryManager.getCompressionFactories(), negociated[SshConstants.PROPOSAL_COMP_ALGS_CTOS]);

        if (isServer) {
            outCipher = s2ccipher;
            outMac = s2cmac;
            outCompression = s2ccomp;
            inCipher = c2scipher;
            inMac = c2smac;
            inCompression = c2scomp;
        } else {
            outCipher = c2scipher;
            outMac = c2smac;
            outCompression = c2scomp;
            inCipher = s2ccipher;
            inMac = s2cmac;
            inCompression = s2ccomp;
        }
        outCipherSize = outCipher.getIVSize();
        if (outCompression != null) {
            outCompression.init(Compression.Type.Deflater, -1);
        }
        inCipherSize = inCipher.getIVSize();
        inMacResult = new byte[inMac.getBlockSize()];
        if (inCompression != null) {
            inCompression.init(Compression.Type.Inflater, -1);
        }
    }

    /**
     * Private method used while putting new keys into use that will resize the key used to
     * initialize the cipher to the needed length.
     *
     * @param E the key to resize
     * @param blockSize the cipher block size
     * @param hash the hash algorithm
     * @param K the key exchange K parameter
     * @param H the key exchange H parameter
     * @return the resize key
     * @throws Exception if a problem occur while resizing the key
     */
    private byte[] resizeKey(byte[] E, int blockSize, Digest hash, byte[] K, byte[] H) throws Exception {
        while (blockSize > E.length) {
            Buffer buffer = new Buffer();
            buffer.putMPInt(K);
            buffer.putRawBytes(H);
            buffer.putRawBytes(E);
            hash.update(buffer.array(), 0, buffer.available());
            byte[] foo = hash.digest();
            byte[] bar = new byte[E.length + foo.length];
            System.arraycopy(E, 0, bar, 0, E.length);
            System.arraycopy(foo, 0, bar, E.length, foo.length);
            E = bar;
        }
        return E;
    }

    /**
     * Send a disconnect packet with the given reason and message.
     * Once the packet has been sent, the session will be closed
     * asynchronously.
     *
     * @param reason the reason code for this disconnect
     * @param msg the text message
     * @throws IOException if an error occured sending the packet
     */
    public void disconnect(int reason, String msg) throws IOException {
        Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT, 0);
        buffer.putInt(reason);
        buffer.putString(msg);
        buffer.putString("");
        WriteFuture f = writePacket(buffer);
        f.addListener(new IoFutureListener() {
            public void operationComplete(IoFuture future) {
                close(false);
            }
        });
    }

    /**
     * Send an unimplemented packet.  This packet should contain the
     * sequence id of the usupported packet: this number is assumed to
     * be the last packet received.
     *
     * @throws IOException if an error occured sending the packet
     */
    protected void notImplemented() throws IOException {
        Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_UNIMPLEMENTED, 0);
        buffer.putInt(seqi - 1);
        writePacket(buffer);
    }

    /**
     * Compute the negociated proposals by merging the client and
     * server proposal.  The negocatiated proposal will be stored in
     * the {@link #negociated} property.
     */
    protected void negociate() {
        String[] guess = new String[SshConstants.PROPOSAL_MAX];
        for (int i = 0; i < SshConstants.PROPOSAL_MAX; i++) {
            String[] c = clientProposal[i].split(",");
            String[] s = serverProposal[i].split(",");
            for (String ci : c) {
                for (String si : s) {
                    if (ci.equals(si)) {
                        guess[i] = ci;
                        break;
                    }
                }
                if (guess[i] != null) {
                    break;
                }
            }
            if (guess[i] == null && i != SshConstants.PROPOSAL_LANG_CTOS && i != SshConstants.PROPOSAL_LANG_STOC) {
                throw new IllegalStateException("Unable to negociate key exchange for item " + i);
            }
        }
        negociated = guess;
    }

    /**
     * Retrieve a configuration property as an integer
     *
     * @param name the name of the property
     * @param defaultValue the default value
     * @return the value of the configuration property or the default value if not found
     */
    public int getIntProperty(String name, int defaultValue) {
        try {
            String v = factoryManager.getProperties().get(name);
            if (v != null) {
                return Integer.parseInt(v);
            }
        } catch (Exception e) {
            // Ignore
        }
        return defaultValue;
    }

    /**
     * Returns the value of the user-defined attribute of this session.
     *
     * @param key the key of the attribute; must not be null.
     * @return <tt>null</tt> if there is no attribute with the specified key
     */
    @SuppressWarnings("unchecked")
    public <T> T getAttribute(AttributeKey<T> key) {
        return (T)attributes.get(key);
    }

    /**
     * Sets a user-defined attribute.
     *
     * @param key   the key of the attribute; must not be null.
     * @param value the value of the attribute; must not be null.
     * @return The old value of the attribute.  <tt>null</tt> if it is new.
     */
    @SuppressWarnings("unchecked")
    public <T, E extends T> T setAttribute(AttributeKey<T> key, E value) {
        return (T)attributes.put(key, value);
    }

    public String getUsername() {
        return username;
    }

    /**
     * {@inheritDoc}
     */
    public void addListener(SessionListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException();
        }

        synchronized (this.listeners) {
            this.listeners.add(listener);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void removeListener(SessionListener listener) {
        synchronized (this.listeners) {
            this.listeners.remove(listener);
        }
    }

    /**
     * {@inheritDoc}
     */
    public CloseFuture getCloseFuture() {
        return this.closeFuture;
    }
}


text:
package org.pointstone.cugappplat.base.cusotomview.swipeview.touch;

import org.pointstone.cugappplat.base.cusotomview.swipeview.CompatItemTouchHelper;

/**
 * Created by Yolanda on 2016/4/19.
 */
public class DefaultItemTouchHelper extends CompatItemTouchHelper {

    private DefaultItemTouchHelperCallback mDefaultItemTouchHelperCallback;

    /**
     * Create default item touch helper.
     */
    public DefaultItemTouchHelper() {
        this(new DefaultItemTouchHelperCallback());
    }

    /**
     * @param callback the behavior of ItemTouchHelper.
     */
    private DefaultItemTouchHelper(DefaultItemTouchHelperCallback callback) {
        super(callback);
        mDefaultItemTouchHelperCallback = (DefaultItemTouchHelperCallback) getCallback();
    }

    /**
     * Set OnItemMoveListener.
     *
     * @param onItemMoveListener {@link OnItemMoveListener}.
     */
    public void setOnItemMoveListener(OnItemMoveListener onItemMoveListener) {
        mDefaultItemTouchHelperCallback.setOnItemMoveListener(onItemMoveListener);
    }

    /**
     * Get OnItemMoveListener.
     *
     * @return {@link OnItemMoveListener}.
     */
    public OnItemMoveListener getOnItemMoveListener() {
        return mDefaultItemTouchHelperCallback.getOnItemMoveListener();
    }

    /**
     * Set OnItemMovementListener.
     *
     * @param onItemMovementListener {@link OnItemMovementListener}.
     */
    public void setOnItemMovementListener(OnItemMovementListener onItemMovementListener) {
        mDefaultItemTouchHelperCallback.setOnItemMovementListener(onItemMovementListener);
    }

    /**
     * Get OnItemMovementListener.
     *
     * @return {@link OnItemMovementListener}.
     */
    public OnItemMovementListener getOnItemMovementListener() {
        return mDefaultItemTouchHelperCallback.getOnItemMovementListener();
    }

    /**
     * Set can long press drag.
     *
     * @param canDrag drag true, otherwise is can't.
     */
    public void setLongPressDragEnabled(boolean canDrag) {
        mDefaultItemTouchHelperCallback.setLongPressDragEnabled(canDrag);
    }

    /**
     * Get can long press drag.
     *
     * @return drag true, otherwise is can't.
     */
    public boolean isLongPressDragEnabled() {
        return mDefaultItemTouchHelperCallback.isLongPressDragEnabled();
    }

    /**
     * Set can long press swipe.
     *
     * @param canSwipe swipe true, otherwise is can't.
     */
    public void setItemViewSwipeEnabled(boolean canSwipe) {
        mDefaultItemTouchHelperCallback.setItemViewSwipeEnabled(canSwipe);
    }

    /**
     * Get can long press swipe.
     *
     * @return swipe true, otherwise is can't.
     */
    public boolean isItemViewSwipeEnabled() {
        return this.mDefaultItemTouchHelperCallback.isItemViewSwipeEnabled();
    }

    /**
     * Set OnItemStateChangedListener.
     *
     * @param onItemStateChangedListener {@link OnItemStateChangedListener}.
     */
    public void setOnItemStateChangedListener(OnItemStateChangedListener onItemStateChangedListener) {
        this.mDefaultItemTouchHelperCallback.setOnItemStateChangedListener(onItemStateChangedListener);
    }

    /**
     * Get OnItemStateChangedListener.
     *
     * @return {@link OnItemStateChangedListener}.
     */
    public OnItemStateChangedListener getOnItemStateChangedListener() {
        return this.mDefaultItemTouchHelperCallback.getOnItemStateChangedListener();
    }

}


text:
"""This module contains implementations of some specific objects for use in
simulations."""

from __future__ import division

__docformat__ = 'restructuredtext'
__author__ = 'Tiago Baptista'

from pyafai import Object
import math

DEG2RAD = math.pi / 180

class SimplePhysicsObject(Object):
    """A simple physics object that can move in 2D space."""

    def __init__(self, x=0, y=0, angle=0):
        super(SimplePhysicsObject, self).__init__(x, y, angle)

        self._vel = 0.0
        self._velx = 0.0
        self._vely = 0.0
        self._ang_vel = 0.0

    @property
    def velocity(self):
        return self._vel

    @velocity.setter
    def velocity(self, v):
        self._velx = v * math.cos(self.angle*DEG2RAD)
        self._vely = v * math.sin(self.angle*DEG2RAD)
        self._vel = v

    @property
    def ang_velocity(self):
        return self._ang_vel

    @ang_velocity.setter
    def ang_velocity(self, v):
        self._ang_vel = v

    def update(self, delta):
        if self._ang_vel != 0:
            self.angle = self._angle + self._ang_vel * delta
        self.x += self._velx * delta
        self.y += self._vely * delta

    @Object.angle.setter
    def angle(self, value):
        #normalize
        while value > 360:
            value -= 360
        while value < 0:
            value += 360

        self._angle = value
        self.velocity = self._vel


text:
package io.seldon.api.caching;

import io.seldon.api.APIException;
import io.seldon.general.Action;
import io.seldon.memcache.ExceptionSwallowingMemcachedClient;
import io.seldon.memcache.MemCacheKeys;

import java.util.ArrayList;
import java.util.List;

import net.spy.memcached.CASMutation;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MemcacheActionHistory implements ActionHistory {

	private static Logger logger = Logger.getLogger(MemcacheActionHistory.class.getName());
	public static int CACHE_TIME = 1800;

	@Autowired
	ExceptionSwallowingMemcachedClient cacheClient;

	@Override
	public List<Long> getRecentActions(String clientName,long userId,int numActions)
	{
		String mkey = MemCacheKeys.getActionHistory(clientName, userId);
		List<Long> res = (List<Long>) cacheClient.get(mkey);
		if (res == null)
		{
			if (logger.isDebugEnabled())
				logger.debug("creating empty action history for user "+userId+" for client "+clientName);
			res = new ArrayList<>();
		}
		else
		{
			if (res.size() > numActions)
				res = res.subList(0, numActions);
			if (logger.isDebugEnabled())
				logger.debug("Got action history for user "+userId+" from memcache");
		}
		return res;
	}

	@Override
	public List<Action> getRecentFullActions(String clientName,long userId,int numActions)
	{
		String mkey = MemCacheKeys.getActionFullHistory(clientName, userId);
		List<Action> res = (List<Action>) cacheClient.get(mkey);
		if (res == null)
		{
			if (logger.isDebugEnabled())
				logger.debug("creating empty action full history for user "+userId+" for client "+clientName);
			res = new ArrayList<Action>();
		}
		else
		{
			if (logger.isDebugEnabled())
				logger.debug("Got action full history for user "+userId+" from memcache of size " + res.size());
			if (res.size() > numActions)
				res = res.subList(0, numActions);

		}
		return res;
	}

	@Override
	public void addFullAction(String clientName,final Action a)
	{
		if (logger.isDebugEnabled())
			logger.debug("Adding full action to cache for "+a.getUserId()+" item "+a.getItemId());
        CASMutation<List<Action>> mutation = new CASMutation<List<Action>>() {

            // This is only invoked when a value actually exists.
            public List<Action> getNewValue(List<Action> current) {
	                current.add(0, a);
	            return current;
            }
        };
        List<Action> actions = new ArrayList<Action>();
        actions.add(a);
		String mkey = MemCacheKeys.getActionFullHistory(clientName, a.getUserId());
        cacheClient.cas(mkey, mutation, actions,CACHE_TIME);

	}

	@Override
	public void addAction(String clientName,long userId,final long itemId) throws APIException
    {
		if (logger.isDebugEnabled())
			logger.debug("Adding action to cache for "+userId+" item "+itemId);
        CASMutation<List<Long>> mutation = new CASMutation<List<Long>>() {

            // This is only invoked when a value actually exists.
            public List<Long> getNewValue(List<Long> current) {
            	if(!current.contains(itemId)) {
	                current.add(0, itemId);
            	}
	            return current;
            }
        };
        List<Long> actions = new ArrayList<>();
        actions.add(itemId);
        String mkey = MemCacheKeys.getActionHistory(clientName, userId);
        cacheClient.cas(mkey, mutation, actions,CACHE_TIME);
    }

}


text:
USE_APACHE=true

# PHP stuff
USE_PHP=true
USE_COMPOSER=true
COMPOSER_AUTO=false
USE_PHPUNIT=true

# Database stuff
USE_MYSQL=true
USE_PHPMYADMIN=true
DB_HOST=localhost
DB_NAME=projectdb
DB_USER=root
DB_PASSWD=root
MYSQL_IMPORT=true

#Git stuff
USE_GIT=true
GIT_USER="Git User"
GIT_EMAIL=user.email@domain.com

# Node stuff
 USE_NODE=false
 USE_GULP=false
 USE_BOWER=false
 USE_GRUNT=false

 USE_MAILCATCHER=false

###
# end configuration
###

echo "Creating swap file"
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024 > /dev/null 2>&1
/sbin/mkswap /var/swap.1 > /dev/null 2>&1
/sbin/swapon /var/swap.1 > /dev/null 2>&1
echo '/var/swap.1 none swap sw 0 0' >> /etc/fstab

echo "Updating ..."
apt-get -qq update > /dev/null 2>&1

sed -i 's|\\u@\\h:\\w\\$ |\\n\\u@\\h:\\w\\n\\$ |g' /home/ubuntu/.bashrc

if $USE_APACHE; then
    echo "Installing Apache"
    apt-get -qq -y install apache2 > /dev/null 2>&1
    cp -f /vagrant/provision/000-default.conf /etc/apache2/sites-available/000-default.conf
    a2enmod rewrite > /dev/null 2>&1
    cp -f /vagrant/provision/servername.conf /etc/apache2/conf-available/servername.conf
    a2enconf servername > /dev/null 2>&1
    service apache2 restart > /dev/null 2>&1
fi

if $USE_PHP; then
    echo "Installing PHP"
    apt-get -qq -y install php libapache2-mod-php > /dev/null 2>&1
    apt-get -qq -y install php-curl > /dev/null 2>&1
    apt-get -qq -y install php-gd > /dev/null 2>&1
    apt-get -qq -y install php-sqlite3 > /dev/null 2>&1
    apt-get -qq -y install php-mcrypt > /dev/null 2>&1
    phpenmod mcrypt
    cp -f /vagrant/provision/php.ini /etc/php/7.0/apache2/php.ini
fi

if $USE_MYSQL; then
    echo "Installing MySQL"
    debconf-set-selections <<< "mysql-server mysql-server/root_password password $DB_PASSWD"
    debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $DB_PASSWD"
    apt-get -qq -y install mysql-server > /dev/null 2>&1
    apt-get -qq -y install mysql-client php-mysql > /dev/null  2>&1

    echo "Creating Database"
    mysql -uroot -p$DB_PASSWD -e "CREATE DATABASE $DB_NAME" >> /dev/null 2>&1
    mysql -uroot -p$DB_PASSWD -e "grant all privileges on $DB_NAME.* to '$DB_USER'@'localhost' identified by '$DB_PASSWD'" > /dev/null 2>&1

    if $MYSQL_IMPORT && [ -f /vagrant/provision/sql ]; then
        echo "SQL file found. Importing Database"
        mysql -u $DB_USER -p$DB_PASSWD $DB_NAME < /vagrant/provision/sql
    fi
fi

if $USE_PHPMYADMIN && $USE_APACHE; then
    echo "Installing phpMyAdmin"
    debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true"
    debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $DB_PASSWD"
    debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $DB_PASSWD"
    debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $DB_PASSWD"
    debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2"
    apt-get -qq -y install phpmyadmin > /dev/null 2>&1
fi

if $USE_COMPOSER; then
    echo "Installing Composer"
    curl -sS https://getcomposer.org/installer | php > /dev/null 2>&1
    mv composer.phar /usr/local/bin/composer
fi

if $COMPOSER_AUTO && [ -f /vagrant/composer.json ]; then
    echo "composer.json found, let's setup your project"
    composer --working-dir=/vagrant/ install
fi

if $USE_GIT; then
    echo "Installing Git"
    apt-get install -y git > /dev/null 2>&1

    echo "[user]" >> /home/ubuntu/.gitconfig
    echo "    name = $GIT_USER" >> /home/ubuntu/.gitconfig
    echo "    email = $GIT_EMAIL" >> /home/ubuntu/.gitconfig

    git clone https://github.com/magicmonty/bash-git-prompt.git /home/ubuntu/.bash-git-prompt --depth=1 > /dev/null 2>&1
    echo "GIT_PROMPT_ONLY_IN_REPO=1" >> /home/ubuntu/.bashrc
    echo "source ~/.bash-git-prompt/gitprompt.sh" >> /home/ubuntu/.bashrc

    apt-get install -y git-ftp > /dev/null 2>&1
fi

if $USE_PHPUNIT; then
    echo "Installing PHPUnit"
    wget -q https://phar.phpunit.de/phpunit.phar
    chmod +x phpunit.phar
    mv phpunit.phar /usr/local/bin/phpunit
fi

if $USE_NODE; then
    echo "Installing Node.js and npm"
    apt-get install -y nodejs > /dev/null 2>&1
    ln -s /usr/bin/nodejs /usr/bin/node
    apt-get install -y npm > /dev/null 2>&1
fi

if $USE_GULP && $USE_NODE; then
    echo "Installing Gulp"
    npm install --global gulp-cli --silent > /dev/null 2>&1
    apt-get install -y libnotify-bin > /dev/null 2>&1
fi

if $USE_BOWER && $USE_NODE; then
    echo "Installing Bower"
    npm install -g bower --silent > /dev/null 2>&1
fi

if $USE_GRUNT && $USE_NODE; then
    echo "Installing Grunt"
    npm install -g grunt-cli --silent > /dev/null 2>&1
fi

if $USE_MAILCATCHER; then
    apt-get -qq -y install build-essential libsqlite3-dev ruby2.3-dev > /dev/null 2>&1
    gem install mailcatcher --no-ri --no-rdoc > /dev/null 2>&1
    echo 'description "Mailcatcher"' > /etc/init/mailcatcher.conf
    echo '' >> /etc/init/mailcatcher.conf
    echo 'start on runlevel [2345]' >> /etc/init/mailcatcher.conf
    echo 'stop on runlevel [2345]' >> /etc/init/mailcatcher.conf
    echo '' >> /etc/init/mailcatcher.conf
    echo 'respawn' >> /etc/init/mailcatcher.conf
    echo 'exec /usr/bin/env $(which mailcatcher) --foreground --http-ip=0.0.0.0' >> /etc/init/mailcatcher.conf
    if $USE_PHP; then
        sed -i 's|^;sendmail_path =|sendmail_path = /usr/bin/env /usr/local/bin/catchmail|g' /etc/php/7.0/apache2/php.ini
    fi
    /usr/bin/env $(which mailcatcher) --ip=0.0.0.0 > /dev/null 2>&1
fi

if $USE_APACHE; then
    service apache2 restart > /dev/null 2>&1
fi

echo "Done Installing stuff. Have a nice day!"


text:
package net.anotheria.moskito.core.command;

import java.util.Map;
/**
 * This interface defines a processor for a single command (word) which can be used with the command controller.
 * @author lrosenberg
 */
public interface CommandProcessor {
	/**
	 * Starts the command.
	 * @param command name of the command
	 * @param parameters parameter map
	 */
	 void startCommand(String command, Map<String,String[]> parameters);

	/**
	 * Stops the command.
	 *
	 */
	 void stopCommand(String command, Map<String,String[]> parameters);
}