text:
<?php

/**
 * @namespace
 */
namespace Pop\Http;

/**
 * HTTP response class
 *
 * @category   Pop
 * @package    Pop_Http
 * @author     Nick Sagona, III <nick@popphp.org>
 * @copyright  Copyright (c) 2009-2014 Moc 10 Media, LLC. (http://www.moc10media.com)
 * @license    http://www.popphp.org/license     New BSD License
 * @version    1.7.0
 */
class Response
{

    /**
     * Response codes & messages
     * @var array
     */
    protected static $responseCodes = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',

        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',

        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',

        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );

    /**
     * HTTP version
     * @var string
     */
    protected $version = '1.1';

    /**
     * Response code
     * @var int
     */
    protected $code = null;

    /**
     * Response message
     * @var string
     */
    protected $message = null;

    /**
     * Response headers
     * @var array
     */
    protected $headers = array();

    /**
     * Response body
     * @var string
     */
    protected $body = null;

    /**
     * Constructor
     *
     * Instantiate the response object.
     *
     * @param  int    $code
     * @param  array  $headers
     * @param  string $body
     * @param  string $message
     * @param  string $version
     * @throws Exception
     * @return \Pop\Http\Response
     */
    public function __construct($code = 200, array $headers = null, $body = null, $message = null, $version = '1.1')
    {
        if (!array_key_exists($code, self::$responseCodes)) {
            throw new Exception('The header code '. $code . ' is not allowed.');
        }

        $this->code = $code;
        $this->message = (null !== $message) ? $message : self::$responseCodes[$code];
        $this->body = $body;
        $this->version = $version;

        if (null === $headers) {
            $headers = array('Content-Type' => 'text/html');
        }

        foreach ($headers as $name => $value) {
            $this->headers[$name] = $value;
        }
    }

    /**
     * Parse a response and create a new response object,
     * either from a URL or a full response string
     *
     * @param  string $response
     * @param  array  $context
     * @param  string $mode
     * @throws Exception
     * @return \Pop\Http\Response
     */
    public static function parse($response, array $context = null, $mode = 'r')
    {
        $headers = array();

        // If a URL, use a stream to get the header and URL contents
        if ((strtolower(substr($response, 0, 7)) == 'http://') || (strtolower(substr($response, 0, 8)) == 'https://')) {
            $http_response_header = null;

            if (null !== $context) {
                $stream = @fopen($response, $mode, false, stream_context_create(array('http' => $context)));
            } else {
                $stream = @fopen($response, $mode);
            }

            if ($stream != false) {
                $meta = stream_get_meta_data($stream);
                $body = stream_get_contents($stream);

                $firstLine = $meta['wrapper_data'][0];
                unset($meta['wrapper_data'][0]);
                $allHeadersAry = $meta['wrapper_data'];
                $bodyStr = $body;
            } else {
                $firstLine = $http_response_header[0];
                unset($http_response_header[0]);
                $allHeadersAry = $http_response_header;
                $bodyStr = null;
            }
        // Else, if a response string, parse the headers and contents
        } else if (substr($response, 0, 5) == 'HTTP/'){
            if (strpos($response, "\r") !== false) {
                $headerStr = substr($response, 0, strpos($response, "\r\n"));
                $bodyStr = substr($response, (strpos($response, "\r\n") + 2));
            } else {
                $headerStr = substr($response, 0, strpos($response, "\n\n"));
                $bodyStr = substr($response, (strpos($response, "\n\n") + 2));
            }

            $firstLine = trim(substr($headerStr, 0, strpos($headerStr, "\n")));
            $allHeaders = trim(substr($headerStr, strpos($headerStr, "\n")));
            $allHeadersAry = explode("\n", $allHeaders);
        } else {
            throw new Exception('The response was not properly formatted.');
        }

        // Get the version, code and message
        $version = substr($firstLine, 0, strpos($firstLine, ' '));
        $version = substr($version, (strpos($version, '/') + 1));
        preg_match('/\d\d\d/', trim($firstLine), $match);
        $code = $match[0];
        $message = str_replace('HTTP/' . $version . ' ' . $code . ' ', '', $firstLine);

        // Get the headers
        foreach ($allHeadersAry as $hdr) {
            $name = substr($hdr, 0, strpos($hdr, ':'));
            $value = substr($hdr, (strpos($hdr, ' ') + 1));
            $headers[trim($name)] = trim($value);
        }

        // If the body content is encoded, decode the body content
        if (array_key_exists('Content-Encoding', $headers)) {
            if (isset($headers['Transfer-Encoding']) && ($headers['Transfer-Encoding'] == 'chunked')) {
                $bodyStr = self::decodeChunkedBody($bodyStr);
            }
            $body = self::decodeBody($bodyStr, $headers['Content-Encoding']);
        } else {
            $body = $bodyStr;
        }

        return new Response($code, $headers, $body, $message, $version);
    }

    /**
     * Send redirect
     *
     * @param  string $url
     * @param  string $code
     * @param  string $version
     * @throws Exception
     * @return void
     */
    public static function redirect($url, $code = '302', $version = '1.1')
    {
        if (headers_sent()) {
            throw new Exception('The headers have already been sent.');
        }

        header("HTTP/{$version} {$code} " . self::$responseCodes[$code]);
        header("Location: {$url}");
    }

    /**
     * Get response message from code
     *
     * @param  int $code
     * @throws Exception
     * @return string
     */
    public static function getMessageFromCode($code)
    {
        if (!array_key_exists($code, self::$responseCodes)) {
            throw new Exception('The header code ' . $code . ' is not allowed.');
        }

        return self::$responseCodes[$code];
    }

    /**
     * Encode the body data.
     *
     * @param  string $body
     * @param  string $encode
     * @throws Exception
     * @return string
     */
    public static function encodeBody($body, $encode = 'gzip')
    {
        switch ($encode) {
            // GZIP compression
            case 'gzip':
                if (!function_exists('gzencode')) {
                    throw new Exception('Gzip compression is not available.');
                }
                $encodedBody = gzencode($body);
                break;

            // Deflate compression
            case 'deflate':
                if (!function_exists('gzdeflate')) {
                    throw new Exception('Deflate compression is not available.');
                }
                $encodedBody = gzdeflate($body);
                break;

            // Unknown compression
            default:
                $encodedBody = $body;

        }

        return $encodedBody;
    }

    /**
     * Decode the body data.
     *
     * @param  string $body
     * @param  string $decode
     * @throws Exception
     * @return string
     */
    public static function decodeBody($body, $decode = 'gzip')
    {
        switch ($decode) {
            // GZIP compression
            case 'gzip':
                if (!function_exists('gzinflate')) {
                    throw new Exception('Gzip compression is not available.');
                }
                $decodedBody = gzinflate(substr($body, 10));
                break;

            // Deflate compression
            case 'deflate':
                if (!function_exists('gzinflate')) {
                    throw new Exception('Deflate compression is not available.');
                }
                $zlibHeader = unpack('n', substr($body, 0, 2));
                $decodedBody = ($zlibHeader[1] % 31 == 0) ? gzuncompress($body) : gzinflate($body);
                break;

            // Unknown compression
            default:
                $decodedBody = $body;

        }

        return $decodedBody;
    }

    /**
     * Decode a chunked transfer-encoded body and return the decoded text
     *
     * @param string $body
     * @return string
     */
    public static function decodeChunkedBody($body)
    {
        $decoded = '';

        while($body != '') {
            $lf_pos = strpos($body, "\012");
            if($lf_pos === false) {
                $decoded .= $body;
                break;
            }
            $chunk_hex = trim(substr($body, 0, $lf_pos));
            $sc_pos = strpos($chunk_hex, ';');
            if($sc_pos !== false)
                $chunk_hex = substr($chunk_hex, 0, $sc_pos);
            if($chunk_hex == '') {
                $decoded .= substr($body, 0, $lf_pos);
                $body = substr($body, $lf_pos + 1);
                continue;
            }
            $chunk_len = hexdec($chunk_hex);
            if($chunk_len) {
                $decoded .= substr($body, $lf_pos + 1, $chunk_len);
                $body = substr($body, $lf_pos + 2 + $chunk_len);
            } else {
                $body = '';
            }
        }

        return $decoded;
    }

    /**
     * Determine if the response is successful
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        $type = floor($this->code / 100);
        return (($type == 3) || ($type == 2) || ($type == 1)) ? true : false;
    }

    /**
     * Determine if the response is a redirect
     *
     * @return boolean
     */
    public function isRedirect()
    {
        $type = floor($this->code / 100);
        return ($type == 3) ? true : false;
    }

    /**
     * Determine if the response is an error
     *
     * @return boolean
     */
    public function isError()
    {
        $type = floor($this->code / 100);
        return (($type == 5) || ($type == 4)) ? true : false;
    }

    /**
     * Get the response code
     *
     * @return int
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Get the response message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Get the response body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Get the response headers
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * Get the response header
     *
     * @param  string $name
     * @return string
     */
    public function getHeader($name)
    {
        return (isset($this->headers[$name])) ? $this->headers[$name] : null;
    }

    /**
     * Get the response headers as a string
     *
     * @param  boolean $status
     * @param  string  $br
     * @return string
     */
    public function getHeadersAsString($status = true, $br = "\n")
    {
        $headers = '';

        if ($status) {
            $headers = "HTTP/{$this->version} {$this->code} {$this->message}{$br}";
        }

        foreach ($this->headers as $name => $value) {
            $headers .= "{$name}: {$value}{$br}";
        }

        return $headers;
    }

    /**
     * Set the response code
     *
     * @param  int $code
     * @throws Exception
     * @return \Pop\Http\Response
     */
    public function setCode($code)
    {
        if (!array_key_exists($code, self::$responseCodes)) {
            throw new Exception('That header code ' . $code . ' is not allowed.');
        }

        $this->code = $code;
        $this->message = self::$responseCodes[$code];

        return $this;
    }

    /**
     * Set the response message
     *
     * @param  string $message
     * @return \Pop\Http\Response
     */
    public function setMessage($message)
    {
        $this->message = $message;
        return $this;
    }

    /**
     * Set the response body
     *
     * @param  string $body
     * @return \Pop\Http\Response
     */
    public function setBody($body = null)
    {
        $this->body = $body;
        return $this;
    }

    /**
     * Set a response header
     *
     * @param  string $name
     * @param  string $value
     * @throws Exception
     * @return \Pop\Http\Response
     */
    public function setHeader($name, $value)
    {
        $this->headers[$name] = $value;
        return $this;
    }

    /**
     * Set response headers
     *
     * @param  array $headers
     * @throws Exception
     * @return \Pop\Http\Response
     */
    public function setHeaders(array $headers)
    {
        foreach ($headers as $name => $value) {
            $this->headers[$name] = $value;
        }

        return $this;
    }

    /**
     * Set IE SSL headers to fix file cache issues in IE over SSL.
     *
     * @return \Pop\Http\Response
     */
    public function setSslHeaders()
    {
        $this->headers['Expires'] = 0;
        $this->headers['Cache-Control'] = 'private, must-revalidate';
        $this->headers['Pragma'] = 'cache';

        return $this;
    }

    /**
     * Send headers
     *
     * @throws Exception
     * @return void
     */
    public function sendHeaders()
    {
        header("HTTP/{$this->version} {$this->code} {$this->message}");
        foreach ($this->headers as $name => $value) {
            header($name . ": " . $value);
        }
    }

    /**
     * Send response
     *
     * @throws Exception
     * @return void
     */
    public function send()
    {
        if (headers_sent()) {
            throw new Exception('The headers have already been sent.');
        }

        $body = $this->body;

        if (array_key_exists('Content-Encoding', $this->headers)) {
            $body = self::encodeBody($body, $this->headers['Content-Encoding']);
            $this->headers['Content-Length'] = strlen($body);
        }

        $this->sendHeaders();
        echo $body;
    }

    /**
     * Return entire response as a string
     *
     * @return string
     */
    public function __toString()
    {
        $body = $this->body;

        if (array_key_exists('Content-Encoding', $this->headers)) {
            $body = self::encodeBody($body, $this->headers['Content-Encoding']);
            $this->headers['Content-Length'] = strlen($body);
        }

        return $this->getHeadersAsString() . "\n" . $body;
    }

}


