text:
""" This file makes open() and friends RPython. Note that RFile should not
be used directly and instead it's magically appearing each time you call
python builtin open()
"""

import os, stat, errno, sys
from rpython.rlib import rposix, rgc
from rpython.rlib.objectmodel import enforceargs
from rpython.rlib.rarithmetic import intmask
from rpython.rlib.rstring import StringBuilder
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rtyper.tool import rffi_platform as platform
from rpython.translator.tool.cbuild import ExternalCompilationInfo

includes = ['stdio.h', 'sys/types.h']
if os.name == "posix":
    includes += ['unistd.h']
    ftruncate = 'ftruncate'
    fileno = 'fileno'
else:
    ftruncate = '_chsize'
    fileno = '_fileno'
eci = ExternalCompilationInfo(includes=includes)

class CConfig(object):
    _compilation_info_ = eci

    off_t = platform.SimpleType('off_t')

    _IONBF = platform.DefinedConstantInteger('_IONBF')
    _IOLBF = platform.DefinedConstantInteger('_IOLBF')
    _IOFBF = platform.DefinedConstantInteger('_IOFBF')
    BUFSIZ = platform.DefinedConstantInteger('BUFSIZ')
    EOF = platform.DefinedConstantInteger('EOF')

config = platform.configure(CConfig)

FILEP = rffi.COpaquePtr("FILE")
OFF_T = config['off_t']

_IONBF = config['_IONBF']
_IOLBF = config['_IOLBF']
_IOFBF = config['_IOFBF']
BUFSIZ = config['BUFSIZ']
EOF = config['EOF']

BASE_BUF_SIZE = 4096
BASE_LINE_SIZE = 100

NEWLINE_UNKNOWN = 0
NEWLINE_CR = 1
NEWLINE_LF = 2
NEWLINE_CRLF = 4

def llexternal(*args, **kwargs):
    return rffi.llexternal(*args, compilation_info=eci, **kwargs)

c_fopen = llexternal('fopen', [rffi.CCHARP, rffi.CCHARP], FILEP,
                     save_err=rffi.RFFI_SAVE_ERRNO)
c_popen = llexternal('popen', [rffi.CCHARP, rffi.CCHARP], FILEP,
                     save_err=rffi.RFFI_SAVE_ERRNO)
c_fdopen = llexternal(('_' if os.name == 'nt' else '') + 'fdopen',
                      [rffi.INT, rffi.CCHARP], FILEP,
                      save_err=rffi.RFFI_SAVE_ERRNO)
c_tmpfile = llexternal('tmpfile', [], FILEP,
                       save_err=rffi.RFFI_SAVE_ERRNO)

c_setvbuf = llexternal('setvbuf', [FILEP, rffi.CCHARP, rffi.INT, rffi.SIZE_T],
                       rffi.INT)

c_fclose = llexternal('fclose', [FILEP], rffi.INT,
                      save_err=rffi.RFFI_SAVE_ERRNO)
c_pclose = llexternal('pclose', [FILEP], rffi.INT,
                      save_err=rffi.RFFI_SAVE_ERRNO)

# Note: the following two functions are called from __del__ methods,
# so must be 'releasegil=False'.  Otherwise, a program using both
# threads and the RFile class cannot translate.  See c684bf704d1f
c_fclose_in_del = llexternal('fclose', [FILEP], rffi.INT, releasegil=False)
c_pclose_in_del = llexternal('pclose', [FILEP], rffi.INT, releasegil=False)
_fclose2 = (c_fclose, c_fclose_in_del)
_pclose2 = (c_pclose, c_pclose_in_del)

c_getc = llexternal('getc', [FILEP], rffi.INT, macro=True)
c_ungetc = llexternal('ungetc', [rffi.INT, FILEP], rffi.INT)
c_fgets = llexternal('fgets', [rffi.CCHARP, rffi.INT, FILEP], rffi.CCHARP)
c_fread = llexternal('fread', [rffi.CCHARP, rffi.SIZE_T, rffi.SIZE_T, FILEP],
                     rffi.SIZE_T)

c_fwrite = llexternal('fwrite', [rffi.CCHARP, rffi.SIZE_T, rffi.SIZE_T, FILEP],
                      rffi.SIZE_T, save_err=rffi.RFFI_SAVE_ERRNO)
c_fflush = llexternal('fflush', [FILEP], rffi.INT,
                      save_err=rffi.RFFI_SAVE_ERRNO)
c_ftruncate = llexternal(ftruncate, [rffi.INT, OFF_T], rffi.INT, macro=True,
                         save_err=rffi.RFFI_SAVE_ERRNO)

c_fseek = llexternal('fseek', [FILEP, rffi.LONG, rffi.INT], rffi.INT,
                     save_err=rffi.RFFI_SAVE_ERRNO)
c_ftell = llexternal('ftell', [FILEP], rffi.LONG,
                     save_err=rffi.RFFI_SAVE_ERRNO)
c_fileno = llexternal(fileno, [FILEP], rffi.INT)

c_feof = llexternal('feof', [FILEP], rffi.INT)
c_ferror = llexternal('ferror', [FILEP], rffi.INT)
c_clearerr = llexternal('clearerr', [FILEP], lltype.Void)

c_stdin = rffi.CExternVariable(FILEP, 'stdin', eci, c_type='FILE*',
                               getter_only=True)
c_stdout = rffi.CExternVariable(FILEP, 'stdout', eci, c_type='FILE*',
                                getter_only=True)
c_stderr = rffi.CExternVariable(FILEP, 'stderr', eci, c_type='FILE*',
                                getter_only=True)

def _error(ll_file):
    err = c_ferror(ll_file)
    c_clearerr(ll_file)
    raise IOError(err, os.strerror(err))

def _dircheck(ll_file):
    try:
        st = os.fstat(c_fileno(ll_file))
    except OSError:
        pass
    else:
        if stat.S_ISDIR(st[0]):
            err = errno.EISDIR
            raise IOError(err, os.strerror(err))

def _sanitize_mode(mode):
    if len(mode) == 0:
        raise ValueError("empty mode string")
    upos = mode.find('U')
    if upos >= 0:
        mode = mode[:upos] + mode[upos+1:]
        first = mode[0:1]
        if first == 'w' or first == 'a':
            raise ValueError("universal newline mode can only be used with "
                             "modes starting with 'r'")
        if first != 'r':
            mode = 'r' + mode
        if 'b' not in mode:
            mode = mode[0] + 'b' + mode[1:]
    elif mode[0] != 'r' and mode[0] != 'w' and mode[0] != 'a':
        raise ValueError("mode string must begin with one of 'r', 'w', 'a' "
                         "or 'U', not '%s'" % mode)
    return mode

def create_file(filename, mode="r", buffering=-1):
    newmode = _sanitize_mode(mode)
    ll_name = rffi.str2charp(filename)
    try:
        ll_mode = rffi.str2charp(newmode)
        try:
            ll_file = c_fopen(ll_name, ll_mode)
            if not ll_file:
                errno = rposix.get_saved_errno()
                raise IOError(errno, os.strerror(errno))
        finally:
            lltype.free(ll_mode, flavor='raw')
    finally:
        lltype.free(ll_name, flavor='raw')
    _dircheck(ll_file)
    f = RFile(ll_file, mode)
    f._setbufsize(buffering)
    return f

def create_fdopen_rfile(fd, mode="r", buffering=-1):
    newmode = _sanitize_mode(mode)
    rposix.validate_fd(fd)
    ll_mode = rffi.str2charp(newmode)
    try:
        ll_file = c_fdopen(fd, ll_mode)
        if not ll_file:
            errno = rposix.get_saved_errno()
            raise OSError(errno, os.strerror(errno))
    finally:
        lltype.free(ll_mode, flavor='raw')
    _dircheck(ll_file)
    f = RFile(ll_file, mode)
    f._setbufsize(buffering)
    return f

def create_temp_rfile():
    res = c_tmpfile()
    if not res:
        errno = rposix.get_saved_errno()
        raise OSError(errno, os.strerror(errno))
    return RFile(res)

def create_popen_file(command, type):
    ll_command = rffi.str2charp(command)
    try:
        ll_type = rffi.str2charp(type)
        try:
            ll_file = c_popen(ll_command, ll_type)
            if not ll_file:
                errno = rposix.get_saved_errno()
                raise OSError(errno, os.strerror(errno))
        finally:
            lltype.free(ll_type, flavor='raw')
    finally:
        lltype.free(ll_command, flavor='raw')
    return RFile(ll_file, close2=_pclose2)

def create_stdio():
    close2 = (None, None)
    stdin = RFile(c_stdin(), close2=close2)
    stdout = RFile(c_stdout(), close2=close2)
    stderr = RFile(c_stderr(), close2=close2)
    return stdin, stdout, stderr

def write_int(f, l):
    if sys.maxint == 2147483647:
        f.write(chr(l & 0xff) +
                chr((l >> 8) & 0xff) +
                chr((l >> 16) & 0xff) +
                chr((l >> 24) & 0xff))
    else:
        f.write(chr(l & 0xff) +
                chr((l >> 8) & 0xff) +
                chr((l >> 16) & 0xff) +
                chr((l >> 24) & 0xff) +
                chr((l >> 32) & 0xff) +
                chr((l >> 40) & 0xff) +
                chr((l >> 48) & 0xff) +
                chr((l >> 56) & 0xff))

class RFile(object):
    _setbuf = lltype.nullptr(rffi.CCHARP.TO)
    _univ_newline = False
    _newlinetypes = NEWLINE_UNKNOWN
    _skipnextlf = False

    def __init__(self, ll_file, mode=None, close2=_fclose2):
        self._ll_file = ll_file
        if mode is not None:
            self._univ_newline = 'U' in mode
        self._close2 = close2

    def _setbufsize(self, bufsize):
        if bufsize >= 0:
            if bufsize == 0:
                mode = _IONBF
            elif bufsize == 1:
                mode = _IOLBF
                bufsize = BUFSIZ
            else:
                mode = _IOFBF
            if self._setbuf:
                lltype.free(self._setbuf, flavor='raw')
            if mode == _IONBF:
                self._setbuf = lltype.nullptr(rffi.CCHARP.TO)
            else:
                self._setbuf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
            c_setvbuf(self._ll_file, self._setbuf, mode, bufsize)

    def __del__(self):
        """Closes the described file when the object's last reference
        goes away.  Unlike an explicit call to close(), this is meant
        as a last-resort solution and cannot release the GIL or return
        an error code."""
        ll_file = self._ll_file
        if ll_file:
            do_close = self._close2[1]
            if do_close:
                do_close(ll_file)       # return value ignored
            if self._setbuf:
                lltype.free(self._setbuf, flavor='raw')

    def _cleanup_(self):
        self._ll_file = lltype.nullptr(FILEP.TO)

    def close(self):
        """Closes the described file.

        Attention! Unlike Python semantics, `close' does not return `None' upon
        success but `0', to be able to return an exit code for popen'ed files.

        The actual return value may be determined with os.WEXITSTATUS.
        """
        res = 0
        ll_file = self._ll_file
        if ll_file:
            # double close is allowed
            self._ll_file = lltype.nullptr(FILEP.TO)
            rgc.may_ignore_finalizer(self)
            do_close = self._close2[0]
            try:
                if do_close:
                    res = do_close(ll_file)
                    if res == -1:
                        errno = rposix.get_saved_errno()
                        raise IOError(errno, os.strerror(errno))
            finally:
                if self._setbuf:
                    lltype.free(self._setbuf, flavor='raw')
                    self._setbuf = lltype.nullptr(rffi.CCHARP.TO)
        return res

    def _check_closed(self):
        if not self._ll_file:
            raise ValueError("I/O operation on closed file")

    def _fread(self, buf, n, stream):
        if not self._univ_newline:
            return c_fread(buf, 1, n, stream)

        i = 0
        dst = buf
        newlinetypes = self._newlinetypes
        skipnextlf = self._skipnextlf
        while n:
            nread = c_fread(dst, 1, n, stream)
            if nread == 0:
                break

            src = dst
            n -= nread
            shortread = n != 0
            while nread:
                nread -= 1
                c = src[0]
                src = rffi.ptradd(src, 1)
                if c == '\r':
                    dst[0] = '\n'
                    dst = rffi.ptradd(dst, 1)
                    i += 1
                    skipnextlf = True
                elif skipnextlf and c == '\n':
                    skipnextlf = False
                    newlinetypes |= NEWLINE_CRLF
                    n += 1
                else:
                    if c == '\n':
                        newlinetypes |= NEWLINE_LF
                    elif skipnextlf:
                        newlinetypes |= NEWLINE_CR
                    dst[0] = c
                    dst = rffi.ptradd(dst, 1)
                    i += 1
                    skipnextlf = False
            if shortread:
                if skipnextlf and c_feof(stream):
                    newlinetypes |= NEWLINE_CR
                break
        self._newlinetypes = newlinetypes
        self._skipnextlf = skipnextlf
        return i

    def read(self, size=-1):
        # XXX CPython uses a more delicate logic here
        self._check_closed()
        ll_file = self._ll_file
        if size == 0:
            return ""
        elif size < 0:
            # read the entire contents
            buf = lltype.malloc(rffi.CCHARP.TO, BASE_BUF_SIZE, flavor='raw')
            try:
                s = StringBuilder()
                while True:
                    returned_size = self._fread(buf, BASE_BUF_SIZE, ll_file)
                    returned_size = intmask(returned_size)  # is between 0 and BASE_BUF_SIZE
                    if returned_size == 0:
                        if c_feof(ll_file):
                            # ok, finished
                            return s.build()
                        raise _error(ll_file)
                    s.append_charpsize(buf, returned_size)
            finally:
                lltype.free(buf, flavor='raw')
        else:  # size > 0
            with rffi.scoped_alloc_buffer(size) as buf:
                returned_size = self._fread(buf.raw, size, ll_file)
                returned_size = intmask(returned_size)  # is between 0 and size
                if returned_size == 0:
                    if not c_feof(ll_file):
                        raise _error(ll_file)
                s = buf.str(returned_size)
                assert s is not None
            return s

    def _readline1(self, raw_buf):
        ll_file = self._ll_file
        for i in range(BASE_LINE_SIZE):
            raw_buf[i] = '\n'

        result = c_fgets(raw_buf, BASE_LINE_SIZE, ll_file)
        if not result:
            if c_feof(ll_file):   # ok
                return 0
            raise _error(ll_file)

        # Assume that fgets() works as documented, and additionally
        # never writes beyond the final \0, which the CPython
        # fileobject.c says appears to be the case everywhere.
        # The only case where the buffer was not big enough is the
        # case where the buffer is full, ends with \0, and doesn't
        # end with \n\0.

        p = 0
        while raw_buf[p] != '\n':
            p += 1
            if p == BASE_LINE_SIZE:
                # fgets read whole buffer without finding newline
                return -1
        # p points to first \n

        if p + 1 < BASE_LINE_SIZE and raw_buf[p + 1] == '\0':
            # \n followed by \0, fgets read and found newline
            return p + 1
        else:
            # \n not followed by \0, fgets read but didnt find newline
            assert p > 0 and raw_buf[p - 1] == '\0'
            return p - 1

    def readline(self, size=-1):
        self._check_closed()
        if size == 0:
            return ""
        elif size < 0 and not self._univ_newline:
            with rffi.scoped_alloc_buffer(BASE_LINE_SIZE) as buf:
                c = self._readline1(buf.raw)
                if c >= 0:
                    return buf.str(c)

                # this is the rare case: the line is longer than BASE_LINE_SIZE
                s = StringBuilder()
                while True:
                    s.append_charpsize(buf.raw, BASE_LINE_SIZE - 1)
                    c = self._readline1(buf.raw)
                    if c >= 0:
                        break
                s.append_charpsize(buf.raw, c)
            return s.build()
        else:  # size > 0 or self._univ_newline
            ll_file = self._ll_file
            c = 0
            s = StringBuilder()
            if self._univ_newline:
                newlinetypes = self._newlinetypes
                skipnextlf = self._skipnextlf
                while size < 0 or s.getlength() < size:
                    c = c_getc(ll_file)
                    if c == EOF:
                        break
                    if skipnextlf:
                        skipnextlf = False
                        if c == ord('\n'):
                            newlinetypes |= NEWLINE_CRLF
                            c = c_getc(ll_file)
                            if c == EOF:
                                break
                        else:
                            newlinetypes |= NEWLINE_CR
                    if c == ord('\r'):
                        skipnextlf = True
                        c = ord('\n')
                    elif c == ord('\n'):
                        newlinetypes |= NEWLINE_LF
                    s.append(chr(c))
                    if c == ord('\n'):
                        break
                if c == EOF:
                    if skipnextlf:
                        newlinetypes |= NEWLINE_CR
                self._newlinetypes = newlinetypes
                self._skipnextlf = skipnextlf
            else:
                while s.getlength() < size:
                    c = c_getc(ll_file)
                    if c == EOF:
                        break
                    s.append(chr(c))
                    if c == ord('\n'):
                        break
            if c == EOF:
                if c_ferror(ll_file):
                    raise _error(ll_file)
            return s.build()

    @enforceargs(None, str)
    def write(self, value):
        self._check_closed()
        with rffi.scoped_nonmovingbuffer(value) as ll_value:
            # note that since we got a nonmoving buffer, it is either raw
            # or already cannot move, so the arithmetics below are fine
            length = len(value)
            bytes = c_fwrite(ll_value, 1, length, self._ll_file)
            if bytes != length:
                errno = rposix.get_saved_errno()
                c_clearerr(self._ll_file)
                raise IOError(errno, os.strerror(errno))

    def flush(self):
        self._check_closed()
        res = c_fflush(self._ll_file)
        if res != 0:
            errno = rposix.get_saved_errno()
            raise IOError(errno, os.strerror(errno))

    def truncate(self, arg=-1):
        self._check_closed()
        if arg == -1:
            arg = self.tell()
        self.flush()
        res = c_ftruncate(self.fileno(), arg)
        if res == -1:
            errno = rposix.get_saved_errno()
            raise IOError(errno, os.strerror(errno))

    def seek(self, pos, whence=0):
        self._check_closed()
        res = c_fseek(self._ll_file, pos, whence)
        if res == -1:
            errno = rposix.get_saved_errno()
            raise IOError(errno, os.strerror(errno))
        self._skipnextlf = False

    def tell(self):
        self._check_closed()
        res = intmask(c_ftell(self._ll_file))
        if res == -1:
            errno = rposix.get_saved_errno()
            raise IOError(errno, os.strerror(errno))
        if self._skipnextlf:
            c = c_getc(self._ll_file)
            if c == ord('\n'):
                self._newlinetypes |= NEWLINE_CRLF
                res += 1
                self._skipnextlf = False
            elif c != EOF:
                c_ungetc(c, self._ll_file)
        return res

    def fileno(self):
        self._check_closed()
        return intmask(c_fileno(self._ll_file))

    def isatty(self):
        self._check_closed()
        return os.isatty(c_fileno(self._ll_file))

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()