text:
package cascading.dbmigrate.tap;

import cascading.dbmigrate.hadoop.DBInputFormat;
import cascading.dbmigrate.hadoop.TupleWrapper;
import cascading.scheme.Scheme;
import cascading.tap.Tap;
import cascading.tap.hadoop.TapIterator;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import cascading.tuple.TupleEntryCollector;
import cascading.tuple.TupleEntryIterator;
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import java.io.Serializable;

public class DBMigrateTap extends Tap {
    public static class Options implements Serializable {
        public Long minId = null;
        public Long maxId = null;
    }

    public class DBMigrateScheme extends Scheme {
        String dbDriver;
        String dbUrl;
        String username;
        String pwd;
        String tableName;
        String pkColumn;
        String[] columnNames;
        int numChunks;
        Options options;

        public DBMigrateScheme(int numChunks, String dbDriver, String dbUrl, String username, String pwd, String tableName, String pkColumn, String[] columnNames, Options options) {
            super(new Fields(columnNames));
            this.dbDriver = dbDriver;
            this.dbUrl = dbUrl;
            this.username = username;
            this.pwd = pwd;
            this.tableName = tableName;
            this.pkColumn = pkColumn;
            this.columnNames = columnNames;
            this.numChunks = numChunks;
            this.options = options;
        }

        @Override
        public void sourceInit(Tap tap, JobConf jc) throws IOException {
            // a hack for MultiInputFormat to see that there is a child format
            FileInputFormat.setInputPaths( jc, getPath() );

            DBInputFormat.setInput(jc, numChunks, dbDriver, username, pwd, dbUrl, tableName, pkColumn, options.minId, options.maxId, columnNames);
        }

        @Override
        public void sinkInit(Tap tap, JobConf jc) throws IOException {
            throw new UnsupportedOperationException("Cannot be used as a sink");
        }

        @Override
        public Tuple source(Object key, Object val) {
            return ((TupleWrapper) val).tuple;
        }

        @Override
        public void sink(TupleEntry te, OutputCollector oc) throws IOException {
            throw new UnsupportedOperationException("Cannot be used as a sink.");
        }
    }

    String connectionUrl;

    public DBMigrateTap(int numChunks, String dbDriver, String dbUrl, String username, String pwd, String tableName, String pkColumn, String[] columnNames) {
        this(numChunks, dbDriver, dbUrl, username, pwd, tableName, pkColumn, columnNames, new Options());
    }

    public DBMigrateTap(int numChunks, String dbDriver, String dbUrl, String username, String pwd, String tableName, String pkColumn, String[] columnNames, Options options) {
        setScheme(new DBMigrateScheme(numChunks, dbDriver, dbUrl, username, pwd, tableName, pkColumn, columnNames, options));
        this.connectionUrl = dbUrl;
    }

    @Override
    public Path getPath() {
        return new Path( "jdbc:/" + connectionUrl.replaceAll( ":", "_" ) );
    }

    @Override
    public TupleEntryIterator openForRead(JobConf conf) throws IOException {
        return new TupleEntryIterator(getSourceFields(), new TapIterator(this, conf));
    }

    @Override
    public TupleEntryCollector openForWrite(JobConf jc) throws IOException {
        throw new UnsupportedOperationException("Not supported.");
    }

    @Override
    public boolean makeDirs(JobConf jc) throws IOException {
        return true;
    }

    @Override
    public boolean deletePath(JobConf jc) throws IOException {
        return false;
    }

    @Override
    public boolean pathExists(JobConf jc) throws IOException {
        return true;
    }

    @Override
    public long getPathModified(JobConf jc) throws IOException {
        return System.currentTimeMillis();
    }

}

redpajama_set_name: RedPajamaGithub


text:
import React, { PropTypes } from 'react';
import moment from 'moment';
import DateUtils from './utils/DateUtils.js';
import formatMixin from './utils/formatMixin';
import DayPicker from './daypicker/DayPicker';
import MonthPicker from './monthpicker/MonthPicker';
import YearPicker from './yearpicker/YearPicker';
import ValueLinkMixin from './utils/ValueLinkMixin';
import cx from 'classnames';

const DatePicker = React.createClass({

  propTypes: {
    onChange: PropTypes.func,
    value: DateUtils.evaluateDateProp,
    valueLink: PropTypes.shape({
      value: DateUtils.evaluateDateProp,
      requestChange: React.PropTypes.func.isRequired
    }),
    defaultValue: DateUtils.evaluateDateProp,
    minDate: DateUtils.evaluateDateProp,
    maxDate: DateUtils.evaluateDateProp,
    locale: PropTypes.string,
    startMode: PropTypes.string,
    fixedMode: PropTypes.bool,
    returnFormat: PropTypes.string,
    floating: PropTypes.bool,
    closeOnClickOutside: PropTypes.bool, // used only with DatePickerInput
    className: PropTypes.string,
    style: PropTypes.object
  },

  mixins: [ ValueLinkMixin, formatMixin ],

  getDefaultProps() {
    return {
      startMode: 'day',
      className: '',
      style: {}
    };
  },

  getInitialState() {
    if (this.props.locale) {
      moment.locale(this.props.locale);
      if (process.env.NODE_ENV !== 'production' && moment.locale() !== this.props.locale) {
        console.warn(`Setting "${this.props.locale}" as locale failed. Did you import it correctly?`); // eslint-disable-line no-console
      }
    }
    return this.getStateFromProps(this.props);
  },

  getStateFromProps(_props) {
    const { value } = this.getValueLink(_props);
    const { defaultValue, startMode } = _props;
    const date = typeof value === 'string' ? this.parsePropDateString(value) : moment(value);
    const initialDate = typeof defaultValue === 'string' ? this.parsePropDateString(defaultValue) : moment(defaultValue);

    const visibleDate = value ? date.clone() : initialDate; // must be copy, otherwise they get linked
    return {
      date: value ? date.clone() : undefined,
      visibleDate,
      mode: startMode
    };
  },

  onChangeVisibleDate(date) {
    this.setState({ visibleDate: date });
  },

  onChangeSelectedDate(date) {
    this.setState({
      visibleDate: date.clone(), // must be copy, otherwise they get linked
      date
    }, () => this.getValueLink().requestChange(date.toDate()));
  },

  onChangeMode(mode) {
    setTimeout(() => this.setState({ mode }));
  },

  changeYear(year) {
    this.setState({ visibleDate: this.state.visibleDate.clone().year(year) });
  },

  changeMonth(month) {
    this.setState({ visibleDate: this.state.visibleDate.clone().month(month) });
  },

  getDayPicker() {
    return (
      <DayPicker
        changeMonth={this.changeMonth}
        date={this.state.date}
        visibleDate={this.state.visibleDate}
        minDate={this.props.minDate}
        maxDate={this.props.maxDate}
        onSelectDate={this.onChangeSelectedDate}
        onChangeMode={this.onChangeMode}
        mode={this.state.mode}
        fixedMode={this.props.fixedMode}
        className={this.props.className}
      />
    );
  },

  getMonthPicker() {
    return (
      <MonthPicker
        changeYear={this.changeYear}
        date={this.state.date}
        visibleDate={this.state.visibleDate}
        minDate={this.props.minDate}
        maxDate={this.props.maxDate}
        onSelectDate={this.onChangeSelectedDate}
        onChangeVisibleDate={this.onChangeVisibleDate}
        onChangeMode={this.onChangeMode}
        mode={this.state.mode}
        fixedMode={this.props.fixedMode}
        className={this.props.className}
      />
    );
  },

  getYearPicker() {
    return (
      <YearPicker
        changeYear={this.changeYear}
        date={this.state.date}
        visibleDate={this.state.visibleDate}
        minDate={this.props.minDate}
        maxDate={this.props.maxDate}
        onSelectDate={this.onChangeSelectedDate}
        onChangeVisibleDate={this.onChangeVisibleDate}
        onChangeMode={this.onChangeMode}
        mode={this.state.mode}
        fixedMode={this.props.fixedMode}
        className={this.props.className}
      />
    );
  },

  render() {
    let picker;
    switch (this.state.mode) {
      case 'day':
        picker = this.getDayPicker();
        break;

      case 'month':
        picker = this.getMonthPicker();
        break;

      case 'year':
        picker = this.getYearPicker();
        break;
    }

    return (
      <div
        className={cx('react-datepicker', this.props.className, { floating: this.props.floating } )}
        style={this.props.style}
      >
        {picker}
      </div>
    );
  },

  componentWillReceiveProps(nextProps) {
    if (this.getValueLink(nextProps).value !== this.getValueLink().value) {
      this.setState(this.getStateFromProps(nextProps));
    }
  }

});

export default DatePicker;


text:
<!DOCTYPE html>

    <title>Welcome/Karibu!! – </title>

    <meta charset="utf-8" />
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

<meta name="description" content="Well! I finally got around to putting this old website together. Welcome to my all things data journal.  Here, you can read posts about data and learn with me as I explore the exciting word of machine learning technologies and big data. I am passionate about exploring the root issues behind relevant problems, and then using data to help build innovative products or find impactful solutions for millions of people around the world to improve the way people work and think.  Let's learn together.

" />
<meta property="og:description" content="Well! I finally got around to putting this old website together. Welcome to my all things data journal.  Here, you can read posts about data and learn with me as I explore the exciting word of machine learning technologies and big data. I am passionate about exploring the root issues behind relevant problems, and then using data to help build innovative products or find impactful solutions for millions of people around the world to improve the way people work and think.  Let's learn together.

" />

<meta name="author" content="" />

<meta property="og:title" content="Welcome/Karibu!!" />
<meta property="twitter:title" content="Welcome/Karibu!!" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title=" - My background and education has given me a strong foundation for using data to answer interesting questions and communicate about technical topics with diverse audience." href="/feed.xml" />

My background and education has given me a strong foundation for using data to answer interesting questions and communicate about technical topics with diverse audience.

          /blog/
          /publications/
         /activities/
         /about/

Welcome/Karibu!!

Well! I finally got around to putting this old website together. Welcome to my all things data journal.  Here, you can read posts about data and learn with me as I explore the exciting word of machine learning technologies and big data. I am passionate about exploring the root issues behind relevant problems, and then using data to help build innovative products or find impactful solutions for millions of people around the world to improve the way people work and think.  Let's learn together.

Neat thing about it - powered by Jekyll and I can use Markdown to author my posts.
It actually is a lot easier than I thought it was going to be.

    Written on September 22, 2017

    Tags:


text:
<?php

declare(strict_types=1);

namespace ShlinkioTest\Shlink\Rest\Middleware\ShortUrl;

use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Shlinkio\Shlink\Core\ShortUrl\Model\Validation\ShortUrlInputFilter;
use Shlinkio\Shlink\Rest\Middleware\ShortUrl\DefaultShortCodesLengthMiddleware;

class DefaultShortCodesLengthMiddlewareTest extends TestCase
{
    private DefaultShortCodesLengthMiddleware $middleware;
    private MockObject & RequestHandlerInterface $handler;

    protected function setUp(): void
    {
        $this->handler = $this->createMock(RequestHandlerInterface::class);
        $this->middleware = new DefaultShortCodesLengthMiddleware(8);
    }

    /**
     * @test
     * @dataProvider provideBodies
     */
    public function defaultValueIsInjectedInBodyWhenNotProvided(array $body, int $expectedLength): void
    {
        $request = ServerRequestFactory::fromGlobals()->withParsedBody($body);
        $this->handler->expects($this->once())->method('handle')->with($this->callback(
            function (ServerRequestInterface $req) use ($expectedLength) {
                $parsedBody = (array) $req->getParsedBody();
                Assert::assertArrayHasKey(ShortUrlInputFilter::SHORT_CODE_LENGTH, $parsedBody);
                Assert::assertEquals($expectedLength, $parsedBody[ShortUrlInputFilter::SHORT_CODE_LENGTH]);

                return true;
            },
        ))->willReturn(new Response());

        $this->middleware->process($request, $this->handler);
    }