text:
<?php

namespace Webgraphe\Phlip\Operation\LanguageConstruct;

use Webgraphe\Phlip\Contracts\ScopeContract;
use Webgraphe\Phlip\Contracts\FormContract;
use Webgraphe\Phlip\Exception\AssertionException;
use Webgraphe\Phlip\FormCollection\DottedPair;
use Webgraphe\Phlip\FormCollection\FormList;
use Webgraphe\Phlip\Operation\ManualOperation;

class CarOperation extends ManualOperation
{
    const IDENTIFIER = 'car';
    const IDENTIFIER_ALTERNATIVE = 'head';

    /**
     * @return string[]
     */
    public function getIdentifiers(): array
    {
        return [self::IDENTIFIER, self::IDENTIFIER_ALTERNATIVE];
    }

    /**
     * @param ScopeContract $scope
     * @param FormList $forms
     * @return FormContract|null
     * @throws AssertionException
     */
    protected function invoke(ScopeContract $scope, FormList $forms): ?FormContract
    {
        $consCell = $scope->execute($forms->assertHead());
        if ($consCell instanceof DottedPair) {
            return $consCell->getFirst();
        }

        return FormList::assertStaticType($consCell)->getHead();
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace mko.Newton
{
    public class TimeInHours : Time
    {
        protected override void InitValue()
        {
            Value = 0.0;
        }

        public override MeasuredValue Create(double Value)
        {
            return new TimeInHours(Value);
        }

        public override MeasuredValue Create(MeasuredValue Value)
        {
            return new TimeInHours((Time)Value);
        }

        public TimeInHours () { }
        public TimeInHours(double Value) : base(Value) { }
        public TimeInHours(Time Value) : base(Value) { }

        public override double ToBaseUnitConversionFactor
        {
            get { return 3600.0; }
        }

        public override string UnitSymbol
        {
            get { return "h"; }
        }

        // Operatoren

        public static bool operator ==(TimeInHours a, TimeInHours b)
        {
            return EQUAL(a, b);
        }

        public static bool operator !=(TimeInHours a, TimeInHours b)
        {
            return !EQUAL(a, b);
        }

        public static TimeInHours operator *(TimeInHours a, double factor)
        {
            return SCALE(factor, a);
        }

        public static TimeInHours operator *(double factor, TimeInHours a)
        {
            return SCALE(factor, a);

        }

        public static TimeInHours operator /(TimeInHours a, double factor)
        {
            return SCALE(1 / factor, a);
        }

        public static TimeInHours operator +(TimeInHours a, TimeInHours b)
        {
            return ADD(a, b);
        }

        public static TimeInHours operator -(TimeInHours a, TimeInHours b)
        {
            return SUB(a, b);
        }

    }
}


text:
define(['exports', './prompt', '../dialog-service'], function (exports, _prompt, _dialogService) {
  'use strict';

  exports.__esModule = true;

  var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  var CommonDialogs = (function () {
    function CommonDialogs(dialogService) {
      _classCallCheck(this, CommonDialogs);

      this.dialogService = dialogService;
    }

    CommonDialogs.prototype.prompt = function prompt(question) {
      return this.dialogService.open({ viewModel: _prompt.Prompt, model: question });
    };

    _createClass(CommonDialogs, null, [{
      key: 'inject',
      value: [_dialogService.DialogService],
      enumerable: true
    }]);

    return CommonDialogs;
  })();

  exports.CommonDialogs = CommonDialogs;
});


text:
'''
Author: Sai Uday Shankar, Korlimarla
Create pom.xml from list of maven artifacts with python
'''

##### Pass the following values into this function
## Project Group ID - As String
## Project Artifact ID  - As String
## Project Version - As string
## These values will serve purpose in creating project values in pom.xml
## Same values will serve in creating jar file after sucessful build with pom.xml
## g is maven group ID as a list even if passing a single item
## a is maven artifact ID as a list even if passing a single item
## v is maven group ID as a list even if passing a single item
#####

from xml.dom import minidom
import itertools

def create_pom_xml(project_groupID, project_artifactID, project_version, g,a,v):
    doc = minidom.Document()
    root = doc.createElement('project')
    doc.appendChild(root)

    modelVersion = doc.createElement('modelVersion')
    text = doc.createTextNode('4.0.0')
    modelVersion.appendChild(text)
    root.appendChild(modelVersion)

    groupId = doc.createElement('groupId')
    text = doc.createTextNode(project_groupID)
    groupId.appendChild(text)
    root.appendChild(groupId)

    artifactId = doc.createElement('artifactId')
    text = doc.createTextNode(project_artifactID)
    artifactId.appendChild(text)
    root.appendChild(artifactId)

    version = doc.createElement('version')
    text = doc.createTextNode(project_version)
    version.appendChild(text)
    root.appendChild(version)

    dependencies = doc.createElement('dependencies')
    root.appendChild(dependencies)

    for g_val, a_val, v_val in itertools.izip(g, a, v):

        dependency = doc.createElement('dependency')
        dependencies.appendChild(dependency)

        dep_group = doc.createElement('groupId')
        text = doc.createTextNode(g_val)
        dep_group.appendChild(text)
        dependency.appendChild(dep_group)
        dependencies.appendChild(dependency)
        root.appendChild(dependencies)

        dep_artifact = doc.createElement('artifactId')
        text = doc.createTextNode(a_val)
        dep_artifact.appendChild(text)
        dependency.appendChild(dep_artifact)
        dependencies.appendChild(dependency)
        root.appendChild(dependencies)

        dep_version = doc.createElement('version')
        text = doc.createTextNode(v_val)
        dep_version.appendChild(text)
        dependency.appendChild(dep_version)
        dependencies.appendChild(dependency)
        root.appendChild(dependencies)

    xml_str = doc.toprettyxml(indent="  ")
    with open("pom.xml", "w") as f:
        f.write(xml_str)


text:
class Variable
  attr_accessor :json, :id, :name, :display_name, :description, :variable_type, :units,
                :prepend, :append, :field_note, :time_duration_format, :time_of_day_format,
                :show_current_button, :date_format, :domain_options, :show_seconds

  def initialize(json: {})
    load_from_json(json) if json.present?
    @domain_options ||= []
  end

  def load_from_json(json)
    return unless json
    @json = json
    root_attributes.each do |attribute|
      send("#{attribute}=", json[attribute.to_s])
    end
  end

  def root_attributes
    [
      :id, :name, :display_name, :description, :variable_type, :units, :prepend,
      :append, :field_note, :time_duration_format, :time_of_day_format,
      :show_current_button, :date_format, :show_seconds
    ]
  end
end


text:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

	<class name="org.mifos.accounts.loan.business.LoanScheduleEntity" table="loan_schedule">
		<id name="actionDateId" column="id" type="integer" unsaved-value="-1" access="field">
			<generator class="native" />
		</id>
		<version name="versionNo" column="version_no" type="integer" unsaved-value="null" />

		<property name="installmentId" column="installment_id" access="field" />
		<property name="actionDate" column="action_date" />
		<property name="paymentStatus" column="payment_status" />
		<property name="paymentDate" column="payment_date" lazy="true" />

		<property name="principal" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="principal_currency_id" />
			<column name="principal" />
		</property>
		<property name="interest" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="interest_currency_id" />
			<column name="interest" />
		</property>
		<property name="penalty" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="penalty_currency_id" />
			<column name="penalty" />
		</property>
		<property name="miscFee" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="misc_fees_currency_id" />
			<column name="misc_fees" />
		</property>
		<property name="miscFeePaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="misc_fees_paid_currency_id" />
			<column name="misc_fees_paid" />
		</property>
		<property name="miscPenalty" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="misc_penalty_currency_id" />
			<column name="misc_penalty" />
		</property>
		<property name="miscPenaltyPaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="misc_penalty_paid_currency_id" />
			<column name="misc_penalty_paid" />
		</property>
		<property name="principalPaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="principal_paid_currency_id" />
			<column name="principal_paid" />
		</property>
		<property name="interestPaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="interest_paid_currency_id" />
			<column name="interest_paid" />
		</property>
		<property name="penaltyPaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="penalty_paid_currency_id" />
			<column name="penalty_paid" />
		</property>
        <property name="extraInterest" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="extra_interest_currency_id" />
			<column name="extra_interest" />
		</property>
        <property name="extraInterestPaid" type="org.mifos.framework.util.helpers.MoneyCompositeUserType">
			<column name="extra_interest_paid_currency_id" />
			<column name="extra_interest_paid" />
		</property>

		<many-to-one name="account" column="account_id" class="org.mifos.accounts.business.AccountBO" unique="true" cascade="none" insert="true" update="true" access="field"/>
		<many-to-one name="customer" column="customer_id" class="org.mifos.customers.business.CustomerBO" access="field"/>
		<set name="accountFeesActionDetails" cascade="all,delete-orphan" lazy="true" inverse="true" access="field">
			<key column="id" update="false" />
			<one-to-many class="org.mifos.accounts.loan.business.LoanFeeScheduleEntity" />
		</set>

	</class>

	<query name="loanScheduleEntity.getScheduleForIds">
		<![CDATA[ from org.mifos.accounts.loan.business.LoanScheduleEntity loanSchedule
				 where loanSchedule.id in (:ids)
		]]>
	</query>

</hibernate-mapping>


text:
package com.cloud.api;

import com.cloud.legacymodel.exceptions.CSExceptionErrorCode;
import com.cloud.legacymodel.exceptions.CloudException;
import com.cloud.legacymodel.exceptions.CloudRuntimeException;
import com.cloud.legacymodel.exceptions.ExceptionProxyObject;

import java.util.ArrayList;

public class ServerApiException extends CloudRuntimeException {
    private ApiErrorCode _errorCode;
    private String _description;

    public ServerApiException() {
        _errorCode = ApiErrorCode.INTERNAL_ERROR;
        _description = null;
        setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ServerApiException.class.getName()));
    }

    public ServerApiException(final ApiErrorCode errorCode, final String description) {
        _errorCode = errorCode;
        _description = description;
        setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ServerApiException.class.getName()));
    }

    // wrap a specific CloudRuntimeException to a ServerApiException
    public ServerApiException(final ApiErrorCode errorCode, final String description, final Throwable cause) {
        super(description, cause);
        _errorCode = errorCode;
        _description = description;
        if (cause instanceof CloudRuntimeException) {
            final CloudRuntimeException rt = (CloudRuntimeException) cause;
            final ArrayList<ExceptionProxyObject> idList = rt.getIdProxyList();
            if (idList != null) {
                for (int i = 0; i < idList.size(); i++) {
                    addProxyObject(idList.get(i));
                }
            }
            setCSErrorCode(rt.getCSErrorCode());
        } else if (cause instanceof CloudException) {
            final CloudException rt = (CloudException) cause;
            final ArrayList<String> idList = rt.getIdProxyList();
            if (idList != null) {
                for (int i = 0; i < idList.size(); i++) {
                    addProxyObject(idList.get(i));
                }
            }
            setCSErrorCode(rt.getCSErrorCode());
        }
    }

    public ApiErrorCode getErrorCode() {
        return _errorCode;
    }

    public void setErrorCode(final ApiErrorCode errorCode) {
        _errorCode = errorCode;
    }

    public String getDescription() {
        return _description;
    }

    public void setDescription(final String description) {
        _description = description;
    }

    @Override
    public String getMessage() {
        return _description;
    }
}


text:
namespace DotVVM.Framework.Testing.SeleniumHelpers.Proxies
{
    public class ListBoxProxy : SelectBaseProxy
    {
        public ListBoxProxy(SeleniumHelperBase helper, PathSelector selector) : base(helper, selector)
        {
        }
    }
}


text:
@interface SRGTableViewCell()

@property(nonatomic)SRGCellViewModel *viewModel;
@property (strong, nonatomic) UILabel *usernameLabel;
@property (strong, nonatomic) UIImageView *userpicImageView;

@end

@implementation SRGTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
  if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    self.viewModel = [SRGCellViewModel new];
    [self initView];

    RAC(self,userpicImageView.image) = RACObserve(self, viewModel.image);
    RAC(self, usernameLabel.text) = RACObserve(self, viewModel.username);
  }
  return self;
}

-(void)initView
{
  self.userpicImageView = [[UIImageView alloc]init];
  self.usernameLabel = [[UILabel alloc]init];

  [self addSubview:self.usernameLabel];
  [self addSubview:self.userpicImageView];

  UIView *superview = self;

  [self.userpicImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(superview.mas_top).with.offset(5);
    make.left.equalTo(superview.mas_left).with.offset(5);
    make.bottom.equalTo(superview.mas_bottom).with.offset(5);
    make.height.equalTo(self.contentView.mas_height).offset(-10);
    make.width.equalTo(self.contentView.mas_height).offset(-10);
  }];

  [self.usernameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.userpicImageView.mas_right).with.offset(10);
    make.top.equalTo(superview.mas_top).with.offset(5);
    make.top.equalTo(superview.mas_right).with.offset(10);
    make.height.equalTo(@40);
  }];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
require "spec_helper"

describe ProcessOut do
  it "has a version number" do
    expect(ProcessOut::VERSION).not_to be nil
  end

  it "creates and fetches an invoice" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    invoice = client.invoice.new(
      name: "Test invoice",
      amount: "9.99",
      currency: "USD"
    ).create
    expect(invoice.id).not_to be_empty

    invoice2 = client.invoice.find(invoice.id)
    expect(invoice2.id).to eq(invoice.id)
  end

  it "captures an invoice and expands the gateway configuration" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    invoice = client.invoice.new(
      name: "Test invoice",
      amount: "9.99",
      currency: "USD"
    ).create

    gr = ProcessOut::GatewayRequest.new("gway_conf_44ae90db0a62f819a404ef6a8ff994ca", {
      method: "POST", url: "https://processout.com?token=test-valid", body: "",
        headers: {
          "Content-Type" => "application/json"
        }
      })
    transaction = invoice.capture(gr)
    expect(transaction.status).to eq("completed")

    transaction = transaction.find(transaction.id, {
      expand: ["gateway_configuration"]
    })
    expect(transaction.gateway_configuration.id).not_to be_empty
  end

  it "creates and deletes a customer" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    customer = client.customer.create
    expect(customer.id).not_to be_empty

    customer.delete
  end

  it "fetches the customers" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    client.customer.all
  end

  it "creates a subscription for a customer and updates its metadata" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    customer = client.customer.create
    expect(customer.id).not_to be_empty

    sub = client.subscription.new(
      customer_id: customer.id,
      amount: "9.99",
      currency: "USD",
      interval: "1d",
      name: "great subscription"
    ).create()
    expect(sub.id).not_to be_empty

    sub.save(
      metadata: {test: "yeah"}
    )
  end

  it "expands a customer project" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    customer = client.customer.create({expand: ["project"]})
    expect(customer.project).not_to eq(nil)
  end

  it "errors when a customer is not found" do
    client = ProcessOut::Client.new("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
      "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")

    begin
      client.customer.find("bad")
      expect(true).to eq(false) # Shouldn't be called
    rescue ProcessOut::NotFoundError => e
      expect(e.code).to eq("resource.customer.not-found")
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>mobile devices on My blog</title>
    <link>http://dangkhoasdc.github.io/tags/mobile-devices/</link>
    <description>Recent content in mobile devices on My blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>vi</language>
    <lastBuildDate>Tue, 28 May 2019 00:00:00 +0000</lastBuildDate>

	<atom:link href="http://dangkhoasdc.github.io/tags/mobile-devices/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Image detections on mobile devices</title>
      <link>http://dangkhoasdc.github.io/post/2019/05/28/image-detections-on-mobile-devices/</link>
      <pubDate>Tue, 28 May 2019 00:00:00 +0000</pubDate>

      <guid>http://dangkhoasdc.github.io/post/2019/05/28/image-detections-on-mobile-devices/</guid>
      <description>I have been working on image detection on mobile devices for the last 6 weeks, which is not long enough to delve into some research paper on model compression or pruning techniques but adequate to get into and conduct some experiments on some detection models.