    public function provideBodies(): iterable
    {
        yield 'value provided' => [[ShortUrlInputFilter::SHORT_CODE_LENGTH => 6], 6];
        yield 'value not provided' => [[], 8];
    }
}


text:
CREATE TABLE SENDMAIL_QUEUE(
        ID BIGINT NOT NULL,
        SUBJECT VARCHAR(50),
	SENDER VARCHAR(200),
	RECEIVER VARCHAR(200),
	CC VARCHAR(200),
	BCC VARCHAR(200),
	CONTENT VARCHAR(65535),
	ATTACHMENT VARCHAR(200),
	DATA VARCHAR(65535),
	CREATE_TIME TIMESTAMP,
	STATUS VARCHAR(50),
	INFO VARCHAR(200),
	CONFIG_ID BIGINT,
	TEMPLATE_ID BIGINT,
	SCOPE_ID VARCHAR(50),
        CONSTRAINT PK_SENDMAIL_QUEUE PRIMARY KEY(ID),
        CONSTRAINT FK_SENDMAIL_QUEUE_CONFIG FOREIGN KEY(CONFIG_ID) REFERENCES SENDMAIL_CONFIG(ID),
	CONSTRAINT FK_SENDMAIL_QUEUE_TEMPLATE FOREIGN KEY(TEMPLATE_ID) REFERENCES SENDMAIL_TEMPLATE(ID)
);


text:
title: "Layout: Author Override"
author: Billy Rick
excerpt: "A post to test author overrides using a data file."
---

Sites that may have content authored from various individuals can be accommodated by using [data files](https://jekyllrb.com/docs/datafiles/).

To attribute an author to a post or page that is different from the site author specified in `_config.yml`:

**Step 1.** Create `_data/authors.yml` and add authors using the following format. Anything variables found under `author` in `_config.yml` can be used (e.g. `name`, `bio`, `avatar`, author `links`, etc.).

```yaml
# /_data/authors.yml

Billy Rick:
  name        : "Billy Rick"
  bio         : "What do you want, jewels? I am a very extravagant man."
  avatar      : "/assets/images/bio-photo-2.jpg"
  links:
    - label: "Email"
      icon: "fas fa-fw fa-envelope-square"
      url: "mailto:billyrick@rick.com"
    - label: "Website"
      icon: "fas fa-fw fa-link"
      url: "https://thewhip.com"
    - label: "Twitter"
      icon: "fab fa-fw fa-twitter-square"
      url: "https://twitter.com/extravagantman"

Cornelius Fiddlebone:
  name        : "Cornelius Fiddlebone"
  bio         : "I ordered what?"
  avatar      : "/assets/images/bio-photo.jpg"
  links:
    - label: "Email"
      icon: "fas fa-fw fa-envelope-square"
      url: "mailto:cornelius@thewhip.com"
    - label: "Twitter"
      icon: "fab fa-fw fa-twitter-square"
      url: "https://twitter.com/rhymeswithsackit"
```

**Step 2.** Assign one of the authors in `authors.yml` to a post or page you wish to override the `site.author` with.

Example: To assign `Billy Rick` as an author for a post the following YAML Front Matter would be applied:

```yaml
author: Billy Rick
```


text:
package com.njyb.gbdbase.service.alldb.convertdata;

import java.io.Serializable;

import com.njyb.gbdbase.model.alldb.commonrightlibrary.AllDBModel;
import com.njyb.gbdbase.model.datasearch.guatemala.GuatemalaImportModel;
/**
 * 危地马拉进口
 * @author WangBo
 * 2015年6月4日
 * GuatemalaIConvertModel.java
 */
public class GuatemalaIConvertModel extends AllDBModel implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 危地马拉数据
	 * @param guatemalaImportModel
	 * @param country
	 * @return
	 */
	public static GuatemalaIConvertModel getGuatemalaIConvertModel(GuatemalaImportModel guatemalaImportModel,String country) {
		GuatemalaIConvertModel allDBModel = new GuatemalaIConvertModel();
		allDBModel.setId(guatemalaImportModel.getGuatemalaImportId());
		allDBModel.setWeight(0);
		allDBModel.setQuantity(guatemalaImportModel.getQuantity());
		allDBModel.setDate(guatemalaImportModel.getDate());
		allDBModel.setCountNum(guatemalaImportModel.getQuantity());
		allDBModel.setCountry(country);
		allDBModel.setGoodsdescription(guatemalaImportModel.getGoodsDesc());
		allDBModel.setExporter(guatemalaImportModel.getExporter());
		allDBModel.setHscode("");
		allDBModel.setImporter(guatemalaImportModel.getImporter());
		allDBModel.setTotalprice(0);
		allDBModel.setUnitprice(0);
		return allDBModel;
	}
}


text:
package com.elfec.cobranza.model.enums;

/**
 * Define los distintos tipos de acciones de las transacciones
 * @author drodriguez
 *
 */
public enum TransactionAction {
	PAYMENT("COBRANZA"),
	ANNULMENT("ANULACION_COBRANZA");
	private String string;
	private TransactionAction(String string)
	{
		this.string = string;
	}

	@Override
	public String toString() {
        return string;
    }

	/**
	 * Obtiene la TransactionAction correspondiente a la cadena provista
	 * a ninguna accion definida
	 * @param actionAsString
	 * @return TransactionAction correspondiente a la cadena, null si la cadena no corresponde
	 */
	public static TransactionAction get(String actionAsString)
	{
		TransactionAction[] actions = TransactionAction.values();
		for (int i = 0; i < actions.length; i++) {
			if(actions[i].toString().equals(actionAsString))
				return actions[i];
		}
		return null;
	}
}


text:
ARAG AS24 PUSH API
==================

This API is used for policy creation for ARAG.

Getting started
---------------

This uses the KASKO push API and is a single request.

1) Make POST request to URL

Authentication
--------------

Authenticate your account when using the API by including your secret API :ref:`key <keys>` in the request. Your API keys carry many privileges, so be sure to keep them secret! Do not share your secret API keys in publicly accessible areas such GitHub, client-side code, and so forth.

Requests that require authentication will return ``404 Not Found``, instead of ``403 Forbidden``, in some places. This is to prevent the accidental leakage of sensitive data to unauthorized users.

Authentication to the API is performed via `HTTP Basic Auth <https://en.wikipedia.org/wiki/Basic_access_authentication>`_. Provide your API key as the basic auth username value. You do not need to provide a password.

If you need to authenticate via bearer auth (e.g., for a cross-origin request), use ``-H "Authorization: Bearer sk_test_SECRET_KEY"`` instead of ``-u sk_test_SECRET_KEY:``.

All API requests must be made over `HTTPS <https://en.wikipedia.org/wiki/HTTPS>`_. Calls made over plain HTTP will fail.

**Basic Authentication**

.. code:: rest

	curl -u sk_test_SECRET_KEY: https://push-api.kasko.io/

**Bearer Authentication**

.. code:: rest

	curl -H "Authorization: Bearer sk_test_SECRET_KEY" https://push-api.kasko.io/

Header
------

All requests must be in JSON and include ``Content-Type`` header.

.. code:: rest

	-H "Content-Type: application/json"

Create a Policy
---------------

Definition
~~~~~~~~~~
.. code:: bash

	POST https://push-api.kasko.io/

Parameters
~~~~~~~~~~

.. csv-table::
   :header: "Parameter", "required", "Type", "Description"
   :widths: 20, 20, 20, 80

   "variant_id", "yes", "``string``", "d2va8Owp4WRnkbMpEWDAmVoN1JejB5GE"
   "input", "yes", "``object``", "JSON - See Product Input"

Product Input
~~~~~~~~~~~~~

.. csv-table::
   :header: "Parameter", "required", "Type", "Description"
   :widths: 20, 20, 20, 80

   "first_name", "yes", "``string``", "Customer first name"
   "last_name", "yes", "``string``", "Customer last name"
   "email", "yes", "``string``", "Customer Email Address"
   "data", "yes", "``object``", "JSON - See Policy Data Input."

Policy Data Input
~~~~~~~~~~~~~~~~~

.. csv-table::
   :header: "Parameter", "required", "Type", "Description"
   :widths: 20, 20, 20, 80

   "start_date", "yes", "``string``", "Start date in `ISO 8601 <https://en.wikipedia.org/wiki/ISO_8601>` format (YYYY-MM-DD)"
   "vin", "yes", "``string``", Vehicle Identification Number."

Example Request
~~~~~~~~~~~~~~~

.. code:: bash

    curl https://push-api.kasko.io/ \
        -u <YOUR SECRET API KEY>: \
        -H "Content-Type: application/json" \
        -d '{
            "variant_id":"d2va8Owp4WRnkbMpEWDAmVoN1JejB5GE",
            "input":{
                "first_name":"Test",
                "last_name":"Person",
                "email":"test@person.com",
                "data":{
                    "start_date":"2017-02-13",
                    "vin":"12345"
                }
            }
        }'

Example Response Success
~~~~~~~~~~~~~~~~~~~~~~~~

Reference of created policy

response code 200

.. code:: javascript

	{
	  "reference": "97c3b16c-f2d1-11e6-88ad-59f2b961d2ab"
	}

Example Response Failure
~~~~~~~~~~~~~~~~~~~~~~~~

response code 400

.. code:: javascript

	{
	  "errorMessage": "Bad Request: The 'vin' field is required."
	}

If you have any questions please email us at ``techsupport@kasko.io``.


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=enum.AsyncSink.html">

Redirecting to enum.AsyncSink.html...


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Reflection.Metadata;

namespace Microsoft.CodeAnalysis.Emit
{
    public sealed class EmitDifferenceResult : EmitResult
    {
        public EmitBaseline? Baseline { get; }

        /// <summary>
        /// Handles of methods with sequence points that have been updated in this delta.
        /// </summary>
        public ImmutableArray<MethodDefinitionHandle> UpdatedMethods { get; }

        /// <summary>
        /// Handles of types that were changed (updated or inserted) in this delta.
        /// </summary>
        public ImmutableArray<TypeDefinitionHandle> ChangedTypes { get; }

        internal EmitDifferenceResult(bool success, ImmutableArray<Diagnostic> diagnostics, EmitBaseline? baseline, ImmutableArray<MethodDefinitionHandle> updatedMethods, ImmutableArray<TypeDefinitionHandle> changedTypes)
            : base(success, diagnostics)
        {
            Baseline = baseline;
            UpdatedMethods = updatedMethods;
            ChangedTypes = changedTypes;
        }
    }
}


text:
using ForumDEG.Interfaces;
using ForumDEG.Utils;
using ForumDEG.Models;
using ForumDEG.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using System.Diagnostics;

namespace ForumDEG.ViewModels {
    public class UserDetailViewModel : BaseViewModel{
        private readonly IPageService _pageService;
        private readonly Helpers.Administrator _administratorService;
        private readonly Helpers.Coordinator _coordinatorService;

        public int Id { get; set; }
        public string Name { get; set; }
        public string Registration { get; set; }
        public string Email { get; set; }
        public string Course { get; set; }
        public int ForumsPresent { get; set; }
        public bool IsAdministrator { get; set; }
        public bool IsCoordinator { get; set; }

        private bool _activityIndicator = false;
        public bool ActivityIndicator {
            get {
                return _activityIndicator;
            }
            set {
                if (_activityIndicator != value) {
                    _activityIndicator = value;

                    OnPropertyChanged("ActivityIndicator");
                }
            }
        }

        public ICommand EditCommand { get; private set; }
        public ICommand DeleteCommand { get; private set; }

        public bool IsCurrentUserAdmin => Helpers.Settings.IsUserAdmin;

        public UserDetailViewModel(IPageService PageService) {
            ActivityIndicator = false;
            _pageService = PageService;
            EditCommand = new Command(EditUser);
            DeleteCommand = new Command(DeleteUser);
            _administratorService = new Helpers.Administrator();
            _coordinatorService = new Helpers.Coordinator();
        }