Firstly, let look at the detection model and make some terms. A detection usually (and from some of the state-of-the-art model: RetinaNet) is composed of 3 components, from bottom to top:</description>
    </item>

  </channel>
</rss>


text:
<!DOCTYPE html>

                <button ng-click="edit(article.id)"  class="btn btn-small btn-danger">edit</button>

{{article.title}}

<button back class="btn btn-default">Retour page précédente</button>


text:
package com.dgrlucky.extend.network.interceptor;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author Vensir
 * @date 16/8/22 下午6:35
 * @company dgrlucky
 * @desc 异常处理拦截器
 */
public class ErrorInterctpor implements Interceptor {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody body = response.body();
        long contentLength = body.contentLength();
        if (!HttpHeaders.hasBody(response)) {//end http

        } else if (bodyEncoded(response.headers())) {//http omit

        } else {//http
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = body.contentType();
            if (contentType != null) {
                try {
                    contentType.charset(charset);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                    return response;
                }
            }
            if (!isPlaintext(buffer)) {
                return response;
            }
            if (contentLength != 0) {
                String result = buffer.clone().readString(charset);
                //parse http
                return response;
            }
        }
        return null;
    }

    //是否为纯文本
    static boolean isPlaintext(Buffer buffer) throws EOFException {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && Character.isWhitespace(codePoint)) {
                    return false;
                }
                return true;
            }
        } catch (EOFException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    //是否加密请求体
    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}


text:
import VirtualDeviceStat from "../../models/VirtualDeviceStat";
import * as Express from "express";
import * as Returns from "./Returns";

export function postVirtualDeviceStats(): (request: Express.Request, response: Express.Response) => Promise<Express.Response> {
    return function (req: Express.Request, res: Express.Response) {
        const virtualDeviceStats: any[] = getValidStats(req);

        function onInsert(err: any) {
            if (err) {
                console.error({info: "Error during virtualDeviceStat entry create", error: err});
            }
            else {
                console.log(JSON.stringify({info: virtualDeviceStats.length + " virtualDeviceStats inserted"}));
            }
        }

        return VirtualDeviceStat.insertMany(virtualDeviceStats, onInsert)
            .then(function() {
                Returns.Okay(res).send({ virtualDeviceStats: virtualDeviceStats.length });
                return res;
            }).catch(function(err: Error) {
                console.error(err);
                Returns.NotOkay(res, 403, err).send();
                return res;
            });
    }
}

function getValidStats(req: Express.Request): any[] {
    const batch = req.body;
    return batch.virtualDeviceStats.filter((virtualDeviceStat: any) =>
        virtualDeviceStat.call && virtualDeviceStat.platform && virtualDeviceStat.messages && virtualDeviceStat.token
        && virtualDeviceStat.env);
}

export default postVirtualDeviceStats;


text:
package com.atexpose.api;

import com.atexpose.api.data_types.DataTypeEnum;
import com.google.common.collect.ImmutableList;
import io.schinzel.basicutils.state.State;
import org.junit.Test;

import java.util.Collections;

import static org.assertj.core.api.Assertions.assertThat;

public class MethodArgumentsTest {

    private MethodArguments getThreeArguments() {
        Argument argument1 = Argument.builder()
                .name("arg1")
                .dataType(DataTypeEnum.STRING.getDataType())
                .defaultValue("my_default_value")
                .build();
        Argument argument2 = Argument.builder()
                .name("arg2")
                .dataType(DataTypeEnum.INT.getDataType())
                .defaultValue("1234")
                .build();
        Argument argument3 = Argument.builder()
                .name("arg3")
                .dataType(DataTypeEnum.BOOLEAN.getDataType())
                .defaultValue("true")
                .build();
        ImmutableList<Argument> arguments = new ImmutableList.Builder<Argument>()
                .add(argument1)
                .add(argument2)
                .add(argument3)
                .build();
        return MethodArguments.create(arguments);
    }

    @Test
    public void size_NullArgumentList_0() {
        int size = MethodArguments.create(null).size();
        assertThat(size).isZero();
    }

    @Test
    public void size_EmptyArgumentList_0() {
        int size = MethodArguments.create(Collections.emptyList()).size();
        assertThat(size).isZero();
    }

    @Test
    public void size_3ArgumentList_3() {
        int size = this.getThreeArguments().size();
        assertThat(size).isEqualTo(3);
    }

    @Test
    public void getCopyOfArgumentDefaultValues_3Arguments_DefaultValuesInCorrectDataTypes() {
        Object[] copyOfArgumentDefaultValues = this.getThreeArguments().getCopyOfArgumentDefaultValues();
        assertThat(copyOfArgumentDefaultValues)
                .containsExactly("my_default_value", 1234, true);
    }

    @Test
    public void getState_3Arguments_Arguments() {
        State state = this.getThreeArguments().getState();
        assertThat(state.getString()).contains("Arguments");
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}

module Matterhorn.Draw.PostListWindow where

import           Prelude ()
import           Matterhorn.Prelude

import           Brick
import           Brick.Widgets.Border
import           Brick.Widgets.Center
import           Control.Monad.Trans.Reader ( withReaderT )
import qualified Data.Text as T
import           Lens.Micro.Platform ( (%~), to )

import           Network.Mattermost.Lenses
import           Network.Mattermost.Types

import           Matterhorn.Draw.Messages
import           Matterhorn.Draw.Util
import           Matterhorn.Themes
import           Matterhorn.Types

hLimitWithPadding :: Int -> Widget n -> Widget n
hLimitWithPadding pad contents = Widget
  { hSize  = Fixed
  , vSize  = (vSize contents)
  , render =
      withReaderT (& availWidthL  %~ (\ n -> n - (2 * pad))) $ render $ cropToContext contents
  }

drawPostListWindow :: PostListContents -> ChatState -> TeamId -> Widget Name
drawPostListWindow contents st tId = joinBorders $ drawPostsBox contents st tId

-- | Draw a PostListWindow as a floating window on top of whatever
-- is rendered beneath it
drawPostsBox :: PostListContents -> ChatState -> TeamId -> Widget Name
drawPostsBox contents st tId =
  centerLayer $ hLimitWithPadding 10 $ borderWithLabel contentHeader $
    padRight (Pad 1) messageListContents
  where -- The 'window title' of the window
        hs = getHighlightSet st tId
        contentHeader = withAttr channelListHeaderAttr $ txt $ case contents of
          PostListFlagged -> "Flagged posts"
          PostListPinned cId ->
              let cName = case findChannelById cId (st^.csChannels) of
                      Nothing -> "<UNKNOWN>"
                      Just cc -> mkChannelName st (cc^.ccInfo)
              in "Posts pinned in " <> cName
          PostListSearch terms searching -> "Search results" <> if searching
            then ": " <> terms
            else " (" <> (T.pack . show . length) entries <> "): " <> terms

        entries = filterMessages knownChannel $ st^.csTeam(tId).tsPostListWindow.postListPosts
        messages = insertDateMarkers
                     entries
                     (getDateFormat st)
                     (st^.timeZone)

        knownChannel msg =
            case msg^.mChannelId of
                Just cId | Nothing <- st^?csChannels.channelByIdL(cId) -> False
                _ -> True

        -- The overall contents, with a sensible default even if there
        -- are no messages
        messageListContents
          | null messages =
            padTopBottom 1 $
            hCenter $
            withDefAttr clientEmphAttr $
            str $ case contents of
              PostListFlagged -> "You have no flagged messages."
              PostListPinned _ -> "This channel has no pinned messages."
              PostListSearch _ searching ->
                if searching
                  then "Searching ..."
                  else "No search results found"
          | otherwise = vBox renderedMessageList

        -- The render-message function we're using
        renderMessageForWindow msg tState tag =
          let renderedMsg = renderSingleMessage st hs True Nothing msg tState tag
          in case msg^.mOriginalPost of
            -- We should factor out some of the channel name logic at
            -- some point, but we can do that later
            Just post
              | Just chan <- st^?csChannels.channelByIdL(post^.postChannelIdL) ->
                 case chan^.ccInfo.cdType of
                  Direct
                    | Just u <- flip userById st =<< chan^.ccInfo.cdDMUserId ->
                        (forceAttr channelNameAttr (txt (addUserSigil $ u^.uiName)) <=>
                          (str "  " <+> renderedMsg))
                  _ -> (forceAttr channelNameAttr (txt (chan^.ccInfo.to (mkChannelName st))) <=>
                         (str "  " <+> renderedMsg))
            _ | CP _ <- msg^.mType -> str "[BUG: unknown channel]"
              | otherwise -> renderedMsg

        -- The full message list, rendered with the current selection
        renderedMessageList =
          let (s, (before, after)) = splitDirSeqOn matchesMessage messagesWithStates
              matchesMessage (m, _) = m^.mMessageId == (MessagePostId <$> st^.csTeam(tId).tsPostListWindow.postListSelected)
              messagesWithStates = (, InThreadShowParent) <$> messages
              tag = PostList
          in case s of
            Nothing ->
                map (\(m, tst) -> renderMessageForWindow m tst tag) (toList messagesWithStates)
            Just curMsg ->
              [unsafeRenderMessageSelection (curMsg, (before, after)) renderMessageForWindow tag]


text:
<<<<<<< HEAD
<<<<<<< HEAD
# mime

Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.

## Install

Install with [npm](http://github.com/isaacs/npm):

    npm install mime

## API - Queries

### mime.lookup(path)
Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.').  E.g.

    var mime = require('mime');

    mime.lookup('/path/to/file.txt');         // => 'text/plain'
    mime.lookup('file.txt');                  // => 'text/plain'
    mime.lookup('.TXT');                      // => 'text/plain'
    mime.lookup('htm');                       // => 'text/html'

### mime.default_type
Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)

### mime.extension(type)
Get the default extension for `type`

    mime.extension('text/html');                 // => 'html'
    mime.extension('application/octet-stream');  // => 'bin'

### mime.charsets.lookup()

Map mime-type to charset

    mime.charsets.lookup('text/plain');        // => 'UTF-8'

(The logic for charset lookups is pretty rudimentary.  Feel free to suggest improvements.)

## API - Defining Custom Types

The following APIs allow you to add your own type mappings within your project.  If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).

### mime.define()

Add custom mime/extension mappings

    mime.define({
        'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],
        'application/x-my-type': ['x-mt', 'x-mtt'],
        // etc ...
    });

    mime.lookup('x-sft');                 // => 'text/x-some-format'

The first entry in the extensions array is returned by `mime.extension()`. E.g.

    mime.extension('text/x-some-format'); // => 'x-sf'

### mime.load(filepath)

Load mappings from an Apache ".types" format file

    mime.load('./my_project.types');

The .types file format is simple -  See the `types` dir for examples.
=======
# mime

Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.

## Install

Install with [npm](http://github.com/isaacs/npm):

    npm install mime

## API - Queries

### mime.lookup(path)
Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.').  E.g.

    var mime = require('mime');

    mime.lookup('/path/to/file.txt');         // => 'text/plain'
    mime.lookup('file.txt');                  // => 'text/plain'
    mime.lookup('.TXT');                      // => 'text/plain'
    mime.lookup('htm');                       // => 'text/html'

### mime.default_type
Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)

### mime.extension(type)
Get the default extension for `type`

    mime.extension('text/html');                 // => 'html'
    mime.extension('application/octet-stream');  // => 'bin'

### mime.charsets.lookup()

Map mime-type to charset

    mime.charsets.lookup('text/plain');        // => 'UTF-8'

(The logic for charset lookups is pretty rudimentary.  Feel free to suggest improvements.)

## API - Defining Custom Types

The following APIs allow you to add your own type mappings within your project.  If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).

### mime.define()

Add custom mime/extension mappings

    mime.define({
        'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],
        'application/x-my-type': ['x-mt', 'x-mtt'],
        // etc ...
    });

    mime.lookup('x-sft');                 // => 'text/x-some-format'

The first entry in the extensions array is returned by `mime.extension()`. E.g.

    mime.extension('text/x-some-format'); // => 'x-sf'

### mime.load(filepath)

Load mappings from an Apache ".types" format file

    mime.load('./my_project.types');

The .types file format is simple -  See the `types` dir for examples.
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
# mime

Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.

## Install

Install with [npm](http://github.com/isaacs/npm):

    npm install mime

## API - Queries

### mime.lookup(path)
Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.').  E.g.

    var mime = require('mime');

    mime.lookup('/path/to/file.txt');         // => 'text/plain'
    mime.lookup('file.txt');                  // => 'text/plain'
    mime.lookup('.TXT');                      // => 'text/plain'
    mime.lookup('htm');                       // => 'text/html'

### mime.default_type
Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)

### mime.extension(type)
Get the default extension for `type`

    mime.extension('text/html');                 // => 'html'
    mime.extension('application/octet-stream');  // => 'bin'

### mime.charsets.lookup()

Map mime-type to charset

    mime.charsets.lookup('text/plain');        // => 'UTF-8'

(The logic for charset lookups is pretty rudimentary.  Feel free to suggest improvements.)

## API - Defining Custom Types

The following APIs allow you to add your own type mappings within your project.  If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).

### mime.define()

Add custom mime/extension mappings

    mime.define({
        'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],
        'application/x-my-type': ['x-mt', 'x-mtt'],
        // etc ...
    });

    mime.lookup('x-sft');                 // => 'text/x-some-format'

The first entry in the extensions array is returned by `mime.extension()`. E.g.

    mime.extension('text/x-some-format'); // => 'x-sf'

### mime.load(filepath)

Load mappings from an Apache ".types" format file

    mime.load('./my_project.types');

The .types file format is simple -  See the `types` dir for examples.
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
package ru.atom.model.dao;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import ru.atom.model.data.Like;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

class Database {
    private static final Logger log = LogManager.getLogger(Database.class);
    private static final SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration().configure()
                .buildSessionFactory();

        log.info("Session factory configured.");
    }

    static <T> List<T> selectTransactional(Function<Session, List<T>> selectAction) {
        Transaction txn = null;
        List<T> ts = Collections.emptyList();
        try (Session session = Database.openSession()) {
            txn = session.beginTransaction();
            ts = selectAction.apply(session);
            txn.commit();
        } catch (RuntimeException e) {
            log.error("Transaction failed.", e);
            if (txn != null && txn.isActive()) {
                txn.rollback();
            }
        }

        return ts;
    }

    static void doTransactional(Function<Session, ?> f) {
        Transaction txn = null;
        try (Session session = Database.openSession()) {
            txn = session.beginTransaction();
            f.apply(session);
            txn.commit();
        } catch (RuntimeException e) {
            log.error("Transaction failed.", e);
            if (txn != null && txn.isActive()) {
                txn.rollback();
            }
        }
    }

    static Session openSession() {
        return sessionFactory.openSession();
    }

    private Database() { }
}


text:
package org.apache.mesos.hdfs.state;

import com.google.inject.Inject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.hdfs.config.HdfsFrameworkConfig;
import org.apache.mesos.hdfs.scheduler.Reconciler;
import org.apache.mesos.process.FailureUtils;
import org.apache.mesos.hdfs.util.HDFSConstants;

/**
 * The Scheduler state machine.
 */
public class StateMachine {
  private final HdfsState state;
  private final HdfsFrameworkConfig config;
  private final Log log = LogFactory.getLog(StateMachine.class);
  private final Reconciler reconciler;
  private AcquisitionPhase currPhase;

  @Inject
  public StateMachine(
    HdfsState state,
    HdfsFrameworkConfig config,
    Reconciler reconciler) {
    this.state = state;
    this.config = config;
    this.currPhase = AcquisitionPhase.RECONCILING_TASKS;
    this.reconciler = reconciler;
  }

  public Reconciler getReconciler() {
    return reconciler;
  }

  public AcquisitionPhase getCurrentPhase() {
    return currPhase;
  }

  public AcquisitionPhase correctPhase() {
    int currJournalCount = 0;
    int currNameCount = 0;

    try {
      currJournalCount = state.getJournalCount();
      currNameCount = state.getNameCount();
    } catch (Exception ex) {
      // We will not change phase here if we cannot determine our state
      log.error("Failed to fetch node counts with exception: " + ex);
      return currPhase;
    }

    int targetJournalCount = config.getJournalNodeCount();
    int targetNameCount = HDFSConstants.TOTAL_NAME_NODES;

    log.info(String.format("Correcting phase with journal counts: %s/%s and name counts: %s/%s",
      currJournalCount,
      targetJournalCount,
      currNameCount,
      targetNameCount));

    if (!reconciler.complete()) {
      transitionTo(AcquisitionPhase.RECONCILING_TASKS);
    } else if (currJournalCount < targetJournalCount) {
      transitionTo(AcquisitionPhase.JOURNAL_NODES);
    } else if (currNameCount < targetNameCount || !state.nameNodesInitialized()) {
      transitionTo(AcquisitionPhase.NAME_NODES);
    } else {
      transitionTo(AcquisitionPhase.DATA_NODES);
    }

    log.info("Current phase is now: " + currPhase);
    return currPhase;
  }

  private void transitionTo(AcquisitionPhase nextPhase) {
    if (currPhase.equals(nextPhase)) {
      log.info(String.format("Acquisition phase is already '%s'", currPhase));
    } else {
      log.info(String.format("Transitioning from acquisition phase '%s' to '%s'", currPhase, nextPhase));
      currPhase = nextPhase;
    }
  }