        public void EditUser() {
            _pageService.PushAsync(new UserEditPage(Registration, IsCoordinator));
        }

        private async void DeleteUser() {
            //Administrator _toDeleteAdmin;
           // Coordinator _toDeleteCoord;
            //bool answer;

            if (IsAdministrator) {
                var answer = await _pageService.DisplayAlert("Deletar Usuário", "Tem certeza que deseja deletar esse usuário? Esta ação não poderá ser desfeita.", "Sim", "Não");
                Debug.WriteLine("Answer: " + answer);
                if (answer == true) {
                    ActivityIndicator = true;
                    if (await _administratorService.DeleteAdministratorAsync(Registration)) {
                        ActivityIndicator = false;
                        await _pageService.DisplayAlert("Usuário deletado", "O usuário foi excluído do sistema com sucesso.", null,"OK");
                        await _pageService.PopToRootAsync();
                    } else {
                        ActivityIndicator = false;
                        await _pageService.DisplayAlert("Erro!", "O usuário não pôde ser deletado, tente novamente.",null ,"OK");
                    }
                }
                      //LOCAL DATABASE//
                //_toDeleteAdmin = await AdministratorDatabase.getAdmDB.Get(Id);
                //answer = await _pageService.DisplayAlert("Deletar Administrador",
                //    "Tem certeza que deseja deletar o Administrador " + _toDeleteAdmin.Name + "?\nEsta ação não poderá ser desfeita.", "Sim", "Não");
                //if (answer == true) {
                //    await AdministratorDatabase.getAdmDB.Delete(_toDeleteAdmin);
                //    await _pageService.PopAsync();
                //} else {
                //    //do nothing
                //}
            } else {
                var answer = await _pageService.DisplayAlert("Deletar Usuário", "Tem certeza que deseja deletar esse usuário? Esta ação não poderá ser desfeita.", "Sim", "Não");
                Debug.WriteLine("Answer: " + answer);
                if (answer == true) {
                    ActivityIndicator = true;
                    if (await _coordinatorService.DeleteCoordinatorAsync(Registration)) {
                        ActivityIndicator = false;
                        await _pageService.PopAsync();
                        await _pageService.DisplayAlert("Usuário deletado", "O usuário foi excluído do sistema com sucesso.", null,"OK");
                        await _pageService.PopToRootAsync();
                    } else {
                        ActivityIndicator = false;
                        await _pageService.DisplayAlert("Erro!", "O usuário não pôde ser deletado, tente novamente.", null, "OK");
                    }
                }
                //LOCAL DATABASE//
                //_toDeleteCoord = await CoordinatorDatabase.getCoordinatorDB.Get(Id);
                //answer = await _pageService.DisplayAlert("Deletar Coordenador",
                //    "Tem certeza que deseja deletar o Coordenador " + _toDeleteCoord.Name + "?\nEsta ação não poderá ser desfeita.", "Sim", "Não");
                //if (answer == true) {
                //    await CoordinatorDatabase.getCoordinatorDB.Delete(_toDeleteCoord);
                //    await _pageService.PopAsync();
                //} else {
                //    //do nothing
                //}
            }
        }
    }
}


text:
package org.apache.tez.runtime.library.conf;

import java.io.IOException;
import java.util.Map;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.tez.common.TezJobConfig;
import org.apache.tez.common.TezUtils;
import org.apache.tez.runtime.library.common.ConfigUtils;
import org.apache.tez.runtime.library.input.ShuffledMergedInput;
import org.apache.tez.runtime.library.input.ShuffledMergedInputLegacy;

@InterfaceAudience.Public
@InterfaceStability.Evolving
public class ShuffledMergedInputConfiguration {

  /**
   * Configure parameters which are specific to the Input.
   */
  @InterfaceAudience.Private
  public static interface SpecificConfigurer<T> extends BaseConfigurer<T> {

    /**
     * Specifies whether the legacy version of this input should be used.
     * @return instance of the current builder
     */
    public T useLegacyInput();
    /**
     * Sets the buffer fraction, as a fraction of container size, to be used while fetching remote
     * data.
     *
     * @param shuffleBufferFraction fraction of container size
     * @return instance of the current builder
     */
    public T setShuffleBufferFraction(float shuffleBufferFraction);

    /**
     * Sets the buffer fraction, as a fraction of container size, to be used after the fetch and
     * merge are complete. This buffer is used to cache merged data and avoids writing it out to
     * disk.
     *
     * @param postMergeBufferFraction fraction of container size
     * @return instance of the current builder
     */
    public T setPostMergeBufferFraction(float postMergeBufferFraction);

    /**
     * Sets a size limit on the maximum segment size to be shuffled to disk. This is a fraction of
     * the shuffle buffer.
     *
     * @param maxSingleSegmentFraction fraction of memory determined by ShuffleBufferFraction
     * @return instance of the current builder
     */
    public T setMaxSingleMemorySegmentFraction(float maxSingleSegmentFraction);

    /**
     * Enable the memory to memory merger
     *
     * @return
     */
    public T enableMemToMemMerger(); // Not super useful until additional params are used.

    /**
     * Configure the point at which in memory segments will be merged. This is specified as a
     * fraction of the shuffle buffer.
     *
     * @param mergeFraction fraction of memory determined by ShuffleBufferFraction, which when
     *                      filled, will
     *                      trigger a merge
     * @return instance of the current builder
     */
    public T setMergeFraction(float mergeFraction);

    /**
     * Enable encrypted data transfer
     *
     * @return instance of the current builder
     */
    public T enableEncryptedTransfer();

    /**
     * Configure the combiner class
     *
     * @param combinerClassName the combiner class name
     * @param combinerConf configuration specific to the Combiner. This can be null
     * @return instance of the current builder
     */
    public T setCombiner(String combinerClassName, Configuration combinerConf);

  }

  @SuppressWarnings("rawtypes")
  @InterfaceAudience.Public
  @InterfaceStability.Evolving
  public static class SpecificBuilder<E extends HadoopKeyValuesBasedBaseConf.Builder> implements
      SpecificConfigurer<SpecificBuilder> {

    private final E edgeBuilder;
    private final ShuffledMergedInputConfiguration.Builder builder;

    @InterfaceAudience.Private
    SpecificBuilder(E edgeBuilder, ShuffledMergedInputConfiguration.Builder builder) {
      this.edgeBuilder = edgeBuilder;
      this.builder = builder;
    }

    public SpecificBuilder<E> useLegacyInput() {
      builder.useLegacyInput();
      return this;
    }

    @Override
    public SpecificBuilder<E> setShuffleBufferFraction(float shuffleBufferFraction) {
      builder.setShuffleBufferFraction(shuffleBufferFraction);
      return this;
    }

    @Override
    public SpecificBuilder<E> setPostMergeBufferFraction(float postMergeBufferFraction) {
      builder.setPostMergeBufferFraction(postMergeBufferFraction);
      return this;
    }

    @Override
    public SpecificBuilder<E> setMaxSingleMemorySegmentFraction(float maxSingleSegmentFraction) {
      builder.setMaxSingleMemorySegmentFraction(maxSingleSegmentFraction);
      return this;
    }

    @Override
    public SpecificBuilder<E> enableMemToMemMerger() {
      builder.enableMemToMemMerger();
      return this;
    }

    @Override
    public SpecificBuilder<E> setMergeFraction(float mergeFraction) {
      builder.setMergeFraction(mergeFraction);
      return this;
    }

    @Override
    public SpecificBuilder<E> enableEncryptedTransfer() {
      builder.enableEncryptedTransfer();
      return this;
    }

    @Override
    public SpecificBuilder<E> setCombiner(String combinerClassName, Configuration combinerConf) {
      builder.setCombiner(combinerClassName, combinerConf);
      return this;
    }

    @Override
    public SpecificBuilder setAdditionalConfiguration(String key, String value) {
      builder.setAdditionalConfiguration(key, value);
      return this;
    }

    @Override
    public SpecificBuilder setAdditionalConfiguration(Map<String, String> confMap) {
      builder.setAdditionalConfiguration(confMap);
      return this;
    }

    @Override
    public SpecificBuilder setFromConfiguration(Configuration conf) {
      builder.setFromConfiguration(conf);
      return this;
    }

    public E done() {
      return edgeBuilder;
    }

  }

  @InterfaceAudience.Private
  @VisibleForTesting
  Configuration conf;

  private String inputClassName;

  @InterfaceAudience.Private
  @VisibleForTesting
  ShuffledMergedInputConfiguration() {
  }

  private ShuffledMergedInputConfiguration(Configuration conf, boolean useLegacyInput) {
    this.conf = conf;
    if (useLegacyInput) {
      inputClassName = ShuffledMergedInputLegacy.class.getName();
    } else {
      inputClassName = ShuffledMergedInput.class.getName();
    }
  }