  public void reconcile(SchedulerDriver driver) {
    try {
      transitionTo(AcquisitionPhase.RECONCILING_TASKS);
      reconciler.reconcile(driver);
    } catch (Exception ex) {
      FailureUtils.exit("Failed to conduct Reconciliation with exception: " + ex, HDFSConstants.RECONCILE_EXIT_CODE);
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of xcomp:adj in UD_Vietnamese-VTB</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Vietnamese-VTB: Relations: xcomp:adj

This relation is a language-specific subtype of <tt>xcomp</tt>.
There are also 1 other language-specific subtypes of xcomp: <tt>xcomp:vcomp</tt>.

125 nodes (0%) are attached to their parents as xcomp:adj.

123 instances of xcomp:adj (98%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.184.

The following 5 pairs of parts of speech are connected with xcomp:adj: <tt>ADJ</tt>-<tt>VERB</tt> (112; 90% instances), <tt>VERB</tt>-<tt>ADJ</tt> (7; 6% instances), <tt>ADV</tt>-<tt>VERB</tt> (4; 3% instances), <tt>ADJ</tt>-<tt>ADJ</tt> (1; 1% instances), <tt>VERB</tt>-<tt>VERB</tt> (1; 1% instances).

# visual-style 11	bgColor:blue
# visual-style 11	fgColor:white
# visual-style 10	bgColor:blue
# visual-style 10	fgColor:white
# visual-style 10 11 xcomp:adj	color:blue
1	Hùng	hùng	PROPN	NNP	_	2	nsubj	_	_
2	thở phào	thở phào	VERB	V	_	0	root	_	_
3	,	,	PUNCT	,	_	2	punct	_	_
4	nếu	nếu	SCONJ	SC	_	6	mark	_	_
5	là	là	AUX	V	_	6	cop	_	_
6	bà	bà	NOUN	N	_	10	advcl	_	_
7	ta	ta	PRON	Pro	_	6	det:pmod	_	_
8	thì	thì	SCONJ	SC	_	10	mark	_	_
9	rất	rất	ADV	Adv	_	10	advmod	_	_
10	dễ	dễ	ADJ	Adj	_	2	conj	_	_
11	hóa giải	hóa giải	VERB	V	_	10	xcomp:adj	_	_
12	.	.	PUNCT	.	_	2	punct	_	_

# visual-style 6	bgColor:blue
# visual-style 6	fgColor:white
# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 4 6 xcomp:adj	color:blue
1	Cường	cường	PROPN	NNP	_	2	nsubj	_	_
2	phân tích	phân tích	VERB	V	_	0	root	_	_
3	nếu	nếu	SCONJ	SC	_	4	mark	_	_
4	liên quan	liên quan	VERB	V	_	2	advcl	_	_
5	càng	càng	ADV	Adv	_	6	advmod	_	_
6	dễ	dễ	ADJ	Adj	_	4	xcomp:adj	_	_
7	tìm	tìm	VERB	V	_	6	xcomp:adj	_	_
8	.	.	PUNCT	.	_	2	punct	_	_

# visual-style 8	bgColor:blue
# visual-style 8	fgColor:white
# visual-style 7	bgColor:blue
# visual-style 7	fgColor:white
# visual-style 7 8 xcomp:adj	color:blue
1	Người	người	NOUN	N	_	7	obl	_	_
2	này	này	PRON	Pro	_	1	det:pmod	_	_
3	ông	ông	NOUN	Nc	_	4	clf:det	_	_
4	Phong	Phong	PROPN	NNP	_	7	nsubj	_	_
5	cũng	cũng	ADV	Adv	_	7	advmod	_	_
6	phải	phải	AUX	AUX	_	7	aux	_	_
7	có	có	ADV	Adv	_	0	root	_	_
8	quen biết	quen biết	VERB	V	_	7	xcomp:adj	_	_
9	.	.	PUNCT	.	_	7	punct	_	_

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
//
//  AbsResponseDataSerializer.h
//  AFNetworking-3.x
//
//  Created by YouXianMing on 16/3/12.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AbsResponseDataSerializer : NSObject

/**
 *  处理返回的参数
 *
 *  @param data 处理前的参数
 *
 *  @return 处理后的参数
 */
- (id)serializeResponseData:(id)data;

@end


text:
	<title>Aravinda de Silva's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Aravinda de Silva's panel show appearances

Aravinda de Silva (born 1965-10-17[ref]) has appeared in 1 episodes between 2006-2006.  Aravinda de Silva on Wikipedia.

2006

2006-07-07 / A Question of Sport


text:
class PixelInfo
{
public:
    PixelInfo() {};
    PixelInfo(int isize, int fsize, int usize) {idata.resize(isize); fdata.resize(fsize); udata.resize(usize);};
    std::vector<int> idata;
    std::vector<float> fdata;
    std::vector<unsigned char> udata;
};

class GlobalComposite
{
public:
    GlobalComposite();
    virtual ~GlobalComposite();

    void gather(Frame* leaf);
    void composite();

protected:
    void convertNormal(unsigned char x, unsigned char y, unsigned char z, unsigned short spherical[2]) const;
    void convertNormalF(float x, float y, float z, float spherical[2]) const;
    unsigned int combineDepthNormal(float depth, unsigned char x, unsigned char y, unsigned char z) const;

private:
    static const int NUM_SCALARS = 1;
    static const int root = 0;
    static const int nCameras = 1;
    static const int compressMode = 3;
    static const bool enableId = false;

    int global_resolution[2];
    double global_extent[6];
    std::vector<Frame *> frames;
    std::map<float, PixelInfo>* depth_list;

    ConfigReader& config() const { return ConfigReader::getInstance(); }
};

#endif


text:
class BackerDecorator < Draper::Decorator
  decorates :backer
  include Draper::LazyHelpers

  def display_value
    number_to_currency source.value
  end

  def display_confirmed_at
    I18n.l(source.confirmed_at.to_date) if source.confirmed_at
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 61(1-2): 243 (1995)

#### Original name
Rhinocladiella pyriformis Pagano & Zucconi

### Remarks
null


text:
package com.ulisesbocchio.jasyptspringboot.wrapper;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertySource;
import com.ulisesbocchio.jasyptspringboot.util.Iterables;
import org.springframework.boot.context.properties.source.ConfigurationProperty;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.InvalidConfigurationPropertyNameException;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginLookup;
import org.springframework.core.env.PropertySource;

public class EncryptableConfigurationPropertySourcesPropertySource extends PropertySource<Iterable<ConfigurationPropertySource>>
        implements EncryptablePropertySource<Iterable<ConfigurationPropertySource>> {

    private final PropertySource<Iterable<ConfigurationPropertySource>> delegate;

    public EncryptableConfigurationPropertySourcesPropertySource(PropertySource<Iterable<ConfigurationPropertySource>> delegate) {
        super(delegate.getName(), Iterables.filter(delegate.getSource(), configurationPropertySource -> !configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)));
        this.delegate = delegate;
    }

    @Override
    public PropertySource<Iterable<ConfigurationPropertySource>> getDelegate() {
        return delegate;
    }

    @Override
    public void refresh() {

    }

    @Override
    public Object getProperty(String name) {
        ConfigurationProperty configurationProperty = findConfigurationProperty(name);
        return (configurationProperty != null) ? configurationProperty.getValue() : null;
    }

    @Override
    public Origin getOrigin(String name) {
        return Origin.from(findConfigurationProperty(name));
    }

    private ConfigurationProperty findConfigurationProperty(String name) {
        try {
            return findConfigurationProperty(ConfigurationPropertyName.of(name));
        }
        catch (InvalidConfigurationPropertyNameException ex) {
            // simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid)
            if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) {
                return null;
            }
            throw ex;
        }
    }

    private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) {
        if (name == null) {
            return null;
        }
        for (ConfigurationPropertySource configurationPropertySource : getSource()) {
            if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) {
                ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name);
                if (configurationProperty != null) {
                    return configurationProperty;
                }
            }
        }
        return null;
    }
}


text:
package com.commercetools.sunrise.myaccount.myorders.myorderdetail.viewmodels;

import com.commercetools.sunrise.framework.viewmodels.content.carts.CartViewModel;
import com.commercetools.sunrise.framework.viewmodels.content.PageContent;

public class MyOrderDetailPageContent extends PageContent {

    private CartViewModel order;

    public MyOrderDetailPageContent() {
    }

    public CartViewModel getOrder() {
        return order;
    }

    public void setOrder(final CartViewModel order) {
        this.order = order;
    }
}


text:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build cgo,!arm,!arm64,!ios

package x509

/*
#cgo CFLAGS: -mmacosx-version-min=10.6 -D__MAC_OS_X_VERSION_MAX_ALLOWED=1060
#cgo LDFLAGS: -framework CoreFoundation -framework Security

#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>

// FetchPEMRoots fetches the system's list of trusted X.509 root certificates.
//
// On success it returns 0 and fills pemRoots with a CFDataRef that contains the extracted root
// certificates of the system. On failure, the function returns -1.
//
// Note: The CFDataRef returned in pemRoots must be released (using CFRelease) after
// we've consumed its content.
int FetchPEMRoots(CFDataRef *pemRoots) {
	if (pemRoots == NULL) {
		return -1;
	}

	CFArrayRef certs = NULL;
	OSStatus err = SecTrustCopyAnchorCertificates(&certs);
	if (err != noErr) {
		return -1;
	}

	CFMutableDataRef combinedData = CFDataCreateMutable(kCFAllocatorDefault, 0);
	int i, ncerts = CFArrayGetCount(certs);
	for (i = 0; i < ncerts; i++) {
		CFDataRef data = NULL;
		SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
		if (cert == NULL) {
			continue;
		}

		// Note: SecKeychainItemExport is deprecated as of 10.7 in favor of SecItemExport.
		// Once we support weak imports via cgo we should prefer that, and fall back to this
		// for older systems.
		err = SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data);
		if (err != noErr) {
			continue;
		}

		if (data != NULL) {
			CFDataAppendBytes(combinedData, CFDataGetBytePtr(data), CFDataGetLength(data));
			CFRelease(data);
		}
	}

	CFRelease(certs);

	*pemRoots = combinedData;
	return 0;
}
*/
import "C"
import (
	"errors"
	"unsafe"
)

func loadSystemRoots() (*CertPool, error) {
	roots := NewCertPool()

	var data C.CFDataRef = nil
	err := C.FetchPEMRoots(&data)
	if err == -1 {
		// TODO: better error message
		return nil, errors.New("crypto/x509: failed to load darwin system roots with cgo")
	}

	defer C.CFRelease(C.CFTypeRef(data))
	buf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data)))
	roots.AppendCertsFromPEM(buf)
	return roots, nil
}


text:
package cmd

import (
	"bytes"
	"fmt"
	"io"
	"strings"

	"github.com/MakeNowJust/heredoc"
	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/oc/cli/util/clientcmd"

	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

type concept struct {
	Name         string
	Abbreviation string
	Description  string
}

var concepts = []concept{
	{
		"Containers",
		"",
		heredoc.Doc(`
      A definition of how to run one or more processes inside of a portable Linux
      environment. Containers are started from an Image and are usually isolated
      from other containers on the same machine.
    `),
	},
	{
		"Image",
		"",
		heredoc.Doc(`
      A layered Linux filesystem that contains application code, dependencies,
      and any supporting operating system libraries. An image is identified by
      a name that can be local to the current cluster or point to a remote Docker
      registry (a storage server for images).
    `),
	}, {
		"Pods",
		"pod",
		heredoc.Doc(`
      A set of one or more containers that are deployed onto a Node together and
      share a unique IP and Volumes (persistent storage). Pods also define the
      security and runtime policy for each container.
    `),
	}, {
		"Labels",
		"",
		heredoc.Doc(`
      Labels are key value pairs that can be assigned to any resource in the
      system for grouping and selection. Many resources use labels to identify
      sets of other resources.
    `),
	}, {
		"Volumes",
		"",
		heredoc.Doc(`
      Containers are not persistent by default - on restart their contents are
      cleared. Volumes are mounted filesystems available to Pods and their
      containers which may be backed by a number of host-local or network
      attached storage endpoints. The simplest volume type is EmptyDir, which
      is a temporary directory on a single machine. Administrators may also
      allow you to request a Persistent Volume that is automatically attached
      to your pods.
    `),
	}, {
		"Nodes",
		"node",
		heredoc.Doc(`
      Machines set up in the cluster to run containers. Usually managed
      by administrators and not by end users.
    `),
	}, {
		"Services",
		"svc",
		heredoc.Doc(`
      A name representing a set of pods (or external servers) that are
      accessed by other pods. The service gets an IP and a DNS name, and can be
      exposed externally to the cluster via a port or a Route. It's also easy
      to consume services from pods because an environment variable with the
      name <SERVICE>_HOST is automatically injected into other pods.
    `),
	}, {
		"Routes",
		"route",
		heredoc.Doc(`
      A route is an external DNS entry (either a top level domain or a
      dynamically allocated name) that is created to point to a service so that
      it can be accessed outside the cluster. The administrator may configure
      one or more Routers to handle those routes, typically through an Apache
      or HAProxy load balancer / proxy.
    `),
	},
	{
		"Replication Controllers",
		"rc",
		heredoc.Doc(`
      A replication controller maintains a specific number of pods based on a
      template that match a set of labels. If pods are deleted (because the
      node they run on is taken out of service) the controller creates a new
      copy of that pod. A replication controller is most commonly used to
      represent a single deployment of part of an application based on a
      built image.
    `),
	},
	{
		"Deployment Configuration",
		"dc",
		heredoc.Doc(`
      Defines the template for a pod and manages deploying new images or
      configuration changes whenever those change. A single deployment
      configuration is usually analogous to a single micro-service. Can support
      many different deployment patterns, including full restart, customizable
      rolling updates, and fully custom behaviors, as well as pre- and post-
      hooks. Each deployment is represented as a replication controller.
    `),
	},
	{
		"Build Configuration",
		"bc",
		heredoc.Doc(`
      Contains a description of how to build source code and a base image into a
      new image - the primary method for delivering changes to your application.
      Builds can be source based and use builder images for common languages like
      Java, PHP, Ruby, or Python, or be Docker based and create builds from a
      Dockerfile. Each build configuration has web-hooks and can be triggered
      automatically by changes to their base images.
    `),
	},
	{
		"Builds",
		"build",
		heredoc.Doc(`
      Builds create a new image from source code, other images, Dockerfiles, or
      binary input. A build is run inside of a container and has the same
      restrictions normal pods have. A build usually results in an image pushed
      to a Docker registry, but you can also choose to run a post-build test that
      does not push an image.
    `),
	},
	{
		"Image Streams and Image Stream Tags",
		"is,istag",
		heredoc.Doc(`
      An image stream groups sets of related images under tags - analogous to a
      branch in a source code repository. Each image stream may have one or
      more tags (the default tag is called "latest") and those tags may point
      at external Docker registries, at other tags in the same stream, or be
      controlled to directly point at known images. In addition, images can be
      pushed to an image stream tag directly via the integrated Docker
      registry.
    `),
	},
	{
		"Secrets",
		"secret",
		heredoc.Doc(`
      The secret resource can hold text or binary secrets for delivery into
      your pods. By default, every container is given a single secret which
      contains a token for accessing the API (with limited privileges) at
      /var/run/secrets/kubernetes.io/serviceaccount. You can create new
      secrets and mount them in your own pods, as well as reference secrets
      from builds (for connecting to remote servers) or use them to import
      remote images into an image stream.
    `),
	},
	{
		"Projects",
		"project",
		heredoc.Doc(`
      All of the above resources (except Nodes) exist inside of a project.
      Projects have a list of members and their roles, like viewer, editor,
      or admin, as well as a set of security controls on the running pods, and
      limits on how many resources the project can use. The names of each
      resource are unique within a project. Developers may request projects
      be created, but administrators control the resources allocated to
      projects.
    `),
	},
}

func writeConcept(w io.Writer, c concept) {
	fmt.Fprintf(w, "* %s", c.Name)
	if len(c.Abbreviation) > 0 {
		fmt.Fprintf(w, " [%s]", c.Abbreviation)
	}
	fmt.Fprintln(w, ":")
	for _, s := range strings.Split(c.Description, "\n") {
		fmt.Fprintf(w, "    %s\n", s)
	}
}

var (
	typesLong = templates.LongDesc(`
    Concepts and Types

    Kubernetes and OpenShift help developers and operators build, test, and deploy
    applications in a containerized cloud environment. Applications may be composed
    of all of the components below, although most developers will be concerned with
    Services, Deployments, and Builds for delivering changes.

    Concepts:

    %[1]sFor more, see https://docs.openshift.com`)

	typesExample = templates.Examples(`
		# View all projects you have access to
	  %[1]s get projects

	  # See a list of all services in the current project
	  %[1]s get svc

	  # Describe a deployment configuration in detail
	  %[1]s describe dc mydeploymentconfig

	  # Show the images tagged into an image stream
	  %[1]s describe is ruby-centos7`)
)

func NewCmdTypes(fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	buf := &bytes.Buffer{}
	for _, c := range concepts {
		writeConcept(buf, c)
	}
	cmd := &cobra.Command{
		Use:     "types",
		Short:   "An introduction to concepts and types",
		Long:    fmt.Sprintf(typesLong, buf.String()),
		Example: fmt.Sprintf(typesExample, fullName),
		Run:     kcmdutil.DefaultSubCommandRun(out),
	}
	return cmd
}