  /**
   * Get a byte array representation of the configuration
   * @return a byte array which can be used as the payload
   */
  public byte[] toByteArray() {
    try {
      return TezUtils.createUserPayloadFromConf(conf);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public void fromByteArray(byte[] payload) {
    try {
      this.conf = TezUtils.createConfFromUserPayload(payload);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public String getInputClassName() {
    return inputClassName;
  }

  public static Builder newBuilder(String keyClass, String valueClass) {
    return new Builder(keyClass, valueClass);
  }

  @InterfaceAudience.Public
  @InterfaceStability.Evolving
  public static class Builder implements SpecificConfigurer<Builder> {

    private final Configuration conf = new Configuration(false);
    private boolean useLegacyInput = false;

    /**
     * Create a configuration builder for {@link org.apache.tez.runtime.library.input.ShuffledMergedInput}
     *
     * @param keyClassName         the key class name
     * @param valueClassName       the value class name
     */
    @InterfaceAudience.Private
    Builder(String keyClassName, String valueClassName) {
      this();
      Preconditions.checkNotNull(keyClassName, "Key class name cannot be null");
      Preconditions.checkNotNull(valueClassName, "Value class name cannot be null");
      setKeyClassName(keyClassName);
      setValueClassName(valueClassName);
    }

    @InterfaceAudience.Private
    Builder() {
      Map<String, String> tezDefaults = ConfigUtils
          .extractConfigurationMap(TezJobConfig.getTezRuntimeConfigDefaults(),
              ShuffledMergedInput.getConfigurationKeySet());
      ConfigUtils.addConfigMapToConfiguration(this.conf, tezDefaults);
      ConfigUtils.addConfigMapToConfiguration(this.conf, TezJobConfig.getOtherConfigDefaults());
    }

    @InterfaceAudience.Private
    Builder setKeyClassName(String keyClassName) {
      Preconditions.checkNotNull(keyClassName, "Key class name cannot be null");
      this.conf.set(TezJobConfig.TEZ_RUNTIME_KEY_CLASS, keyClassName);
      return this;
    }

    @InterfaceAudience.Private
    Builder setValueClassName(String valueClassName) {
      Preconditions.checkNotNull(valueClassName, "Value class name cannot be null");
      this.conf.set(TezJobConfig.TEZ_RUNTIME_VALUE_CLASS, valueClassName);
      return this;
    }

    public Builder useLegacyInput() {
      this.useLegacyInput = true;
      return this;
    }

    @Override
    public Builder setShuffleBufferFraction(float shuffleBufferFraction) {
      this.conf
          .setFloat(TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT, shuffleBufferFraction);
      return this;
    }

    @Override
    public Builder setPostMergeBufferFraction(float postMergeBufferFraction) {
      this.conf.setFloat(TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT, postMergeBufferFraction);
      return this;
    }

    @Override
    public Builder setMaxSingleMemorySegmentFraction(float maxSingleSegmentFraction) {
      this.conf.setFloat(TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMORY_LIMIT_PERCENT,
          maxSingleSegmentFraction);
      return this;
    }

    @Override
    public Builder enableMemToMemMerger() {
      this.conf.setBoolean(TezJobConfig.TEZ_RUNTIME_SHUFFLE_ENABLE_MEMTOMEM, true);
      return this;
    }

    @Override
    public Builder setMergeFraction(float mergeFraction) {
      this.conf.setFloat(TezJobConfig.TEZ_RUNTIME_SHUFFLE_MERGE_PERCENT, mergeFraction);
      return this;
    }

    @Override
    public Builder enableEncryptedTransfer() {
      this.conf.setBoolean(TezJobConfig.TEZ_RUNTIME_SHUFFLE_ENABLE_SSL, true);
      return this;
    }

    @Override
    public Builder setCombiner(String combinerClassName, Configuration combinerConf) {
      this.conf.set(TezJobConfig.TEZ_RUNTIME_COMBINER_CLASS, combinerClassName);
      if (combinerConf != null) {
        // Merging the confs for now. Change to be specific in the future.
        ConfigUtils.mergeConfsWithExclusions(this.conf, combinerConf,
            TezJobConfig.getRuntimeConfigKeySet());
      }
      return this;
    }

    /**
     * Set the key comparator class
     *
     * @param comparatorClassName the key comparator class name
     * @return instance of the current builder
     */
    public Builder setKeyComparatorClass(String comparatorClassName) {
      this.conf.set(TezJobConfig.TEZ_RUNTIME_KEY_COMPARATOR_CLASS,
          comparatorClassName);
      return this;
    }

    @Override
    public Builder setAdditionalConfiguration(String key, String value) {
      Preconditions.checkNotNull(key, "Key cannot be null");
      if (ConfigUtils.doesKeyQualify(key,
          Lists.newArrayList(ShuffledMergedInput.getConfigurationKeySet(),
              TezJobConfig.getRuntimeAdditionalConfigKeySet()),
          TezJobConfig.getAllowedPrefixes())) {
        if (value == null) {
          this.conf.unset(key);
        } else {
          this.conf.set(key, value);
        }
      }
      return this;
    }

    @Override
    public Builder setAdditionalConfiguration(Map<String, String> confMap) {
      Preconditions.checkNotNull(confMap, "ConfMap cannot be null");
      Map<String, String> map = ConfigUtils.extractConfigurationMap(confMap,
          Lists.newArrayList(ShuffledMergedInput.getConfigurationKeySet(),
              TezJobConfig.getRuntimeAdditionalConfigKeySet()), TezJobConfig.getAllowedPrefixes());
      ConfigUtils.addConfigMapToConfiguration(this.conf, map);
      return this;
    }

    @Override
    public Builder setFromConfiguration(Configuration conf) {
      // Maybe ensure this is the first call ? Otherwise this can end up overriding other parameters
      Preconditions.checkArgument(conf != null, "Configuration cannot be null");
      Map<String, String> map = ConfigUtils.extractConfigurationMap(conf,
          Lists.newArrayList(ShuffledMergedInput.getConfigurationKeySet(),
              TezJobConfig.getRuntimeAdditionalConfigKeySet()), TezJobConfig.getAllowedPrefixes());
      ConfigUtils.addConfigMapToConfiguration(this.conf, map);
      return this;
    }

    public Builder enableCompression(String compressionCodec) {
      this.conf.setBoolean(TezJobConfig.TEZ_RUNTIME_COMPRESS, true);
      if (compressionCodec != null) {
        this.conf
            .set(TezJobConfig.TEZ_RUNTIME_COMPRESS_CODEC, compressionCodec);
      }
      return this;
    }

    /**
     * Create the actual configuration instance.
     *
     * @return an instance of the Configuration
     */
    public ShuffledMergedInputConfiguration build() {
      return new ShuffledMergedInputConfiguration(this.conf, this.useLegacyInput);
    }
  }

}


text:
import nova.conf
from nova.tests.functional.api_sample_tests import test_servers

CONF = nova.conf.CONF

class DeferredDeleteSampleJsonTests(test_servers.ServersSampleBase):
    extension_name = "os-deferred-delete"

    def _get_flags(self):
        f = super(DeferredDeleteSampleJsonTests, self)._get_flags()
        f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
        f['osapi_compute_extension'].append(
            'nova.api.openstack.compute.contrib.deferred_delete.'
            'Deferred_delete')
        return f

    def setUp(self):
        super(DeferredDeleteSampleJsonTests, self).setUp()
        self.flags(reclaim_instance_interval=1)

    def test_restore(self):
        uuid = self._post_server()
        self._do_delete('servers/%s' % uuid)

        response = self._do_post('servers/%s/action' % uuid,
                                 'restore-post-req', {})
        self.assertEqual(202, response.status_code)
        self.assertEqual('', response.content)

    def test_force_delete(self):
        uuid = self._post_server()
        self._do_delete('servers/%s' % uuid)

        response = self._do_post('servers/%s/action' % uuid,
                                 'force-delete-post-req', {})
        self.assertEqual(202, response.status_code)
        self.assertEqual('', response.content)


text:
package net.jworkflow.kernel.interfaces;

import java.util.function.Consumer;

public interface WorkflowBuilderConsumer<TData> extends Consumer<WorkflowBuilder<TData>> {

}


text:
package scalangine.states

import scalangine.entities.Entity
import scalangine.entities.Player
import scalangine.engine.GameRunner
import scalangine.entities.SplashItem
import scalangine.engine.StateGameRunner
import scalangine.entities.Background

class FlashSampleState(id: Int) extends GameState(id: Int) {

	var entities: List[Entity] = Nil
	var timer: Long = 0

	override def init(gameRunner: GameRunner) {
	  entities = new Background :: new SplashItem("/home/justin/Pictures/spritesheets/brickwork.png", "Wacky Adventures") :: Nil
	  entities(0).init(0, 0)
	  entities(1).init(300, 300)
	}

	override def update(gameRunner: GameRunner, delta: Long) {
	  entities.foreach(x => x.update(gameRunner, delta))
	  timer += delta
	  if(timer > 10000) {
	    gameRunner match {
	      case sgr: StateGameRunner => sgr.nextGameState = Some(2)
	    }
	  }
	}

	override def draw(gameRunner: GameRunner) {
	  entities.foreach(x => x.draw(gameRunner))
	}
}


text:
import json
from typing import Any
from urllib.error import URLError
from urllib.request import Request, urlopen

from libqtile.log_utils import logger
from libqtile.widget import base

try:
    import xmltodict

    def xmlparse(body):
        return xmltodict.parse(body)

except ImportError:
    # TODO: we could implement a similar parser by hand, but i'm lazy, so let's
    # punt for now
    def xmlparse(body):
        raise Exception("no xmltodict library")

class GenPollText(base.ThreadPoolText):
    """A generic text widget that polls using poll function to get the text"""

    defaults = [
        ("func", None, "Poll Function"),
    ]

    def __init__(self, **config):
        base.ThreadPoolText.__init__(self, "", **config)
        self.add_defaults(GenPollText.defaults)

    def poll(self):
        if not self.func:
            return "You need a poll function"
        return self.func()

class GenPollUrl(base.ThreadPoolText):
    """A generic text widget that polls an url and parses it using parse function"""

    defaults = [
        ("url", None, "Url"),
        ("data", None, "Post Data"),
        ("parse", None, "Parse Function"),
        ("json", True, "Is Json?"),
        ("user_agent", "Qtile", "Set the user agent"),
        ("headers", {}, "Extra Headers"),
        ("xml", False, "Is XML?"),
    ]  # type: list[tuple[str, Any, str]]

    def __init__(self, **config):
        base.ThreadPoolText.__init__(self, "", **config)
        self.add_defaults(GenPollUrl.defaults)

        self.headers["User-agent"] = self.user_agent
        if self.json:
            self.headers["Content-Type"] = "application/json"

        if self.data and not isinstance(self.data, str):
            self.data = json.dumps(self.data).encode()

    def fetch(self):
        req = Request(self.url, self.data, self.headers)
        res = urlopen(req)
        charset = res.headers.get_content_charset()

        body = res.read()
        if charset:
            body = body.decode(charset)

        if self.json:
            body = json.loads(body)

        if self.xml:
            body = xmlparse(body)
        return body

    def poll(self):
        if not self.parse or not self.url:
            return "Invalid config"

        try:
            body = self.fetch()
        except URLError:
            return "No network"

        try:
            text = self.parse(body)
        except Exception:
            logger.exception("got exception polling widget")
            text = "Can't parse"

        return text


text:
package org.specs2.exter.matcher

import org.specs2.matcher.{Expectable, Matcher}
import org.specs2.specification.SpecificationStructure

trait ExterSeq { self: SpecificationStructure =>

  private def seqToEnglish[A](seq: Seq[A]) = {
    seq.map(x => s"'$x'")
      .mkString(", ")
      .reverse
      .replaceFirst(" ,", " and ".reverse)
      .reverse
  }

  /** Assert that a given sequence contains all of the listed elements, regardless of order. */
  def containAll[A](values: A*) = new Matcher[Seq[A]] {
    def apply[S <: Seq[A]](ex: Expectable[S]) = {
      val subject = ex.value
      val notFound = values.filter(!subject.contains(_))

      result(
        notFound.length == 0,
        s"$subject contained ${seqToEnglish(values)}",
        s"$subject does not contain ${seqToEnglish(notFound)}",
        ex
      )
    }
  }

  /** Assert that a given sequence contains all and no more of the listed elements, regardless of order. */
  def containExactly[A](values: A*) = new Matcher[Seq[A]] {
    def apply[S <: Seq[A]](ex: Expectable[S]) = {
      val subject = ex.value
      val notFound = values.filter(!subject.contains(_))

      lazy val diff = subject.toSet.diff(values.toSet).toSeq
      lazy val failMessage =
        if (notFound.length == 0) s"$subject had extra values ${seqToEnglish(diff)}"
        else  s"$subject does not contain ${seqToEnglish(notFound)}"

      result(
        subject.length == values.length && notFound.length == 0,
        s"$subject contained exactly ${seqToEnglish(values)}",
        failMessage,
        ex
      )
    }
  }

  /** Assert that at least one of the listed elements is within the given sequence */
  def containSome[A](values: A*) = new Matcher[Seq[A]] {
    def apply[S <: Seq[A]](ex: Expectable[S]) = {
      val subject = ex.value
      val found = values.filter(subject.contains)

      result(
        found.length > 0,
        s"${seqToEnglish(found)} found in $subject",
        s"None of the expected values found (${seqToEnglish(values)}}) in $subject",
        ex
      )
    }
  }

}


text:
/*
 *  Nano River Technologies viperboard driver
 *
 *  This is the core driver for the viperboard. There are cell drivers
 *  available for I2C, ADC and both GPIOs. SPI is not yet supported.
 *  The drivers do not support all features the board exposes. See user
 *  manual of the viperboard.
 *
 *  (C) 2012 by Lemonage GmbH
 *  Author: Lars Poeschel <poeschel@lemonage.de>
 *  All rights reserved.
 *
 *  This program is free software; you can redistribute  it and/or modify it
 *  under  the terms of  the GNU General  Public License as published by the
 *  Free Software Foundation;  either version 2 of the  License, or (at your
 *  option) any later version.
 *
 */

#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/mutex.h>

#include <linux/mfd/core.h>
#include <linux/mfd/viperboard.h>

#include <linux/usb.h>

static const struct usb_device_id vprbrd_table[] = {
	{ USB_DEVICE(0x2058, 0x1005) },   /* Nano River Technologies */
	{ }                               /* Terminating entry */
};

MODULE_DEVICE_TABLE(usb, vprbrd_table);

static const struct mfd_cell vprbrd_devs[] = {
	{
		.name = "viperboard-gpio",
	},
	{
		.name = "viperboard-i2c",
	},
	{
		.name = "viperboard-adc",
	},
};

static int vprbrd_probe(struct usb_interface *interface,
			      const struct usb_device_id *id)
{
	struct vprbrd *vb;

	u16 version = 0;
	int pipe, ret;

	/* allocate memory for our device state and initialize it */
	vb = kzalloc(sizeof(*vb), GFP_KERNEL);
	if (vb == NULL) {
		dev_err(&interface->dev, "Out of memory\n");
		return -ENOMEM;
	}

	mutex_init(&vb->lock);

	vb->usb_dev = usb_get_dev(interface_to_usbdev(interface));

	/* save our data pointer in this interface device */
	usb_set_intfdata(interface, vb);
	dev_set_drvdata(&vb->pdev.dev, vb);

	/* get version information, major first, minor then */
	pipe = usb_rcvctrlpipe(vb->usb_dev, 0);
	ret = usb_control_msg(vb->usb_dev, pipe, VPRBRD_USB_REQUEST_MAJOR,
		VPRBRD_USB_TYPE_IN, 0x0000, 0x0000, vb->buf, 1,
		VPRBRD_USB_TIMEOUT_MS);
	if (ret == 1)
		version = vb->buf[0];

	ret = usb_control_msg(vb->usb_dev, pipe, VPRBRD_USB_REQUEST_MINOR,
		VPRBRD_USB_TYPE_IN, 0x0000, 0x0000, vb->buf, 1,
		VPRBRD_USB_TIMEOUT_MS);
	if (ret == 1) {
		version <<= 8;
		version = version | vb->buf[0];
	}

	dev_info(&interface->dev,
		 "version %x.%02x found at bus %03d address %03d\n",
		 version >> 8, version & 0xff,
		 vb->usb_dev->bus->busnum, vb->usb_dev->devnum);

	ret = mfd_add_devices(&interface->dev, -1, vprbrd_devs,
				ARRAY_SIZE(vprbrd_devs), NULL, 0, NULL);
	if (ret != 0) {
		dev_err(&interface->dev, "Failed to add mfd devices to core.");
		goto error;
	}

	return 0;

error:
	if (vb) {
		usb_put_dev(vb->usb_dev);
		kfree(vb);
	}

	return ret;
}

static void vprbrd_disconnect(struct usb_interface *interface)
{
	struct vprbrd *vb = usb_get_intfdata(interface);

	mfd_remove_devices(&interface->dev);
	usb_set_intfdata(interface, NULL);
	usb_put_dev(vb->usb_dev);
	kfree(vb);

	dev_dbg(&interface->dev, "disconnected\n");
}

static struct usb_driver vprbrd_driver = {
	.name		= "viperboard",
	.probe		= vprbrd_probe,
	.disconnect	= vprbrd_disconnect,
	.id_table	= vprbrd_table,
};

module_usb_driver(vprbrd_driver);

MODULE_DESCRIPTION("Nano River Technologies viperboard mfd core driver");
MODULE_AUTHOR("Lars Poeschel <poeschel@lemonage.de>");
MODULE_LICENSE("GPL");


text:
using FilterLists.Directory.Domain.Aggregates.FilterLists;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Change = FilterLists.Directory.Infrastructure.Persistence.Queries.Entities.Change;

namespace FilterLists.Directory.Infrastructure.Persistence.Commands.EntityTypeConfigurations;

internal class FilterListChangeTypeConfiguration : IEntityTypeConfiguration<FilterListChange>
{
    public virtual void Configure(EntityTypeBuilder<FilterListChange> builder)
    {
        builder.Property<long>(nameof(Change.FilterListId));
        builder.Property(c => c.Before)
            .HasColumnType("jsonb");
        builder.Property(c => c.After)
            .HasColumnType("jsonb");
    }
}


text:
<?php
$strTableName="evusers";
$_SESSION["OwnerID"] = $_SESSION["_".$strTableName."_OwnerID"];

$strOriginalTableName="evusers";

$gstrOrderBy="";
if(strlen($gstrOrderBy) && strtolower(substr($gstrOrderBy,0,8))!="order by")
	$gstrOrderBy="order by ".$gstrOrderBy;

// alias for 'SQLQuery' object
$gSettings = new ProjectSettings("evusers");
$gQuery = $gSettings->getSQLQuery();
$eventObj = &$tableEvents["evusers"];

$reportCaseSensitiveGroupFields = false;

$gstrSQL = $gQuery->gSQLWhere("");

?>


text:
package org.sittingbull.gt.util;

import java.text.DecimalFormat;

/*
 * Author: Ahmet Karahan
 */

/*
 * Reference:
 * 	[1] An Extension of Wilkinson's Algorithm for positioning Tick Labels on Axes
 * 		 				(Justin Talbot, Sharon Lin, Pat Hanrahan)
 */
public class XWilkinson {

	private boolean loose = false;
	public void setLooseFlag(boolean value) {
		loose = value;
		nice.reset();
	}

//	private double w[] = {0.2, 0.25, 0.5, 0.05};
	private double w[] = {0.25, 0.2, 0.5, 0.05};
	private double w(double s, double c, double d, double l) {
		return w[0]*s + w[1]*c + w[2]*d + w[3]*l;
	}
	public void changeW(double[] w) {
		this.w = w;
		nice.reset();
	}

	private NiceStepSizeGenerator.NiceStep n;
	public NiceStepSizeGenerator nice;
	public XWilkinson(NiceStepSizeGenerator nice) {
		this.nice = nice;
	}

	/*
	 * a mod b for float numbers (reminder of a/b)
	 */
	private double flooredMod(double a, double n) {
		return a-n*Math.floor(a/n);
	}

	/*
	 * a conditional eps (should work with very small scales without limitation)
	 */
/*	private double eps(double step) {
		double power = nice.logB(step);
		power -= ((double) Double.MAX_EXPONENT - power > 10) ? 10 : Double.MAX_EXPONENT;
		return Math.pow(nice.base, power);
	}*/

	private double v(double min, double max, double step) {
//		double eps = eps(step);
//		double eps = Math.pow(nice.base, -10);
		return (flooredMod(min, step) < MachineEpsilon.doubleValue() && min<=0 && max>=0) ? 1 : 0;
	}

	private double simplicity(double min, double max, double step) {
	    if(nice.Q.length>1)
	    	return 1 - (double)n.i/(nice.Q.length-1) - n.j + v(min, max, step);
	    else
	    	return 1 - n.j + v(min, max, step);
	}

	private double simplicity_max() {
		if(nice.Q.length>1)
			return 1 - (double)n.i/(nice.Q.length-1) - n.j + 1.0;
		 else
			 return 1 - n.j + 1.0;
	}

	private double coverage(double dmin, double dmax, double lmin, double lmax) {
		double a = dmax-lmax;
		double b = dmin-lmin;
		double c = 0.1*(dmax-dmin);
		return 1 - 0.5 * ((a*a+b*b)/(c*c));
	}

	private double coverage_max(double dmin, double dmax, double span) {
		double range = dmax-dmin;
		if(span > range) {
			double half = (span-range)/2;
			double r = 0.1*range;
			return 1 - half*half/(r*r);
		} else
			return 1.0;
	}

	/*
	 *
	 * @param k		number of labels
	 * @param m		number of desired labels
	 * @param dmin	data range minimum
	 * @param dmax	data range maximum
	 * @param lmin	label range minimum
	 * @param lmax	label range maximum
	 * @return		density
	 *
	 * k-1 number of intervals between labels
	 * m-1 number of intervals between desired number of labels
	 * r   label interval length/label range
	 * rt  desired label interval length/actual range
	 */
	private double density(int k, int m, double dmin, double dmax, double lmin, double lmax) {
		double r = (k-1)/(lmax-lmin);
		double rt = (m-1)/(Math.max(lmax, dmax)-Math.min(lmin, dmin));
		return 2-Math.max(r/rt, rt/r);   // return 1-Math.max(r/rt, rt/r); (paper is wrong)
	}

	private double density_max(int k, int m) {
		if(k >= m)
			return 2-(k-1)/(m-1);        // return 2-(k-1)/(m-1); (paper is wrong)
		else
			return 1;
	}

	private double legibility(double min, double max, double step) {
		return 1; // Later more
	}

	public class Label {
		public double min, max, step, score;
		public String toString() {
			DecimalFormat df = new DecimalFormat("00.00");
			String s = "(Score: " + df.format(score) + ") ";
			for(double x=min; x<=max; x=x+step) {
				s += df.format(x) + "\t";
			}
			return s;
		}
        public java.util.List<Double> toList() {
          java.util.ArrayList l = new java.util.ArrayList();
          for(double x=min; x<=max; x+=step) {
            l.add(x);
          }
          return l;
        }
	}

	/**
	 *
	 * @param dmin  data range min
	 * @param dmax  data range max
	 * @param m     desired number of labels
	 * @return      XWilkinson.Label
	 */
	public Label search(double dmin, double dmax, int m) {
		Label best = new Label();
		double bestScore = -2;
		double sm, dm, cm, delta;
		while(true) {
			n = nice.next();
			sm = simplicity_max();
			if(w(sm, 1, 1, 1) < bestScore)
				break;
			for(int k=2;;k++) {
				dm = density_max(k, m);
				if(w(sm, 1, dm, 1) < bestScore)
					break;
				delta = (dmax-dmin)/(k+1)/n.j/nice.Q[n.i];
				double z = Math.ceil(nice.logB(delta));
				while(true) {
					double step = n.j*nice.Q[n.i]*Math.pow(nice.base, z);
					cm = coverage_max(dmin, dmax, step*(k-1));
					if(w(sm,cm,dm,1) < bestScore)
						break;
					double min_start = (Math.floor(dmax/step) - (k-1)) * n.j;
					double max_start = Math.ceil(dmin/step) * n.j;
					if(min_start > max_start) {
						z = z+1;
						continue;
					}
					for(double start = min_start; start<=max_start; start++) {
						double lmin = start * step/n.j;
						double lmax = lmin + step*(k-1);
						double lstep = step;
						double c = coverage(dmin, dmax, lmin, lmax);
						double s = simplicity(lmin, lmax, lstep);
						double d = density(k, m, dmin, dmax, lmin, lmax);
						double l = legibility(lmin, lmax, lstep);
						double score = w(s, c, d, l);

						if(score > bestScore && (!loose || (lmin <= dmin && lmax >= dmax))) {
							best.min = lmin; best.max = lmax; best.step = lstep; best.score = score;
							bestScore = score;
						}
					}
					z = z+1;
				}
			}
		}
		nice.reset();
		return best;
	}
}


text:
#include <aws/resourcegroupstaggingapi/model/GetComplianceSummaryRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ResourceGroupsTaggingAPI::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetComplianceSummaryRequest::GetComplianceSummaryRequest() :
    m_targetIdFiltersHasBeenSet(false),
    m_regionFiltersHasBeenSet(false),
    m_resourceTypeFiltersHasBeenSet(false),
    m_tagKeyFiltersHasBeenSet(false),
    m_groupByHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_paginationTokenHasBeenSet(false)
{
}

Aws::String GetComplianceSummaryRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_targetIdFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> targetIdFiltersJsonList(m_targetIdFilters.size());
   for(unsigned targetIdFiltersIndex = 0; targetIdFiltersIndex < targetIdFiltersJsonList.GetLength(); ++targetIdFiltersIndex)
   {
     targetIdFiltersJsonList[targetIdFiltersIndex].AsString(m_targetIdFilters[targetIdFiltersIndex]);
   }
   payload.WithArray("TargetIdFilters", std::move(targetIdFiltersJsonList));

  }

  if(m_regionFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> regionFiltersJsonList(m_regionFilters.size());
   for(unsigned regionFiltersIndex = 0; regionFiltersIndex < regionFiltersJsonList.GetLength(); ++regionFiltersIndex)
   {
     regionFiltersJsonList[regionFiltersIndex].AsString(m_regionFilters[regionFiltersIndex]);
   }
   payload.WithArray("RegionFilters", std::move(regionFiltersJsonList));

  }

  if(m_resourceTypeFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> resourceTypeFiltersJsonList(m_resourceTypeFilters.size());
   for(unsigned resourceTypeFiltersIndex = 0; resourceTypeFiltersIndex < resourceTypeFiltersJsonList.GetLength(); ++resourceTypeFiltersIndex)
   {
     resourceTypeFiltersJsonList[resourceTypeFiltersIndex].AsString(m_resourceTypeFilters[resourceTypeFiltersIndex]);
   }
   payload.WithArray("ResourceTypeFilters", std::move(resourceTypeFiltersJsonList));

  }

  if(m_tagKeyFiltersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> tagKeyFiltersJsonList(m_tagKeyFilters.size());
   for(unsigned tagKeyFiltersIndex = 0; tagKeyFiltersIndex < tagKeyFiltersJsonList.GetLength(); ++tagKeyFiltersIndex)
   {
     tagKeyFiltersJsonList[tagKeyFiltersIndex].AsString(m_tagKeyFilters[tagKeyFiltersIndex]);
   }
   payload.WithArray("TagKeyFilters", std::move(tagKeyFiltersJsonList));

  }

  if(m_groupByHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> groupByJsonList(m_groupBy.size());
   for(unsigned groupByIndex = 0; groupByIndex < groupByJsonList.GetLength(); ++groupByIndex)
   {
     groupByJsonList[groupByIndex].AsString(GroupByAttributeMapper::GetNameForGroupByAttribute(m_groupBy[groupByIndex]));
   }
   payload.WithArray("GroupBy", std::move(groupByJsonList));

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  if(m_paginationTokenHasBeenSet)
  {
   payload.WithString("PaginationToken", m_paginationToken);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetComplianceSummaryRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ResourceGroupsTaggingAPI_20170126.GetComplianceSummary"));
  return headers;

}


text:
#include "stinger.h"
#include "xml_support.h"

#define VTX(v) stinger_vertices_vertex_get(vertices, v)

inline void
stinger_vertex_to_xml(const stinger_vertices_t * vertices, vindex_t v, FILE * out, int64_t indent_level)
{
  const stinger_vertex_t * vout = VTX(v);

  XML_INIT(out, indent_level);
  XML_TAG_START(vertex);
  XML_ATTRIBUTE_VTYPE(type, vout->type);
  XML_ATTRIBUTE_VWEIGHT(weight, vout->weight);
  XML_ATTRIBUTE_INT64(inDegree, vout->inDegree);
  XML_ATTRIBUTE_INT64(outDegree, vout->outDegree);
  XML_TAG_END();
  XML_TAG_START(edges);
  XML_TAG_END();
  XML_TAG_CLOSE(edges);
#if defined(STINGER_VERTEX_KEY_VALUE_STORE)
  /* TODO attributes */
#endif
  XML_TAG_CLOSE(vertex);
  XML_END();
}


text:
set -o errexit
set -o nounset
set -o pipefail

OS_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${OS_ROOT}/hack/util.sh"
source "${OS_ROOT}/hack/common.sh"
os::log::install_errexit

ensure_ginkgo_or_die
ensure_iptables_or_die

os::build::setup_env
go test -c ./test/extended -o ${OS_OUTPUT_BINPATH}/extended.test

function cleanup()
{
  out=$?
  cleanup_openshift
  echo "[INFO] Exiting"
  exit $out
}

echo "[INFO] Starting 'images' extended tests"

trap "exit" INT TERM
trap "cleanup" EXIT

export TMPDIR="${TMPDIR:-"/tmp"}"
export BASETMPDIR="${TMPDIR}/openshift-extended-tests/images"
setup_env_vars
reset_tmp_dir
configure_os_server
start_os_server

install_registry
wait_for_registry

echo "[INFO] Creating image streams"
oc create -n openshift -f examples/image-streams/image-streams-centos7.json --config="${ADMIN_KUBECONFIG}"

# Run the tests
pushd ${OS_ROOT}/test/extended >/dev/null
export KUBECONFIG="${ADMIN_KUBECONFIG}"
export EXTENDED_TEST_PATH="${OS_ROOT}/test/extended"
TMPDIR=${BASETMPDIR} ginkgo -progress -stream -v -p ${OS_OUTPUT_BINPATH}/extended.test "$@"
popd >/dev/null


text:
//
//  CollectionDemo5Cell.h
//  STHelperKit
//
//  Created by ST on 16/9/5.
//  Copyright © 2016年 沈兆良. All rights reserved.
//

#import <UIKit/UIKit.h>

static NSString *CollectionDemo5CellId = @"CollectionDemo5CellId";

@interface CollectionDemo5Cell : UICollectionViewCell
/** 1. */
@property(nonatomic, strong)NSString *text;
@end


text:
function [phi,normal,d,xA,xB,idxA,idxB,mu,n,D,dn,dD] = contactConstraints(obj,kinsol,allow_multiple_contacts,active_collision_options)
% function [phi,xA,xB,idxA,idxB,n,D,mu,dn,dD] = contactConstraints(obj,kinsol,body_idx)
% Compute the contact constraints for a manipulator, and relevent bases.
% The contact frame always points from body B to body A.
%
% @param obj
% @param kinsol
% @param allow_multiple_contacts Allow multiple contacts per body pair.
%      Optional, defaults to false.
% @param active_collision_options A optional struct to determine which
%    bodies and collision groups are checked. See collisionDetect.
% @retval phi (m x 1) Vector of gap function values (typically contact distance), for m possible contacts
% @retval normal (3 x m) Contact normal vector in world coordinates, points from B to A
% @retval d {k} (3 x m) Contact friction basis vectors in world coordinates, points from B to A
% @retval xA (3 x m) The closest point on body A to contact with body B, relative to body A origin and in body A frame
% @retval xB (3 x m) The closest point on body B to contact with body A, relative to body B origin and in body B frame
% @retval idxA (m x 1) The index of body A. 0 is the special case for the environment/terrain
% @retval idxB (m x 1) The index of body B. 0 is the special case for the environment/terrain
% @retval mu (m x 1) Coefficients of friction
% @retval n (m x n) normal vector in joint coordinates, state vector length n
% @retval D {2k}(m x n) friction cone basis in joint coordinates, for k directions
% @retval dn (mn x n) dn/dq derivative
% @retval dD {2k}(mn x n) dD/dq derivative

compute_first_derivative = nargout > 8;
compute_second_derivative = nargout > 10;

if nargin<3,
  allow_multiple_contacts = false;
end

if nargin<4,
  active_collision_options = struct();
end

if ~isstruct(kinsol)
  % treat input as contactPositions(obj,q)
  kinsol = doKinematics(obj,kinsol,compute_second_derivative);
end

[phi,normal,xA,xB,idxA,idxB] = collisionDetect(obj,kinsol,allow_multiple_contacts,active_collision_options);
idxA = idxA';
idxB = idxB';
nC = numel(phi);

% If there are no potential collisions, return empty
if nC == 0
  d = [];
  mu = [];
  n = [];
  D = [];
  dn = [];
  dD = [];
  return;
end

% For now, all coefficients of friction are 1
mu = ones(nC,1);

if obj.mex_model_ptr ~= 0
  if compute_first_derivative
    if ~compute_second_derivative
      [d, n, D] = contactConstraintsmex(obj.mex_model_ptr, normal, int32(idxA), int32(idxB), xA, xB);
    else
      [d, n, D, dn, dD] = contactConstraintsmex(obj.mex_model_ptr, normal, int32(idxA), int32(idxB), xA, xB);
    end
  else
    d = surfaceTangentsmex(obj.mex_model_ptr, normal);
  end
else %MATLAB implementation
  if compute_first_derivative
    if ~compute_second_derivative
      [d, n, D] = contactConstraintDerivatives(obj, normal, kinsol, idxA, idxB, xA, xB);
    else
      [d, n, D, dn, dD] = contactConstraintDerivatives(obj, normal, kinsol, idxA, idxB, xA, xB);
    end
  else
    d = obj.surfaceTangents(normal);
  end
end

end


text:
package module

import (
	"github.com/ixre/gof"
	"github.com/ixre/gof/storage"
	"go2o/core/module/bank"
	"go2o/core/module/pay"
)

type PaymentModule struct {
	app     gof.App
	storage storage.Interface
	ptArr   []*bank.PaymentPlatform
	gateway *pay.Gateway
}

func (p *PaymentModule) Submit(userId int64, data map[string]string) error {
	return p.gateway.Submit(userId, data)
}

func (p *PaymentModule) CreateToken(userId int64) string {
	return p.gateway.CreatePostToken(userId)
}

func (p *PaymentModule) CheckAndPayment(userId int64, data map[string]string) error {
	return p.gateway.CheckAndPayment(userId, data["trade_no"], data["trade_pwd"])
}

// 模块数据
func (p *PaymentModule) SetApp(app gof.App) {
	p.app = app
	p.storage = app.Storage()
	p.gateway = pay.NewGateway(p.storage)
}

// 初始化模块
func (p *PaymentModule) Init() {

}

// 获取支付平台
func (p *PaymentModule) GetPayPlatform() []*bank.PaymentPlatform {
	if p.ptArr == nil {
		p.ptArr = []*bank.PaymentPlatform{
			bank.Alipay, bank.ChinaPay,
			bank.Tenpay, bank.KuaiBill}
	}
	return p.ptArr
}


text:
local Arg = {...}

shell.setCompletionFunction(shell.getRunningProgram(),function(shell,nIndex,sText) if nIndex == 1 then return fs.complete(sText, shell.dir(), true, true) end end)

if Arg[1] == nil then
  print("Usage: size <path>")
  return 1
end

local filename = shell.resolve(Arg[1])

if fs.exists(filename) == true then
  if fs.isDir(filename) then
    os.loadAPI("/usr/apis/wilmaapi")
    local fileta = wilmaapi.listAllFiles(filename)
    local size = 0
    for _,sizefile in ipairs(fileta) do
      size = size + fs.getSize(sizefile)
    end
    print("Size: "..size.." Bytes")
  else
  print("Size: "..fs.getSize(filename).." Bytes")
  end
else
  print("File does not exists")
  return 2
end

return 0


text:
begin require 'rspec/expectations'; rescue LoadError; require 'spec/expectations'; end
require 'cucumber/formatter/unicode'
$:.unshift(File.dirname(__FILE__) + '/../../lib')
require 'frontmatter'

Before do
end

After do
end

Given /^([A-Z0-9a-z\._\/\-\ ]+) as a path to a file ([not])?\ ?containing frontmatter$/ do |path, check|
  @doc = path
  @not  = check
end

Given /^I have a document containing frontmatter$/ do
@doc = <<-eos
---
title: Test
date: 2011-01-01
layout: default
---
Bla blah
eos
end

When /^I call ([A-Z0-9a-z_\?]+)$/ do |method|
  @front_matter_content = FrontMatter.send(method.to_sym, @doc)
end

Then /^I should receive\ ?a? ([A-Za-z]+)$/ do |object|
  if ['true', 'false'].include? object
    @front_matter_content.to_s.should == object
  else
    @front_matter_content.class.name.should == object
  end
end

Then /^the hash should have a :([a-z]+) key$/ do |key|
  @front_matter_content.has_key?(key.to_sym).should == true
end


text:
package br.com.arbo.steamside.cloud.autoupload;

import javax.inject.Inject;

import br.com.arbo.steamside.settings.file.File_steamside_xml;
import br.com.arbo.steamside.settings.file.SaveFile;
import br.com.arbo.steamside.settings.file.SaveSteamsideXml;
import br.com.arbo.steamside.xml.SteamsideXml;

public class AutoUpload implements SaveFile {

	@Inject
	public AutoUpload(
			File_steamside_xml file_steamside_xml,
			ParallelUpload parallel)
	{
		SaveSteamsideXml save = new SaveSteamsideXml(file_steamside_xml);
		save.addListener(parallel::submit);
		this.save = save;
	}

	@Override
	public void save(SteamsideXml xml)
	{
		this.save.save(xml);
	}

	private final SaveFile save;

}


text:
"use strict";

var forEach       = require("./for-each")
  , isPlainObject = require("./is-plain-object")
  , ensureValue   = require("./valid-value")
  , isArray       = Array.isArray;

var copyValue = function (value, ancestors, ancestorsCopy) {
	var mode;
	if (isPlainObject(value)) mode = "object";
	else if (isArray(value)) mode = "array";
	if (!mode) return value;

	var copy = ancestorsCopy[ancestors.indexOf(value)];
	if (copy) return copy;
	copy = mode === "object" ? {} : [];

	ancestors.push(value);
	ancestorsCopy.push(copy);
	if (mode === "object") {
		forEach(value, function (item, key) {
			copy[key] = copyValue(item, ancestors, ancestorsCopy);
		});
	} else {
		value.forEach(function (item, index) {
			copy[index] = copyValue(item, ancestors, ancestorsCopy);
		});
	}
	ancestors.pop();
	ancestorsCopy.pop();

	return copy;
};

module.exports = function (source) { return copyValue(ensureValue(source), [], []); };


text:
Ext.define('gov.va.cpe.viewdef.editors.RoadTripEditor', {
	requires: ['gov.va.cpe.viewdef.editors.PointOfCareEditor',
	           'gov.va.cpe.viewdef.editors.PointOfCareForm',
	           'gov.va.hmp.healthtime.PointInTime'],
	alias: 'widget.roadtrip',
	extend: 'Ext.panel.Panel',
	minWidth: 330,
	height: 180,
	layout: 'border',
	items: [{
		xtype: 'form',
		region: 'center',
		layout: {type: 'vbox', align: 'stretch'},
		items: [{
			xtype: 'pocedit',
			fieldLabel: 'Location',
			allowBlank: false,
			name: 'locationUid',
		},{
			xtype: 'datefield',
			fieldLabel: 'Date',
			name: 'day'
		},{
			xtype: 'textfield',
			fieldLabel: 'Time',
			name: 'time'
		},{
			xtype: 'textfield',
			fieldLabel: 'Comment',
			name: 'comment'
		}]
	}],
	reset: function(a, b, c) {
		this.down('form').getForm().reset();
	},
	setValue: function(val) {
		var json = val;
		if(!Ext.isObject(val)) {
			json = Ext.decode(val);
		}
		if(json.data && json.data.length>0) {
			json = json.data[0];
		}
		if(json.day) {
			json.day = PointInTime.format(json.day, 'm/d/Y');
		}
		if(json.location && json.location.uid && !json.locationUid) {
			json.locationUid = json.location.uid;
		}
		if(json.locationUid) {
			var store = Ext.StoreManager.get('pocStore') || Ext.create('gov.va.cpe.store.PointOfCareStore');
			var recdex = store.find('uid',json.locationUid);
			if(recdex==-1 && json.location && json.location.displayName && !(json.location.displayName == json.locationUid)) {
				// Broken link.
				json.locationUid = json.location.displayName;
			}
		}

		this.down('form').getForm().reset();
		this.down('form').getForm().setValues(json);
		this.srcJson = json;
	},
	getValue: function() {
		// Get full blown location object from location UID to send to back-end
		var vals = this.down('form').getForm().getValues();
		if(vals.locationUid) {

			var store = Ext.StoreManager.get('pocStore') || Ext.create('gov.va.cpe.store.PointOfCareStore');
			store.each(function(rec){
				if(rec.get('uid')==vals.locationUid) {
					vals.location = rec.data;
				}
			});
			if(!vals.location) {
				vals.location = {
					uid: vals.locationUid,
					displayName: vals.locationUid,
					description: vals.locationUid
				}
			}
		}

		if(vals.day) {
			vals.day = Ext.Date.format(new Date(vals.day), Ext.Date.patterns.HL7);
		}

		if(this.srcJson && this.srcJson.uid) {
			vals.uid = this.srcJson.uid;
		}
		return vals;
	},
	isValid: function() {
		return true;
	},
	statics: {
		editRecord: function(evt, pid, uid) {
			var pid = pid;
			var cmp = null;
			var boards = Ext.ComponentQuery.query('boardgridpanel');
			if(boards && boards.length>0) {
				for(bdex in boards) {
					var board = boards[bdex];
					if(board && board.isVisible && board.el && board.el.dom) {
						var tcmp = evt.target;
						var cont = tcmp.compareDocumentPosition(board.el.dom);
						if(cont==10) {
							cmp = board;
							break;
						}
					}
				}
			}

			var cX = evt.clientX;
			var cY = evt.clientY;
			var wdth = 350;
			var ht = 200;
			if(cmp) {
				if(cmp.getWidth()<(cX+wdth)) {
					cX = cmp.getWidth()-wdth;
				}
				if(cmp.getHeight()<(cY+ht)) {
					cY = cmp.getHeight()-ht;
				}
			}
			var constrainToComponent = null;
			if(cmp && cmp.el) {
				constrainToComponent = cmp.el;
			}

			var wnd = Ext.create('Ext.window.Window', {
				layout: 'fit',
				header: 'false',
				items: [{
					xtype: 'roadtrip'
				}],
				constrainTo: constrainToComponent,
				constrainHeader: true,
				bbar: {items:[{
					xtype: 'button',
					itemId: "acceptBtn",
					disabled: true,
					text: 'Submit',
					handler: function(bn) {
						var rt = bn.up('window').down('roadtrip');
						var val = rt.getValue();
						var pwnd = bn.up('window');
						Ext.Ajax.request({
							url: '/patientDomain/roadTrip',
							method: 'POST',
							params: {value: Ext.encode(val), pid: pid},
							success: function(resp) {
								pwnd.close();
							},
							failure: function(resp) {
								Ext.MessageBox.alert('Save Failed','Could not save Transport: '+resp.responseText);
							}
						})
					}
				}]},
			    onBoxReady: function () {
			        var me = this;

			        me.transport = me.down('roadtrip');
			        me.form = me.transport.down('form');
			        me.form.on('validitychange', function(form, isValid) {
			        	var savebtn = me.down('#acceptBtn');
			        	if (isValid) {
			        		savebtn.enable();
			        	} else {
			        		savebtn.disable();
			        	}
			        });
			    }
			});
			if(uid && !uid=='') {
				Ext.Ajax.request({
					url: '/patientDomain/findOne/'+uid,
					method: 'GET',
					success: function(resp) {
						var rec = Ext.decode(resp.responseText);
						if(rec && rec.uid) {
							wnd.down('roadtrip').setValue(rec);
							wnd.setPosition(cX, cY);
							wnd.setSize(350, 220);
							wnd.show();
						}
					},
					failure: function(resp) {

					}
				});
			}
			else {
				wnd.setPosition(cX, cY);
				wnd.setSize(350, 220);
				wnd.show();
			}
		},
		deleteRecord: function(evt, pid, uid) {
			Ext.Ajax.request({
				url: '/editor/submitFieldValue',
				method: 'POST',
				params: {
					fieldName: 'removed',
					value: 'true',
					pid: pid,
					uid: uid
				},
				success: function(resp) {

				},
				failure: function(resp) {

				}
			})
		}
	}
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?php echo (isset($GLOBALS['ActivePage']) ? $GLOBALS['ActivePage'] . ' - ' : ''); ?>PHP One Framework</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="content/css/bootstrap.min.css" rel="stylesheet" />
    <link href="content/css/bootstrap-theme.min.css" rel="stylesheet" />
	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" />
	<link href="content/css/Styles.css" rel="stylesheet" />

                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                  </button>
                  Php One

				    <li <?= ($GLOBALS['ActivePage'] == "Home" ? 'class="active"' : ''); ?>>Home

		            <li <?= ($GLOBALS['ActivePage'] == "About" ? 'class="active"' : ''); ?>>About

                    <li <?= ($GLOBALS['ActivePage'] == "Contact" ? 'class="active"' : ''); ?>>Contact

		<?php require_once($view); ?>


text:
import { LEG_CAVE, STATION_NORMAL } from '../core/constants';
import { StationPosition } from '../core/StationPosition';

const ftom = 12 * 0.0254;

class pltHandler {

	constructor( fileName ) {

		this.fileName = fileName;
		this.type = 'text';

	}

	parse ( cave, dataStream, metadata /*, section */ ) {

		cave.metadata = metadata;

		cave.setCRS( null );

		const surveyTree  = cave.surveyTree;
		const limits      = cave.limits;
		const projection  = cave.projection;

		const stationMap  = new Map();
		const xSects      = [];
		const stations    = [];
		const groups      = [];

		const lines = dataStream.split( /[\n\r]+/ );
		const l = lines.length;

		let path = [];
		let segments = [];
		let stationName;
		let surveyName;
		let surveyId = 0;
		let lastStationIndex = -1;
		let section = 'root';
		let lrud, stationIndex, coords;

		for ( let i = 0; i < l; i++ ) {

			const parts = lines[ i ].split( /\s+/ );

			const cmd = parts[ 0 ].charAt( 0 );

			switch ( cmd ) {

			case 'M': // move

				if ( segments.length > 1 ) groups.push( segments );

				segments = [];
				lastStationIndex = -1;

			case 'D': // eslint-disable-line no-fallthrough

				stationName = parts[ 4 ].substring( 1 );

				path[ 2 ] = stationName;

				coords = readCoords( parts );
				coords.type = STATION_NORMAL;

				stationIndex = coords.stationIndex;

				segments.push( { coords: coords, type: LEG_CAVE, survey: surveyId } );

				if ( coords.connections === 0 ) {

					// parse comment
					const comment = ( parts[ 13 ] === undefined ) ? null : parts.slice( 13 ).join( ' ' );

					surveyTree.addLeaf( path, coords, comment );

				}

				coords.connections++;

				if ( parts[ 5 ] === 'P' ) {

					let l = +parts[ 6 ];
					let u = +parts[ 7 ];
					let d = +parts[ 8 ];
					let r = +parts[ 9 ];

					let nCount = 0;

					if ( l < 0 ) { l = 0; nCount++; }
					if ( u < 0 ) { u = 0; nCount++; }
					if ( d < 0 ) { d = 0; nCount++; }
					if ( r < 0 ) { r = 0; nCount++; }

					if ( nCount !== 4 ) {

						lrud = {
							l: l * ftom,
							u: u * ftom,
							d: d * ftom,
							r: r * ftom
						};

						const from = ( lastStationIndex !== -1 ) ? stations[ lastStationIndex ] : null;

						xSects.push( { m_from: lastStationIndex, m_to: stationIndex, start: from, end: coords, lrud: lrud, survey: surveyId, type: 2  } );

					}

					lastStationIndex = stationIndex;

				}

				break;

			case 'N': // line survey

				surveyName = parts[ 0 ].substring( 1 );

				path = [ section, surveyName ];
				surveyId = surveyTree.addPath( section + '.' + surveyName ).id;

				break;

			case 'Z': // end of survey

				/*
				limits.min.set(
					+parts[ 3 ],
					+parts[ 1 ],
					+parts[ 5 ]
				);

				limits.max.set(
					+parts[ 4 ],
					+parts[ 2 ],
					+parts[ 6 ]
				);
				*/

				break;

			case 'F': // feature survey
			case 'L': // feature location
			case 'X': // end of survey
			case 'O': // Datum
			case 'G': // UTM Zone
			case 'P': // fixed point
			case 'R': // loop spec
			case 'C': // loop count
			case '\x1A': // end of file

				break;

			case 'S':

				section = lines[ i ].substring( 1 );
				break;

			default:

				console.log( 'unknown command ', cmd );

			}

		}

		if ( segments.length > 1 ) groups.push( segments );

		cave.addStations( stations );

		cave.addLineSegments( groups );

		cave.addXsects( xSects );

		return Promise.resolve( cave );

		function readCoords( parts ) {

			const lastKey = parts[ 1 ] + ':' + parts[ 2 ] + ':' + parts[ 3 ];
			const cachedCoords = stationMap.get( lastKey );

			let coords;

			if ( cachedCoords !== undefined ) {

				coords = cachedCoords;

			} else {

				coords = new StationPosition(
					+parts[ 2 ] * ftom,
					+parts[ 1 ] * ftom,
					+parts[ 3 ] * ftom
				);

				if ( projection !== null ) {

					const projectedCoords = projection.forward( {
						x: coords.x,
						y: coords.y
					} );

					coords.x = projectedCoords.x;
					coords.y = projectedCoords.y;

				}

				coords.stationIndex = stations.length;

				stations.push( coords );
				stationMap.set( lastKey, coords );

				limits.expandByPoint( coords );

			}

			return coords;

		}

	}

}

export { pltHandler };