text:
package com.youaix.framework.page;

import java.util.*;

import com.youaix.framework.mission.Mission;

import android.app.Application;
import android.app.Notification;
import android.app.Service;
import android.content.res.Resources;
import android.os.Vibrator;

public class UIXApplication extends Application
{
	/*
	// TODO: missions可能会变成null值
	private HashMap<String, Mission> missions = null;

	public void onCreate()
	{
		super.onCreate();
		this.createMissionPool();
	}

	private final void createMissionPool()
	{
		this.missions = new HashMap<String, Mission>();
	}

	public final void newMission(String missionName, Mission mission)
	{
		this.missions.put(missionName, mission);
	}

	public final void missionCompleted(String missionName)
	{
		this.missions.remove(missionName);
	}

	public final Object getMissionData(String missionName, String field)
	{
		Mission mission = this.missions.get(missionName);
		if (mission != null) return mission.getData(field);
		else return null;
	}

	public final void stopMission(String missionName)
	{
		Mission mission = this.missions.get(missionName);
		if (mission != null) mission.stopMission();
	}

	public final void pauseMission(String missionName)
	{
		Mission mission = this.missions.get(missionName);
		if (mission != null) mission.pauseMission();
	}

	public final void resumeMission(String missionName)
	{
		Mission mission = this.missions.get(missionName);
		if (mission != null) mission.resumeMission();
	}
	*/
}


text:
module Locomotive::Coal

  class Resource

    attr_accessor :attributes

    def initialize(attributes)
      @attributes = attributes
    end

    def method_missing(name, *args)
      if self.attributes.key?(name.to_s)
        self.attributes[name.to_s]
      else
        super
      end
    end

    def respond_to?(name, include_private = false)
      self.attributes.key?(name.to_s) || super
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
import multiprocessing as mp
import os
import re
import sys
import webbrowser

try:
    import ujson as json
except ImportError:
    import json

from argparse import ArgumentParser
from multiprocessing import Queue
from time import time, sleep
from urllib.parse import ParseResult, urlsplit, urlunsplit, parse_qs, urlencode

# add the helpsocial directory to the path
# so that we can import it more cleanly
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from helpsocial import RestConnectClient
from helpsocial.auth import UserAuth
from helpsocial.hooks import RequestPrinter, ResponsePrinter
from helpsocial.utils import data_get

class Worker(object):
    def __init__(self, client, template_url, token):
        self.name = 'Worker-' + os.urandom(4).hex()
        self.pid = None
        self.template_url = template_url
        self.client = client
        self.auth = UserAuth(client.auth_scope, client.api_key, token)

    def handle(self, manager, conversation_id):
        self.pid = str(mp.current_process().pid)
        self._log('handling conversation {}', conversation_id)
        url = re.sub('{conversation_id}', conversation_id, self.template_url)
        try:
            authed_url = self._authenticate(url, self._get_single_use_token())
            self._log('opening conversation spa [{}]...', authed_url)
            if webbrowser.open_new(authed_url):
                self._log('opened conversation spa.')
            else:
                self._log('failed to open conversation spa.')
        except Exception as e:
            self._log('{} opening conversation {} spa.', e, conversation_id)
        finally:
            manager.work_complete(self)
            self.pid = None

    def _get_single_use_token(self):
        """Retrieve an single use token for the authenticated user.
        This allows the client to relatively safely authenticate their user through
        the query string, as is required when accessing a page via an iFrame, where
        headers cannot be set.
        """

        self._log('Retrieving single use token.')
        response = self.client.get('tokens/exchange', auth=self.auth, http_errors=True)
        if response.status_code != 200:
            raise Exception(response.json())
        return data_get(response.json(), 'data.token')

    def _authenticate(self, url, token):
        self._log('Authenticating spa request [{}].', url)
        parsed = urlsplit(url)
        query = {} if not parsed.query else parse_qs(parsed.query)
        query.update({
            'scope': token['scope'],
            'token': token['value']
        })
        return urlunsplit((parsed.scheme, parsed.netloc, parsed.path,
                           urlencode(query, doseq=True), parsed.fragment,))

    def _log(self, message, *args, **kwargs):
        print('[{},{}] {}'.format(self.name, self.pid, message.format(*args, **kwargs)))

class Manager(object):
    def __init__(self, workers=-1):
        self.cancelled = False
        self._workers = Queue(workers)
        self._queue = Queue()
        self._processes = []
        self._thread = mp.Process(target=self._run)

    def add_worker(self, worker):
        if self._workers.full():
            raise Exception('Worker pool full')
        self._workers.put_nowait(worker)

    def queue(self, conversation):
        self._queue.put(conversation)

    def has_pending(self):
        return not self._queue.empty()

    def start(self):
        self._thread.start()

    def stop(self):
        self.cancelled = True
        for process in self._processes:
            process.terminate()

        start = time()
        while self._thread.is_alive():
            if (time() - start) > 30:
                self._thread.terminate()
                break
            sleep(1)

    def work_complete(self, worker):
        self._workers.put_nowait(worker)

    def _run(self):
        while True:
            if self.cancelled:
                break
            try:
                worker = self._workers.get_nowait()
            except:
                print('No worker available.')
                sleep(1)
                break
            try:
                job = self._queue.get_nowait()
            except:
                print('No job available.')
                self._workers.put(worker)
                sleep(1)
                break

            process = mp.Process(target=worker.handle, args=(self, job,))
            self._processes.append(process)
            process.start()

def read_config(path):
    """Read the json configuration

    :type path: string
    :param path:
    :return:
    """
    if not os.path.exists(path):
        raise IOError('{} does not exist.', path)
    with open(path, 'r') as file_:
        return json.load(file_)

def single(conversation_id, config_path):
    config = read_config(config_path)

    client = RestConnectClient(
        data_get(config, 'auth.auth_scope'),
        data_get(config, 'auth.api_key'),
        host=data_get(config, 'api.host'),
        ssl=data_get(config, 'api.ssl'),
        request_hooks=[RequestPrinter()],
        response_hooks=[ResponsePrinter()]
    )

    manager = Manager()
    manager.add_worker(Worker(client,
                              data_get(config, 'launch_conversation.spa_url'),
                              data_get(config, 'launch_conversation.user_token')))

    manager.queue(conversation_id)

    manager.start()
    while manager.has_pending():
        sleep(1)
    manager.stop()

if __name__ == '__main__':
    parser = ArgumentParser()

    sub = parser.add_subparsers()

    single_cmd = sub.add_parser('single')
    single_cmd.add_argument('conversation_id', help='Conversation id to open.')
    single_cmd.add_argument('--config', dest='config_path', default=os.path.join(os.path.abspath(os.path.dirname(__file__)), '.config.json'))
    single_cmd.set_defaults(func=single)

    args = vars(parser.parse_args())
    func = args['func']
    del args['func']

    func(**args)


text:
import csv
import unittest
from infrastructure import models
from scorecard.models import Geography
from django.db import transaction
import xlrd
import logging
import json

logger = logging.Logger(__name__)

headers = [
    x.strip()
    for x in """
    Function, Project Description, Project Number,
    Type, MTSF Service Outcome, IUDF,
    Own Strategic Objectives, Asset Class, Asset Sub-Class,
    Ward Location, GPS Longitude, GPS Latitude""".strip().split(
        ","
    )
]
# Audited Outcome 2017/18,
# Full Year Forecast 2018/19,
# Budget year 2019/20,
# Budget year 2020/21,
# Budget year 2021/22

def float_or_none(val):
    try:
        return float(val)
    except ValueError:
        return None

def check_file(fp):
    reader = csv.DictReader(fp)
    return check_headers(reader.fieldnames)

def check_headers(fields):
    missing_headers = [h for h in headers if h not in fields]
    if len(missing_headers) > 0:
        raise ValueError(
            "The following fields are missing from the data source: %s"
            % missing_headers
        )

@transaction.atomic
def load_excel(filename, financial_year=None, file_contents=None):
    def clean(s):
        if type(s) == str:
            return s.strip()
        else:
            return s

    def fix_broken_headers(header_row):
        header_row = [r.replace("\n", " ") for r in header_row]
        header_row = [
            r.replace("Project Decription", "Project Description") for r in header_row
        ]
        return header_row

    def sheet_parser(sheet):
        skip = True
        header_row = []
        for idx in range(0, sheet.nrows):
            row = [clean(sheet.cell(idx, col).value) for col in range(0, sheet.ncols)]

            val = sheet.cell(idx, 0).value.strip()
            if val != "Function" and skip:
                continue
            elif val == "Function":
                header_row = fix_broken_headers(row)
                check_headers(header_row)
                skip = False
                continue
            elif val == "":
                return

            yield dict(zip(header_row, row))

    workbook = xlrd.open_workbook(filename, file_contents=file_contents)
    print(workbook.sheets)
    for sheet in workbook.sheets():
        geo_code = sheet.name
        logger.info("Processing sheet: %s" % sheet.name)
        if Geography.objects.filter(geo_code=geo_code).count() == 0:
            raise Exception(
                "%s is an unknown Geography. Please ensure that this Geography exists in the database"
                % geo_code
            )
        geography = Geography.objects.get(geo_code=geo_code)
        load_file(geography, sheet_parser(sheet), financial_year)

def load_csv(geography, fp):
    check_file(fp)
    fp.seek(0)
    reader = csv.DictReader(fp)
    return load_file(geography, reader)

@transaction.atomic
def load_file(geography, reader, financial_year):
    implementation_year, _ = models.FinancialYear.objects.get_or_create(budget_year=financial_year)
    for idx, row in enumerate(reader):
        try:
            p, _ = models.Project.objects.update_or_create(
                geography=geography,
                function=row["Function"],
                project_description=row["Project Description"],
                project_number=row["Project Number"],
                defaults={
                    "project_type": row["Type"],
                    "mtsf_service_outcome": row["MTSF Service Outcome"],
                    "iudf": row["IUDF"],
                    "own_strategic_objectives": row["Own Strategic Objectives"],
                    "asset_class": row["Asset Class"],
                    "asset_subclass": row["Asset Sub-Class"],
                    "ward_location": row["Ward Location"],
                    "longitude": float_or_none(row["GPS Longitude"]),
                    "latitude": float_or_none(row["GPS Latitude"]),
                    "latest_implementation_year": implementation_year,
                },
            )
            additional_fields = [k for k in row.keys() if k not in headers]
            budget_phase_fields = find_phase(additional_fields)
            quarterly_fields = find_quarter(additional_fields)

            if not is_selected_year_in_column_headers(budget_phase_fields, financial_year):
                raise ValueError("Could not find a field for the selected budget phase and/or year")

            for field in budget_phase_fields:
                amount = row[field]
                create_expenditure(p, field, amount)
            for field in quarterly_fields:
                amount = row[field]
                create_quarter(p, field, amount, financial_year)

        except Exception as e:
            raise ValueError("Error loading data in row: %d - %s" % (idx + 2, row))

    return idx + 1

def create_expenditure(project, finance_phase, amount):
    phase, year = create_finance_phase(finance_phase)

    try:
        expenditure, _ = models.Expenditure.objects.update_or_create(
            project=project,
            budget_phase=phase,
            financial_year=year,
            defaults={"amount": float(amount)},
        )
        return True
    except ValueError:
        return False

def create_finance_phase(s):
    phase, year = parse_finance_phase(s)
    fy, _ = models.FinancialYear.objects.get_or_create(budget_year=year)

    try:
        phase = models.BudgetPhase.objects.get(name=phase)
    except models.BudgetPhase.DoesNotExist as e:
        raise ValueError("Could not find an existing budget phase matching those supplied")

    return phase, fy

def create_quarter(project, header, amount, financial_year):
    """
    create the nessesary quarter
    """
    quarter = None
    if "Q1" in header:
        quarter = "q1"
    elif "Q2" in header:
        quarter = "q2"
    elif "Q3" in header:
        quarter = "q3"
    elif "Q4" in header:
        quarter = "q4"
    else:
        raise ValueError("Unknown Quarter")

    if quarter and amount:
        models.ProjectQuarterlySpend.objects.update_or_create(
            project=project,
            financial_year=financial_year,
            defaults={quarter: float(amount)},
        )

def parse_finance_phase(s):
    parts = s.split()
    year = parts[-1]

    y1, y2 = year.split("/")
    if len(y2) == 2:
        y2 = str(int(y1) + 1)

    year = "%s/%s" % (y1, y2)

    return " ".join(parts[0:-1]), year

def find_phase(fields):
    """Find fields with the project budgets"""
    phase = []
    for field in fields:
        if (
            field.startswith("Audited")
            or field.startswith("Adjusted")
            or field.startswith("Original")
            or field.startswith("Budgeted")
            or field.startswith("Budget year")
            or field.startswith("Full Year Forecast")
        ):
            phase.append(field)

    return phase

def find_quarter(fields):
    """Find the fields with project quarters"""
    return [field for field in fields if field.startswith("Q")]

def chart_quarters(quarter_queryset, phase_queryset):
    """
    prepare data for charting.
    """
    quarter_data = []
    original_data = {"labels": [], "data": []}
    adjusted_data = {"labels": [], "data": []}

    if phase_queryset:
        for phase in phase_queryset:
            if phase.budget_phase.name == "Original Budget":
                original_data["labels"].append(phase.budget_phase.name)
                original_data["data"].append(float(phase.amount))
            elif phase.budget_phase.name == "Adjusted Budget":
                adjusted_data["labels"].append(phase.budget_phase.name)
                adjusted_data["data"].append(float(phase.amount))

    if quarter_queryset:
        for spend in quarter_queryset:
            if spend.q1:
                quarter_data.append(["Q1", float(spend.q1)])
            if spend.q2:
                quarter_data.append(["Q2", float(spend.q2)])
            if spend.q3:
                quarter_data.append(["Q3", float(spend.q3)])
            if spend.q4:
                quarter_data.append(["Q4", float(spend.q4)])

    quarter_data = sorted(quarter_data, key=lambda quarter: quarter[0])
    return original_data, adjusted_data, quarter_data

def is_selected_year_in_column_headers(budget_phases, year):
    year_exists = False
    for field in budget_phases:
        if "budget" in field.lower():
            if str(year)[:5] in field:
                year_exists = True

    return year_exists


text:
package org.apache.ignite.internal.client;

import java.io.*;

/**
 * Cache metrics used to obtain statistics on cache itself or any of its entries.
 * Cache metrics can be fetched from server either for the whole cache or for
 * specific entry via any of the {@code metrics(...)} methods available on
 * {@link GridClientData} API.
 */
public interface GridClientDataMetrics extends Serializable {
    /**
     * Gets create time of the owning entity (either cache or entry).
     *
     * @return Create time.
     */
    public long createTime();

    /**
     * Gets last write time of the owning entity (either cache or entry).
     *
     * @return Last write time.
     */
    public long writeTime();

    /**
     * Gets last read time of the owning entity (either cache or entry).
     *
     * @return Last read time.
     */
    public long readTime();

    /**
     * Gets total number of reads of the owning entity (either cache or entry).
     *
     * @return Total number of reads.
     */
    public int reads();

    /**
     * Gets total number of writes of the owning entity (either cache or entry).
     *
     * @return Total number of writes.
     */
    public int writes();

    /**
     * Gets total number of hits for the owning entity (either cache or entry).
     *
     * @return Number of hits.
     */
    public int hits();

    /**
     * Gets total number of misses for the owning entity (either cache or entry).
     *
     * @return Number of misses.
     */
    public int misses();
}


text:
package ecse414.fall2015.group21.game.util;

/**
 * Represents a thread that runs at a specific TPS until terminated.
 * <p>
 * This is a library file from com.flowpowered.commons.ticking
 */
public class TPSLimitedThread extends Thread {
    private final TickingElement element;
    private final Timer timer;
    private volatile boolean running = false;

    public TPSLimitedThread(String name, TickingElement element, int tps) {
        super(name);
        this.element = element;
        timer = new Timer(tps);
    }

    @Override
    public void run() {
        try {
            running = true;
            element.onStart();
            timer.start();
            long lastTime = getTime() - (long) (1f / timer.getTps() * 1000000000), currentTime;
            while (running) {
                try {
                    element.onTick((currentTime = getTime()) - lastTime);
                    lastTime = currentTime;
                    timer.sync();
                } catch (Exception ex) {
                    System.err.println("Exception in ticking thread, attempting to stop normally");
                    ex.printStackTrace();
                    break;
                }
            }
            element.onStop();
        } catch (Exception ex) {
            System.err.println("Exception in ticking thread");
            ex.printStackTrace();
        }
    }

    public void terminate() {
        running = false;
    }

    public boolean isRunning() {
        return running;
    }

    private static long getTime() {
        return System.nanoTime();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Cowboy.Buffer;
using Logrila.Logging;

namespace Cowboy.WebSockets
{
    internal sealed class WebSocketClientHandshaker
    {
        private static readonly ILog _log = Logger.Get<WebSocketClientHandshaker>();
        private static readonly char[] _headerLineSplitter = new char[] { '\r', '\n' };

        internal static byte[] CreateOpenningHandshakeRequest(AsyncWebSocketClient client, out string secWebSocketKey)
        {
            var sb = new StringBuilder();

            // The handshake MUST be a valid HTTP request as specified by [RFC2616].
            // The method of the request MUST be GET, and the HTTP version MUST be at least 1.1.
            // For example, if the WebSocket URI is "ws://example.com/chat",
            // the first line sent should be "GET /chat HTTP/1.1".
            sb.AppendFormatWithCrCf("GET {0} HTTP/{1}",
                !string.IsNullOrEmpty(client.Uri.PathAndQuery) ? client.Uri.PathAndQuery : "/",
                Consts.HttpVersion);

            // The request MUST contain a |Host| header field whose value
            // contains /host/ plus optionally ":" followed by /port/ (when not
            // using the default port).
            sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Host, client.Uri.Host);

            // The request MUST contain an |Upgrade| header field whose value
            // MUST include the "websocket" keyword.
            sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Upgrade, Consts.WebSocketUpgradeToken);

            // The request MUST contain a |Connection| header field whose value
            // MUST include the "Upgrade" token.
            sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Connection, Consts.WebSocketConnectionToken);

            // The request MUST include a header field with the name
            // |Sec-WebSocket-Key|.  The value of this header field MUST be a
            // nonce consisting of a randomly selected 16-byte value that has
            // been base64-encoded (see Section 4 of [RFC4648]).  The nonce
            // MUST be selected randomly for each connection.
            secWebSocketKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Substring(0, 16)));
            sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketKey, secWebSocketKey);

            // The request MUST include a header field with the name
            // |Sec-WebSocket-Version|.  The value of this header field MUST be 13.
            sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketVersion, Consts.WebSocketVersion);

            // The request MAY include a header field with the name
            // |Sec-WebSocket-Extensions|.  If present, this value indicates
            // the protocol-level extension(s) the client wishes to speak.  The
            // interpretation and format of this header field is described in Section 9.1.
            if (client.OfferedExtensions != null && client.OfferedExtensions.Any())
            {
                foreach (var extension in client.OfferedExtensions)
                {
                    sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketExtensions, extension.ExtensionNegotiationOffer);
                }
            }

            // The request MAY include a header field with the name
            // |Sec-WebSocket-Protocol|.  If present, this value indicates one
            // or more comma-separated subprotocol the client wishes to speak,
            // ordered by preference.  The elements that comprise this value
            // MUST be non-empty strings with characters in the range U+0021 to
            // U+007E not including separator characters as defined in
            // [RFC2616] and MUST all be unique strings.  The ABNF for the
            // value of this header field is 1#token, where the definitions of
            // constructs and rules are as given in [RFC2616].
            if (client.RequestedSubProtocols != null && client.RequestedSubProtocols.Any())
            {
                foreach (var description in client.RequestedSubProtocols)
                {
                    sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketProtocol, description.RequestedSubProtocol);
                }
            }

            // The request MUST include a header field with the name |Origin|
            // [RFC6454] if the request is coming from a browser client.  If
            // the connection is from a non-browser client, the request MAY
            // include this header field if the semantics of that client match
            // the use-case described here for browser clients.  The value of
            // this header field is the ASCII serialization of origin of the
            // context in which the code establishing the connection is
            // running.  See [RFC6454] for the details of how this header field
            // value is constructed.

            // The request MAY include any other header fields, for example,
            // cookies [RFC6265] and/or authentication-related header fields
            // such as the |Authorization| header field [RFC2616], which are
            // processed according to documents that define them.

            sb.AppendWithCrCf();

            // GET /chat HTTP/1.1
            // Host: server.example.com
            // Upgrade: websocket
            // Connection: Upgrade
            // Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
            // Sec-WebSocket-Protocol: chat, superchat
            // Sec-WebSocket-Version: 13
            // Origin: http://example.com
            var request = sb.ToString();
#if DEBUG
            _log.DebugFormat("[{0}]{1}{2}", client.RemoteEndPoint, Environment.NewLine, request);
#endif
            return Encoding.UTF8.GetBytes(request);
        }

        internal static bool VerifyOpenningHandshakeResponse(AsyncWebSocketClient client, byte[] buffer, int offset, int count, string secWebSocketKey)
        {
            BufferValidator.ValidateBuffer(buffer, offset, count, "buffer");
            if (string.IsNullOrEmpty(secWebSocketKey))
                throw new ArgumentNullException("secWebSocketKey");

            var response = Encoding.UTF8.GetString(buffer, offset, count);
#if DEBUG
            _log.DebugFormat("[{0}]{1}{2}", client.RemoteEndPoint, Environment.NewLine, response);
#endif
            try
            {
                // HTTP/1.1 101 Switching Protocols
                // Upgrade: websocket
                // Connection: Upgrade
                // Sec-WebSocket-Accept: 1tGBmA9p0DQDgmFll6P0/UcVS/E=
                // Sec-WebSocket-Protocol: chat
                Dictionary<string, string> headers;
                List<string> extensions;
                List<string> protocols;
                ParseOpenningHandshakeResponseHeaders(response, out headers, out extensions, out protocols);
                if (headers == null)
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to invalid headers.", client.RemoteEndPoint));

                // If the status code received from the server is not 101, the
                // client handles the response per HTTP [RFC2616] procedures.  In
                // particular, the client might perform authentication if it
                // receives a 401 status code; the server might redirect the client
                // using a 3xx status code (but clients are not required to follow them), etc.
                if (!headers.ContainsKey(Consts.HttpStatusCodeName))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to lack of status code.", client.RemoteEndPoint));
                if (!headers.ContainsKey(Consts.HttpStatusCodeDescription))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to lack of status description.", client.RemoteEndPoint));
                if (headers[Consts.HttpStatusCodeName] == ((int)HttpStatusCode.BadRequest).ToString())
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to bad request [{1}].",
                        client.RemoteEndPoint, headers[Consts.HttpStatusCodeName]));
                if (headers[Consts.HttpStatusCodeName] != ((int)HttpStatusCode.SwitchingProtocols).ToString())
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to expected 101 Switching Protocols but received [{1}].",
                        client.RemoteEndPoint, headers[Consts.HttpStatusCodeName]));

                // If the response lacks an |Upgrade| header field or the |Upgrade|
                // header field contains a value that is not an ASCII case-
                // insensitive match for the value "websocket", the client MUST
                // _Fail the WebSocket Connection_.
                if (!headers.ContainsKey(HttpKnownHeaderNames.Connection))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to lack of connection header item.", client.RemoteEndPoint));
                if (headers[HttpKnownHeaderNames.Connection].ToLowerInvariant() != Consts.WebSocketConnectionToken.ToLowerInvariant())
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to invalid connection header item value [{1}].",
                        client.RemoteEndPoint, headers[HttpKnownHeaderNames.Connection]));

                // If the response lacks a |Connection| header field or the
                // |Connection| header field doesn't contain a token that is an
                // ASCII case-insensitive match for the value "Upgrade", the client
                // MUST _Fail the WebSocket Connection_.
                if (!headers.ContainsKey(HttpKnownHeaderNames.Upgrade))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to lack of upgrade header item.", client.RemoteEndPoint));
                if (headers[HttpKnownHeaderNames.Upgrade].ToLowerInvariant() != Consts.WebSocketUpgradeToken.ToLowerInvariant())
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to invalid upgrade header item value [{1}].",
                        client.RemoteEndPoint, headers[HttpKnownHeaderNames.Upgrade]));

                // If the response lacks a |Sec-WebSocket-Accept| header field or
                // the |Sec-WebSocket-Accept| contains a value other than the
                // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
                // Key| (as a string, not base64-decoded) with the string "258EAFA5-
                // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
                // trailing whitespace, the client MUST _Fail the WebSocket Connection_.
                if (!headers.ContainsKey(HttpKnownHeaderNames.SecWebSocketAccept))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to lack of Sec-WebSocket-Accept header item.", client.RemoteEndPoint));
                string challenge = GetSecWebSocketAcceptString(secWebSocketKey);
                if (!headers[HttpKnownHeaderNames.SecWebSocketAccept].Equals(challenge, StringComparison.OrdinalIgnoreCase))
                    throw new WebSocketHandshakeException(string.Format(
                        "Handshake with remote [{0}] failed due to invalid Sec-WebSocket-Accept header item value [{1}].",
                        client.RemoteEndPoint, headers[HttpKnownHeaderNames.SecWebSocketAccept]));

                // If the response includes a |Sec-WebSocket-Extensions| header
                // field and this header field indicates the use of an extension
                // that was not present in the client's handshake (the server has
                // indicated an extension not requested by the client), the client
                // MUST _Fail the WebSocket Connection_.
                if (extensions != null)
                {
                    foreach (var extension in extensions)
                    {
                        // The empty string is not the same as the null value for these
                        // purposes and is not a legal value for this field.
                        if (string.IsNullOrWhiteSpace(extension))
                            throw new WebSocketHandshakeException(string.Format(
                                "Handshake with remote [{0}] failed due to empty extension.", client.RemoteEndPoint));
                    }

                    client.AgreeExtensions(extensions);
                }

                // If the response includes a |Sec-WebSocket-Protocol| header field
                // and this header field indicates the use of a subprotocol that was
                // not present in the client's handshake (the server has indicated a
                // subprotocol not requested by the client), the client MUST _Fail
                // the WebSocket Connection_.
                if (protocols != null)
                {
                    if (!protocols.Any())
                        throw new WebSocketHandshakeException(string.Format(
                            "Handshake with remote [{0}] failed due to empty sub-protocol.", client.RemoteEndPoint));
                    if (protocols.Count > 1)
                        throw new WebSocketHandshakeException(string.Format(
                            "Handshake with remote [{0}] failed due to suggest to use multiple sub-protocols.", client.RemoteEndPoint));
                    foreach (var protocol in protocols)
                    {
                        // The empty string is not the same as the null value for these
                        // purposes and is not a legal value for this field.
                        if (string.IsNullOrWhiteSpace(protocol))
                            throw new WebSocketHandshakeException(string.Format(
                                "Handshake with remote [{0}] failed due to empty sub-protocol.", client.RemoteEndPoint));
                    }

                    var suggestedProtocols = protocols.First().Split(',')
                        .Select(p => p.TrimStart().TrimEnd()).Where(p => !string.IsNullOrWhiteSpace(p));

                    if (!suggestedProtocols.Any())
                        throw new WebSocketHandshakeException(string.Format(
                            "Handshake with remote [{0}] failed due to invalid sub-protocol.", client.RemoteEndPoint));
                    if (suggestedProtocols.Count() > 1)
                        throw new WebSocketHandshakeException(string.Format(
                            "Handshake with remote [{0}] failed due to suggest to use multiple sub-protocols.", client.RemoteEndPoint));

                    // The value chosen MUST be derived
                    // from the client's handshake, specifically by selecting one of
                    // the values from the |Sec-WebSocket-Protocol| field that the
                    // server is willing to use for this connection (if any).
                    client.UseSubProtocol(suggestedProtocols.First());
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("{0}{1}{2}", client, Environment.NewLine, response);
                _log.Error(ex.Message, ex);
                throw;
            }

            return true;
        }

        private static void ParseOpenningHandshakeResponseHeaders(string response,
            out Dictionary<string, string> headers,
            out List<string> extensions,
            out List<string> protocols)
        {
            headers = new Dictionary<string, string>();

            // The |Sec-WebSocket-Extensions| header field MAY appear multiple times
            // in an HTTP request (which is logically the same as a single
            // |Sec-WebSocket-Extensions| header field that contains all values.
            // However, the |Sec-WebSocket-Extensions| header field MUST NOT appear
            // more than once in an HTTP response.
            extensions = null;
            // The |Sec-WebSocket-Protocol| header field MAY appear multiple times
            // in an HTTP request (which is logically the same as a single
            // |Sec-WebSocket-Protocol| header field that contains all values).
            // However, the |Sec-WebSocket-Protocol| header field MUST NOT appear
            // more than once in an HTTP response.
            protocols = null;

            var lines = response.Split(_headerLineSplitter).Where(l => l.Length > 0);
            foreach (var line in lines)
            {
                // HTTP/1.1 101 Switching Protocols
                // HTTP/1.1 400 Bad Request
                if (line.StartsWith(@"HTTP/"))
                {
                    var segements = line.Split(' ');
                    if (segements.Length > 1)
                    {
                        headers.Add(Consts.HttpStatusCodeName, segements[1]);

                        if (segements.Length > 2)
                        {
                            headers.Add(Consts.HttpStatusCodeDescription, segements[2]);
                        }
                    }
                }
                else
                {
                    foreach (var key in HttpKnownHeaderNames.All)
                    {
                        if (line.StartsWith(key + ":"))
                        {
                            var index = line.IndexOf(':');
                            if (index != -1)
                            {
                                var value = line.Substring(index + 1);

                                if (key == HttpKnownHeaderNames.SecWebSocketExtensions)
                                {
                                    if (extensions == null)
                                        extensions = new List<string>();
                                    extensions.Add(value.Trim());
                                }
                                else if (key == HttpKnownHeaderNames.SecWebSocketProtocol)
                                {
                                    if (protocols == null)
                                        protocols = new List<string>();
                                    protocols.Add(value.Trim());
                                }
                                else
                                {
                                    if (headers.ContainsKey(key))
                                    {
                                        headers[key] = string.Join(",", headers[key], value.Trim());
                                    }
                                    else
                                    {
                                        headers.Add(key, value.Trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private static string GetSecWebSocketAcceptString(string secWebSocketKey)
        {
            string retVal;

            using (SHA1 sha1 = SHA1.Create())
            {
                string acceptString = string.Concat(secWebSocketKey, Consts.SecWebSocketKeyGuid);
                byte[] toHash = Encoding.UTF8.GetBytes(acceptString);
                retVal = Convert.ToBase64String(sha1.ComputeHash(toHash));
            }

            return retVal;
        }
    }
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2015 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless resuired by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include <cstdlib>
#include <map>
#include <string>
#include <iostream>
#include <libgreenstack/Response.h>

#include <gtest/gtest.h>

namespace Greenstack {
    class ResponseTest : public ::testing::Test {
    };

    TEST_F(ResponseTest, Constructor) {
        Response response;
        EXPECT_EQ(std::numeric_limits<uint32_t>::max(), response.getOpaque());
        EXPECT_EQ(Opcode::InvalidOpcode, response.getOpcode());
        EXPECT_TRUE(response.getFlexHeader().isEmpty());
        EXPECT_FALSE(response.isFenceBitSet());
        EXPECT_FALSE(response.isMoreBitSet());
        EXPECT_FALSE(response.isQuietBitSet());
    }

    TEST_F(ResponseTest, EmptyEncode) {
        Response response;
        std::vector<uint8_t> data;
        response.encode(data);
        EXPECT_EQ(9, data.size());

        // opaque 4 byes == 0xffffffff
        EXPECT_EQ(0xff, data[0]);
        EXPECT_EQ(0xff, data[1]);
        EXPECT_EQ(0xff, data[2]);
        EXPECT_EQ(0xff, data[3]);

        // opcode 2 bytes 0xffff
        EXPECT_EQ(0xff, data[4]);
        EXPECT_EQ(0xff, data[5]);

        // flags 1 byte, 1
        EXPECT_EQ(0x1, data[6]);

        // Status code 2 bytes, 0xffff
        EXPECT_EQ(0xff, data[7]);
        EXPECT_EQ(0xff, data[8]);
    }

    TEST_F(ResponseTest, Opaque) {
        Response res;
        std::vector<uint8_t> data;

        res.setOpaque(0xaabbccdd);
        EXPECT_EQ(0xaabbccdd, res.getOpaque());
        res.encode(data);
        EXPECT_EQ(0xaa, data[0]);
        EXPECT_EQ(0xbb, data[1]);
        EXPECT_EQ(0xcc, data[2]);
        EXPECT_EQ(0xdd, data[3]);
    }

    TEST_F(ResponseTest, Opcode) {
        Response res;
        std::vector<uint8_t> data;

        res.setOpcode(Opcode::Mutation);
        EXPECT_EQ(Opcode::Mutation, res.getOpcode());
        res.encode(data);
        EXPECT_EQ(0x04, data[4]);
        EXPECT_EQ(0x05, data[5]);
    }

    TEST_F(ResponseTest, FenceBit) {
        Response res;
        std::vector<uint8_t> data;

        res.setFenceBit(true);
        EXPECT_TRUE(res.isFenceBitSet());
        res.encode(data);
        EXPECT_EQ(0x05, data[6]);
        res.setFenceBit(false);
        EXPECT_FALSE(res.isFenceBitSet());
        res.encode(data);
        EXPECT_EQ(0x01, data[6]);
    }

    TEST_F(ResponseTest, MoreBit) {
        Response res;
        std::vector<uint8_t> data;

        res.setMoreBit(true);
        EXPECT_TRUE(res.isMoreBitSet());
        res.encode(data);
        EXPECT_EQ(0x09, data[6]);
        res.setMoreBit(false);
        EXPECT_FALSE(res.isMoreBitSet());
        res.encode(data);
        EXPECT_EQ(0x01, data[6]);
    }

    TEST_F(ResponseTest, QuietBit) {
        Response res;
        std::vector<uint8_t> data;

        res.setQuietBit(true);
        EXPECT_TRUE(res.isQuietBitSet());
        res.encode(data);
        EXPECT_EQ(0x11, data[6]);
        res.setQuietBit(false);
        EXPECT_FALSE(res.isQuietBitSet());
        res.encode(data);
        EXPECT_EQ(0x01, data[6]);
    }

    TEST_F(ResponseTest, MultipleBits) {
        Response res;
        std::vector<uint8_t> data;

        res.setFenceBit(true);
        res.setMoreBit(true);
        res.setQuietBit(true);

        EXPECT_TRUE(res.isFenceBitSet());
        EXPECT_TRUE(res.isQuietBitSet());
        EXPECT_TRUE(res.isMoreBitSet());
        res.encode(data);
        EXPECT_EQ(0x1d, data[6]);
    }

    TEST_F(ResponseTest, FlexHeaderBit) {
        Response res;
        std::vector<uint8_t> data;
        res.getFlexHeader().setHash(32);
        res.encode(data);
        EXPECT_EQ(0x3, data[6]); // is causing the flex header bit to be added
    }

    TEST_F(ResponseTest, Status) {
        Response res;
        res.setStatus(Status::InvalidArguments);
        std::vector<uint8_t> data;
        res.encode(data);
        EXPECT_EQ(0x00, data[7]);
        EXPECT_EQ(0x01, data[8]);
    }

    TEST_F(ResponseTest, Payload) {
        Response res;
        std::vector<uint8_t> data;

        std::vector<uint8_t> payload;
        payload.resize(20);
        res.setPayload(payload);
        res.encode(data);

        EXPECT_EQ(29, data.size());
        auto iterator = data.begin();
        iterator += 9;
        EXPECT_TRUE(equal(iterator, data.end(), payload.begin()));
    }

    TEST_F(ResponseTest, Decode) {
        // We've already tested the encode functionality, so
        // we can just create a new one and encode it and see
        // that it doesn't differ...
        Response res;
        res.setOpcode(Opcode::Noop);
        res.setStatus(Status::Success);
        res.setOpaque(0xaabbccdd);
        res.setFenceBit(true);
        res.setMoreBit(true);
        res.setQuietBit(true);
        res.getFlexHeader().setHash(32);
        std::vector<uint8_t> data;
        res.encode(data);

        ByteArrayReader reader(data);

        Message *created = Message::create(reader, data.size());
        EXPECT_FALSE(dynamic_cast<Response*>(created) == 0);
        std::vector<uint8_t> data2;
        created->encode(data2);

        EXPECT_TRUE(data == data2);
        delete created;
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner.optimizations;

import com.facebook.presto.Session;
import com.facebook.presto.execution.warnings.WarningCollector;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.Subfield;
import com.facebook.presto.spi.Subfield.NestedField;
import com.facebook.presto.spi.TableHandle;
import com.facebook.presto.spi.plan.AggregationNode;
import com.facebook.presto.spi.plan.FilterNode;
import com.facebook.presto.spi.plan.OrderingScheme;
import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.spi.plan.PlanNodeIdAllocator;
import com.facebook.presto.spi.plan.ProjectNode;
import com.facebook.presto.spi.plan.TableScanNode;
import com.facebook.presto.spi.plan.TopNNode;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.spi.type.ArrayType;
import com.facebook.presto.spi.type.RowType;
import com.facebook.presto.spi.type.TypeSignature;
import com.facebook.presto.sql.planner.PlanVariableAllocator;
import com.facebook.presto.sql.planner.TypeProvider;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.DistinctLimitNode;
import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode;
import com.facebook.presto.sql.planner.plan.GroupIdNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.RowNumberNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SimplePlanRewriter;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.SpatialJoinNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.UnnestNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.relational.OriginalExpressionUtils;
import com.facebook.presto.sql.tree.Cast;
import com.facebook.presto.sql.tree.DefaultExpressionTraversalVisitor;
import com.facebook.presto.sql.tree.DereferenceExpression;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.GenericLiteral;
import com.facebook.presto.sql.tree.LongLiteral;
import com.facebook.presto.sql.tree.Node;
import com.facebook.presto.sql.tree.StringLiteral;
import com.facebook.presto.sql.tree.SubscriptExpression;
import com.facebook.presto.sql.tree.SymbolReference;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static com.facebook.presto.SystemSessionProperties.isPushdownSubfieldsEnabled;
import static com.facebook.presto.spi.Subfield.allSubscripts;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.sql.relational.OriginalExpressionUtils.castToExpression;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;

public class PushdownSubfields
        implements PlanOptimizer
{
    private final Metadata metadata;

    public PushdownSubfields(Metadata metadata)
    {
        this.metadata = requireNonNull(metadata, "metadata is null");
    }

    @Override
    public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, PlanVariableAllocator variableAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector)
    {
        requireNonNull(plan, "plan is null");
        requireNonNull(session, "session is null");
        requireNonNull(types, "types is null");

        if (!isPushdownSubfieldsEnabled(session)) {
            return plan;
        }

        return SimplePlanRewriter.rewriteWith(new Rewriter(session, metadata, types), plan, new Rewriter.Context());
    }

    private static class Rewriter
            extends SimplePlanRewriter<Rewriter.Context>
    {
        private final Session session;
        private final Metadata metadata;
        private final TypeProvider types;
        private final SubfieldExtractor subfieldExtractor;

        public Rewriter(Session session, Metadata metadata, TypeProvider types)
        {
            this.session = requireNonNull(session, "session is null");
            this.metadata = requireNonNull(metadata, "metadata is null");
            this.types = requireNonNull(types, "types is null");
            this.subfieldExtractor = new SubfieldExtractor(types);
        }

        @Override
        public PlanNode visitAggregation(AggregationNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getGroupingKeys());

            for (AggregationNode.Aggregation aggregation : node.getAggregations().values()) {
                aggregation.getArguments().forEach(expression -> subfieldExtractor.process(castToExpression(expression), context.get()));

                aggregation.getFilter().ifPresent(expression -> subfieldExtractor.process(castToExpression(expression), context.get()));

                aggregation.getOrderBy()
                        .map(OrderingScheme::getOrderByVariables)
                        .ifPresent(context.get().variables::addAll);

                aggregation.getMask().ifPresent(context.get().variables::add);
            }

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitApply(ApplyNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getCorrelation());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitDistinctLimit(DistinctLimitNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getDistinctVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitExplainAnalyze(ExplainAnalyzeNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getSource().getOutputVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitFilter(FilterNode node, RewriteContext<Context> context)
        {
            subfieldExtractor.process(castToExpression(node.getPredicate()), context.get());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Context> context)
        {
            for (Map.Entry<VariableReferenceExpression, VariableReferenceExpression> entry : node.getGroupingColumns().entrySet()) {
                context.get().addAssignment(entry.getKey(), entry.getValue());
            }

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitIndexJoin(IndexJoinNode node, RewriteContext<Context> context)
        {
            node.getCriteria().stream()
                    .map(IndexJoinNode.EquiJoinClause::getProbe)
                    .forEach(context.get().variables::add);
            node.getCriteria().stream()
                    .map(IndexJoinNode.EquiJoinClause::getIndex)
                    .forEach(context.get().variables::add);
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitJoin(JoinNode node, RewriteContext<Context> context)
        {
            node.getCriteria().stream()
                    .map(JoinNode.EquiJoinClause::getLeft)
                    .forEach(context.get().variables::add);
            node.getCriteria().stream()
                    .map(JoinNode.EquiJoinClause::getRight)
                    .forEach(context.get().variables::add);

            node.getFilter()
                    .map(OriginalExpressionUtils::castToExpression)
                    .ifPresent(expression -> subfieldExtractor.process(expression, context.get()));

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getDistinctVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitOutput(OutputNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getOutputVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitProject(ProjectNode node, RewriteContext<Context> context)
        {
            for (Map.Entry<VariableReferenceExpression, RowExpression> entry : node.getAssignments().entrySet()) {
                VariableReferenceExpression variable = entry.getKey();
                Expression expression = castToExpression(entry.getValue());

                if (expression instanceof SymbolReference) {
                    context.get().addAssignment(variable, new VariableReferenceExpression(((SymbolReference) expression).getName(), types.get(expression)));
                    continue;
                }

                Optional<Subfield> subfield = toSubfield(expression);
                if (subfield.isPresent()) {
                    context.get().addAssignment(variable, subfield.get());
                    continue;
                }

                subfieldExtractor.process(expression, context.get());
            }

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitRowNumber(RowNumberNode node, RewriteContext<Context> context)
        {
            context.get().variables.add(node.getRowNumberVariable());
            context.get().variables.addAll(node.getPartitionBy());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Context> context)
        {
            context.get().variables.add(node.getSourceJoinVariable());
            context.get().variables.add(node.getFilteringSourceJoinVariable());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitSort(SortNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getOrderingScheme().getOrderByVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Context> context)
        {
            subfieldExtractor.process(castToExpression(node.getFilter()), context.get());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitTableScan(TableScanNode node, RewriteContext<Context> context)
        {
            if (context.get().subfields.isEmpty()) {
                return node;
            }

            ImmutableMap.Builder<VariableReferenceExpression, ColumnHandle> newAssignments = ImmutableMap.builder();

            for (Map.Entry<VariableReferenceExpression, ColumnHandle> entry : node.getAssignments().entrySet()) {
                VariableReferenceExpression variable = entry.getKey();
                if (context.get().variables.contains(variable)) {
                    newAssignments.put(entry);
                    continue;
                }

                List<Subfield> subfields = context.get().findSubfields(variable.getName());

                verify(!subfields.isEmpty(), "Missing variable: " + variable);

                String columnName = getColumnName(session, metadata, node.getTable(), entry.getValue());

                // Prune subfields: if one subfield is a prefix of another subfield, keep the shortest one.
                // Example: {a.b.c, a.b} -> {a.b}
                List<Subfield> columnSubfields = subfields.stream()
                        .filter(subfield -> !prefixExists(subfield, subfields))
                        .map(Subfield::getPath)
                        .map(path -> new Subfield(columnName, path))
                        .collect(toImmutableList());

                newAssignments.put(variable, entry.getValue().withRequiredSubfields(columnSubfields));
            }

            return new TableScanNode(
                    node.getId(),
                    node.getTable(),
                    node.getOutputVariables(),
                    newAssignments.build(),
                    node.getCurrentConstraint(),
                    node.getEnforcedConstraint());
        }

        @Override
        public PlanNode visitTableWriter(TableWriterNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getColumns());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitTopN(TopNNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getOrderingScheme().getOrderByVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitTopNRowNumber(TopNRowNumberNode node, RewriteContext<Context> context)
        {
            context.get().variables.add(node.getRowNumberVariable());
            context.get().variables.addAll(node.getPartitionBy());
            context.get().variables.addAll(node.getOrderingScheme().getOrderByVariables());
            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitUnion(UnionNode node, RewriteContext<Context> context)
        {
            for (Map.Entry<VariableReferenceExpression, Collection<VariableReferenceExpression>> entry : node.getVariableMapping().asMap().entrySet()) {
                entry.getValue().forEach(variable -> context.get().addAssignment(entry.getKey(), variable));
            }

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitUnnest(UnnestNode node, RewriteContext<Context> context)
        {
            ImmutableList.Builder<Subfield> newSubfields = ImmutableList.builder();
            for (Map.Entry<VariableReferenceExpression, List<VariableReferenceExpression>> entry : node.getUnnestVariables().entrySet()) {
                VariableReferenceExpression container = entry.getKey();
                boolean found = false;

                if (isRowType(container)) {
                    for (VariableReferenceExpression field : entry.getValue()) {
                        if (context.get().variables.contains(field)) {
                            found = true;
                            newSubfields.add(new Subfield(container.getName(), ImmutableList.of(allSubscripts(), new NestedField(field.getName()))));
                        }
                        else {
                            List<Subfield> matchingSubfields = context.get().findSubfields(field.getName());
                            if (!matchingSubfields.isEmpty()) {
                                found = true;
                                matchingSubfields.stream()
                                        .map(Subfield::getPath)
                                        .map(path -> new Subfield(container.getName(), ImmutableList.<Subfield.PathElement>builder()
                                                .add(allSubscripts())
                                                .add(new NestedField(field.getName()))
                                                .addAll(path)
                                                .build()))
                                        .forEach(newSubfields::add);
                            }
                        }
                    }
                }
                else {
                    for (VariableReferenceExpression field : entry.getValue()) {
                        if (context.get().variables.contains(field)) {
                            found = true;
                            context.get().variables.add(container);
                        }
                        else {
                            List<Subfield> matchingSubfields = context.get().findSubfields(field.getName());

                            if (!matchingSubfields.isEmpty()) {
                                found = true;
                                matchingSubfields.stream()
                                        .map(Subfield::getPath)
                                        .map(path -> new Subfield(container.getName(), ImmutableList.<Subfield.PathElement>builder()
                                                .add(allSubscripts())
                                                .addAll(path)
                                                .build()))
                                        .forEach(newSubfields::add);
                            }
                        }
                    }
                }
                if (!found) {
                    context.get().variables.add(container);
                }
            }
            context.get().subfields.addAll(newSubfields.build());

            return context.defaultRewrite(node, context.get());
        }

        @Override
        public PlanNode visitWindow(WindowNode node, RewriteContext<Context> context)
        {
            context.get().variables.addAll(node.getSpecification().getPartitionBy());

            node.getSpecification().getOrderingScheme()
                    .map(OrderingScheme::getOrderByVariables)
                    .ifPresent(context.get().variables::addAll);

            node.getWindowFunctions().values().stream()
                    .map(WindowNode.Function::getFunctionCall)
                    .map(CallExpression::getArguments)
                    .flatMap(List::stream)
                    .map(OriginalExpressionUtils::castToExpression)
                    .forEach(expression -> subfieldExtractor.process(expression, context.get()));

            node.getWindowFunctions().values().stream()
                    .map(WindowNode.Function::getFrame)
                    .map(WindowNode.Frame::getStartValue)
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .forEach(context.get().variables::add);

            node.getWindowFunctions().values().stream()
                    .map(WindowNode.Function::getFrame)
                    .map(WindowNode.Frame::getEndValue)
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .forEach(context.get().variables::add);

            return context.defaultRewrite(node, context.get());
        }

        private boolean isRowType(VariableReferenceExpression variable)
        {
            return variable.getType() instanceof ArrayType && ((ArrayType) variable.getType()).getElementType() instanceof RowType;
        }

        private static boolean prefixExists(Subfield subfieldPath, Collection<Subfield> subfieldPaths)
        {
            return subfieldPaths.stream().anyMatch(path -> path.isPrefix(subfieldPath));
        }

        private static String getColumnName(Session session, Metadata metadata, TableHandle tableHandle, ColumnHandle columnHandle)
        {
            return metadata.getColumnMetadata(session, tableHandle, columnHandle).getName();
        }

        private static Optional<Subfield> toSubfield(Node expression)
        {
            ImmutableList.Builder<Subfield.PathElement> elements = ImmutableList.builder();
            while (true) {
                if (expression instanceof SymbolReference) {
                    return Optional.of(new Subfield(((SymbolReference) expression).getName(), elements.build().reverse()));
                }

                if (expression instanceof DereferenceExpression) {
                    DereferenceExpression dereference = (DereferenceExpression) expression;
                    elements.add(new NestedField(dereference.getField().getValue()));
                    expression = dereference.getBase();
                }
                else if (expression instanceof SubscriptExpression) {
                    SubscriptExpression subscript = (SubscriptExpression) expression;
                    Expression index = subscript.getIndex();
                    if (index instanceof Cast) {
                        index = ((Cast) index).getExpression();
                    }
                    if (index instanceof LongLiteral) {
                        elements.add(new Subfield.LongSubscript(((LongLiteral) index).getValue()));
                    }
                    else if (index instanceof StringLiteral) {
                        elements.add(new Subfield.StringSubscript(((StringLiteral) index).getValue()));
                    }
                    else if (index instanceof GenericLiteral) {
                        GenericLiteral literal = (GenericLiteral) index;
                        if (BIGINT.getTypeSignature().equals(TypeSignature.parseTypeSignature(literal.getType()))) {
                            elements.add(new Subfield.LongSubscript(Long.valueOf(literal.getValue())));
                        }
                        else {
                            return Optional.empty();
                        }
                    }
                    else {
                        return Optional.empty();
                    }
                    expression = subscript.getBase();
                }
                else {
                    return Optional.empty();
                }
            }
        }

        private static final class SubfieldExtractor
                extends DefaultExpressionTraversalVisitor<Void, Context>
        {
            private final TypeProvider typeProvider;

            private SubfieldExtractor(TypeProvider typeProvider)
            {
                this.typeProvider = requireNonNull(typeProvider, "typeProvider is null");
            }

            @Override
            protected Void visitSubscriptExpression(SubscriptExpression node, Context context)
            {
                Optional<Subfield> subfield = toSubfield(node);
                if (subfield.isPresent()) {
                    context.subfields.add(subfield.get());
                }
                else {
                    process(node.getBase(), context);
                    process(node.getIndex(), context);
                }
                return null;
            }

            @Override
            protected Void visitDereferenceExpression(DereferenceExpression node, Context context)
            {
                Optional<Subfield> subfield = toSubfield(node);
                if (subfield.isPresent()) {
                    context.subfields.add(subfield.get());
                }
                else {
                    process(node.getBase(), context);
                    process(node.getField(), context);
                }
                return null;
            }

            @Override
            protected Void visitSymbolReference(SymbolReference node, Context context)
            {
                context.variables.add(new VariableReferenceExpression(node.getName(), typeProvider.get(node)));
                return null;
            }
        }

        private static final class Context
        {
            // Variables whose subfields cannot be pruned
            private final Set<VariableReferenceExpression> variables = new HashSet<>();
            private final Set<Subfield> subfields = new HashSet<>();

            private void addAssignment(VariableReferenceExpression variable, VariableReferenceExpression otherVariable)
            {
                if (variables.contains(variable)) {
                    variables.add(otherVariable);
                    return;
                }

                List<Subfield> matchingSubfields = findSubfields(variable.getName());
                verify(!matchingSubfields.isEmpty(), "Missing variable: " + variable);

                matchingSubfields.stream()
                        .map(Subfield::getPath)
                        .map(path -> new Subfield(otherVariable.getName(), path))
                        .forEach(subfields::add);
            }

            private void addAssignment(VariableReferenceExpression variable, Subfield subfield)
            {
                if (variables.contains(variable)) {
                    subfields.add(subfield);
                    return;
                }

                List<Subfield> matchingSubfields = findSubfields(variable.getName());
                verify(!matchingSubfields.isEmpty(), "Missing variable: " + variable);

                matchingSubfields.stream()
                        .map(Subfield::getPath)
                        .map(path -> new Subfield(subfield.getRootName(), ImmutableList.<Subfield.PathElement>builder()
                                .addAll(subfield.getPath())
                                .addAll(path)
                                .build()))
                        .forEach(subfields::add);
            }

            private List<Subfield> findSubfields(String rootName)
            {
                return subfields.stream()
                        .filter(subfield -> rootName.equals(subfield.getRootName()))
                        .collect(toImmutableList());
            }
        }
    }
}


text:
import * as jeeves from '../services/jeeves';
import * as bone from '../services/bone';
import * as martinez from '../services/martinez';
import * as bronas from '../services/bronas';
import * as boegivar from '../services/boegivar';
import * as tourettes from '../services/tourettes';

export function handleBoegivar(bot, chatId, userFirstName) {
  const reply = boegivar.sayBoegivar(userFirstName);
  bot.sendMessage(chatId, reply);
}

export function handleBone(bot, chatId) {
  const reply = bone.sayBone();
  bot.sendMessage(chatId, reply);
}

export function handleBronas(bot, chatId) {
  const reply = bronas.sayBronas();
  bot.sendMessage(chatId, reply);
}

export function handleGreeting(bot, chatId, userFirstName) {
  const reply = jeeves.getGreeting(userFirstName);
  bot.sendMessage(chatId, reply);
}

export function handleMartinez(bot, chatId) {
  const reply = martinez.sayMartinez();
  bot.sendMessage(chatId, reply);
}

export function handleRandom(bot, chatId) {
  const reply = jeeves.getFucker();
  bot.sendMessage(chatId, reply);
}

export function handleTourettes(bot, chatId, text) {
  const reply = tourettes.sayTourettes(text);
  bot.sendMessage(chatId, reply);
}

export function handleHelp(bot, chatId) {
  const reply = jeeves.getHelp();
  bot.sendMessage(chatId, reply);
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<configuration>

  <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <SMTPHost>${smtpHost}</SMTPHost>
    <To>${to}</To>
    <From>${from}</From>
    <Subject>%logger{20} - %m</Subject>
    <Layout class="ch.qos.logback.classic.html.HTMLLayout"/>
  </appender>

  <root level="debug">
    <appender-ref ref="EMAIL" />
  </root>
</configuration>


text:
namespace eja
{
	class message;

	using message_list = std::deque<std::shared_ptr<message>>;

	class message : public object, public mode<u8>
	{
	protected:
		std::string m_id;
		std::string m_origin;
		string_deque m_clients;
		string_ptr m_data;
		message_type m_type = message_type::none;

	public:
		using ptr = std::shared_ptr<message>;

	protected:
		message() { }
		explicit message(const message& msg) : object(msg), mode<u8>(msg), m_id(msg.m_id), m_clients(msg.m_clients), m_origin(msg.m_origin), m_data(msg.m_data), m_type(msg.m_type) { }
		explicit message(const message_type& type) : m_type(type) { }
		explicit message(const message_type& type, const u8 bits) : mode<u8>(bits), m_type(type) { }
		explicit message(const u8 bits) : mode<u8>(bits) { }

		// Operator
		message& operator=(const message& msg);

	public:
		// Interface
		virtual void clear() override;

		// Utility
		void add(const std::string& client) { m_clients.push_back(client); }
		void add(const string_deque& clients) { m_clients.insert(m_clients.end(), clients.begin(), clients.end()); }

		// Has
		bool has_id() const { return !m_id.empty(); }
		bool has_origin() const { return !m_origin.empty(); }
		bool has_data() const { return m_data != nullptr; }
		bool has_type() const { return m_type != message_type::none; }

		bool has_client() const { return m_clients.size() == 1; }
		bool has_clients() const { return !m_clients.empty(); }

		// Set
		void set_id() { m_id.clear(); }
		void set_id(std::string&& id) { m_id = std::move(id); }
		void set_id(const std::string& id) { m_id = id; }
		void set_id(const void* id, const size_t size) { m_id.assign(reinterpret_cast<const char*>(id), size); }
		void set_id(const char* id) { m_id.assign(id, strlen(id)); }

		void set_client() { m_clients.clear(); }
		void set_client(const std::string& client) { m_clients.assign(1, client); }

		void set_clients() { m_clients.clear(); }
		void set_clients(const string_deque& clients) { m_clients = clients; }

		void set_origin() { m_origin.clear(); }
		void set_origin(std::string&& origin) { m_origin = std::move(origin); }
		void set_origin(const std::string& origin) { m_origin = origin; }
		void set_origin(const void* origin, const size_t size) { m_origin.assign(reinterpret_cast<const char*>(origin), size); }
		void set_origin(const char* origin) { m_origin.assign(origin, strlen(origin)); }

		void set_data() { m_data.reset(); }
		void set_data(const string_ptr& ptr) { m_data = ptr; }
		void set_data(const void* data, const size_t size) { m_data = std::make_shared<std::string>(reinterpret_cast<const char*>(data), size); }
		void set_data(std::string&& data) { m_data = std::make_shared<std::string>(std::move(data)); }
		void set_data(const std::string& str) { m_data = std::make_shared<std::string>(str); }
		void set_data(const char* psz) { m_data = std::make_shared<std::string>(psz); }

		void set_type(const message_type type) { m_type = type; }

		// Get
		const std::string& get_id() const { return m_id; }
		const std::string& get_origin() const { return m_origin; }
		const string_ptr& get_data() const { return m_data; }
		message_type get_type() const { return m_type; }

		const std::string& get_client() const { return m_clients.at(0); }
		const string_deque& get_clients() const { return m_clients; }

		MSGPACK_DEFINE(m_mode, m_id, m_clients, m_origin, m_data);
	};

	// Operator
	inline message& message::operator=(const message& msg)
	{
		if (this != &msg)
		{
			object::operator=(msg);
			mode<u8>::operator=(msg);

			m_id = msg.m_id;
			m_clients = msg.m_clients;
			m_origin = msg.m_origin;
			m_data = msg.m_data;
			m_type = msg.m_type;
		}

		return *this;
	}

	// Factory
	template <message_type T>
	class message_impl final : public message
	{
		make_factory(message_impl);

	public:
		message_impl() : message(T) { }

		MSGPACK_DEFINE(MSGPACK_BASE(message));
	};
}

#endif


text:
"""
This module contains all style configuration for rendering charts. Setting any
of these variables will change how charts are rendered.
"""

# CHART

#: Default chart width
default_chart_width = 800

#: Default chart height
default_chart_height = 600

#: Chart background color
background_color = '#f9f9f9'

#: Chart margin as a percent of chart width
margin = 0.05

# CHART TITLE

#: Chart title text color
title_color = '#333'

#: Chart title font
title_font_family = 'Monaco'

#: Chart title font size
title_font_size = 16

#: Approximate glyph height of the title font
title_font_char_height = 16

#: Approximate glyph width of the title font
title_font_char_width = 9

#: Gap between title and rest of chart
title_gap = 4

# LEGEND

#: Chart legend text color
legend_color = '#666'

#: Chart legend font
legend_font_family = 'Monaco'

#: Chart legend font size
legend_font_size = 14

#: Approximate glyph height of the legend font
legend_font_char_height = 14

#: Approximate glyph width of the legend font
legend_font_char_width = 8

#: Gap between legend and rest of chart
legend_gap = 4

#: Size of the bubble next to an legend item
legend_bubble_size = 10

#: Offset from the top of the glyph
legend_bubble_offset = 4

# AXIS

#: Axis title text color
axis_title_color = '#666'

#: Axis title font
axis_title_font_family = 'Monaco'

#: Axis title font size
axis_title_font_size = 14

#: Approximate glyph height of the axis title font
axis_title_font_char_height = 14

#: Approximate glyph width of the axis title font
axis_title_font_char_width = 8

#: Gap between axis title and rest of chart
axis_title_gap = 16

# TICKS

#: Width of a tick mark
tick_width = 1

#: Length of a tick mark
tick_size = 4

#: Color of tick marks
tick_color = '#eee'

#: Color of the zero tick mark
zero_color = '#a8a8a8'

# TICK LABELS

#: Color of tick label text
label_color = '#9c9c9c'

#: Tick label font
tick_font_family = 'Monaco'

#: Tick label font size
tick_font_size = 14

#: Approximate glyph height of the tick label font
tick_font_char_height = 14

#: Approximate glyph width of the tick label font
tick_font_char_width = 8

# SERIES

#: Default sequence of :class:`.Shape` colors
default_series_colors = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00']

#: Default :class:`.Dots` radius
default_dot_radius = 3

#: Default :class:`.Line` width
default_line_width = 2


text:
'use strict';

/**
 * @ngdoc service
 * @name webClientSideApp.LowPass
 * @description
 * # LowPass
 * Factory in the webClientSideApp.
 */
angular.module('webClientSideApp')
  .factory('LowPass', function (AbstractSoundnode, NodeParameter) {
    // Service logic
    function LowPass() {}
    LowPass.prototype = Object.create(AbstractSoundnode.prototype);

    LowPass.prototype.type = 'lowpass';

    LowPass.prototype.initNode = function(audioContext) {
      this.output = audioContext.createGain();
      this.input = audioContext.createGain();

      this.lowpass = audioContext.createBiquadFilter();
      this.lowpass.type = 'lowpass';

      this.input.connect(this.lowpass);
      this.lowpass.connect(this.output);

      this.output.gain.value = 1;
      this.input.gain.value = 1;

      this.parameters[0] = new NodeParameter();
      this.parameters[0].name = 'frequency';
      this.parameters[0].min = 20;
      this.parameters[0].max = 20000;
      this.parameters[0].step = 1;

      this.parameters[1] = new NodeParameter();
      this.parameters[1].name = 'Q';
      this.parameters[1].min = 1;
      this.parameters[1].max = 1000;
      this.parameters[1].step = 1;

      if(typeof this.value.frequency === 'undefined' || this.value.frequency === null) {
        this.lowpass.frequency.value = 440;
        this.value.frequency = 440;
      } else {
        this.lowpass.frequency.value = this.value.frequency;
      }
      if(typeof this.value.Q === 'undefined' || this.value.Q === null) {
        this.lowpass.Q.value = 0;
        this.value.Q = 0;
      } else {
        this.lowpass.Q.value = this.value.Q;
      }
    };
    LowPass.prototype.setValue = function() {
      this.value.frequency = this.lowpass.frequency.value;
      this.value.gain = this.lowpass.gain.value;
    };
    LowPass.prototype.setParameters = function(paramName) {
      this.lowpass[paramName].value = this.value[paramName];
    };
    LowPass.prototype.getInput = function() {
      return this.lowpass;
    };
    LowPass.prototype.getOutput = function() {
      return this.lowpass;
    };

    // Public API here
    return LowPass;
  });


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barcamp 2015</title>

    <link rel="stylesheet" type="text/css" href="fonts/feather/style.css">

    <link rel="stylesheet" type="text/css" href="css/demo.css" />

    <link rel="stylesheet" type="text/css" href="css/component.css" />
    <link rel="stylesheet" type="text/css" href="css/animate.css" />

CHATEXPLORE POWER OF SOCKET

PAINTINGMULTIPLAYER PAINTING GAME

ALIEN DESTROYERREMOTING CONTROL FROM MOBILE

                <button class="button button--nav-prev">Previous product
                </button>
                <button class="button button--zoom">View details
                </button>
                <button class="button button--nav-next">Next product
                </button>

                <canvas id="myCanvas" style="position:absolute;z-index:4;"></canvas>

RED

PINK

PURPLE

DEEP PURPLE

INDIGO

BLUE

LIGHT BLUE

CYAN

BROWN

DEEP ORANGE

GREEN

LIGHT GREEN

LIME

YELLOW

AMBER

            <button class="button button--close">Close content
            </button>
            <button class="color-tool">

COLOR

            </button>
            <button class="color-clear">

CLEAR

            </button>


text:
set -e

__WARNING_LINE_1="DO NOT MODIFY"
__WARNING_LINE_2="Generated by /docker-entrypoint-scripts/generate-nginx-conf-includes/brotli_min_length.conf.sh"

printf "%b" "####\n##  ${__WARNING_LINE_1}\n##  ${__WARNING_LINE_2}\n####\n\n" \
  > ${NGINX__BROTLI_MIN_LENGTH__CONF_FILE_PATH}
printf "%b" "brotli_min_length  ${NGINX__BROTLI_MIN_LENGTH};\n" \
  >> ${NGINX__BROTLI_MIN_LENGTH__CONF_FILE_PATH}


text:
#include <aws/core/utils/UUID.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/crypto/Factories.h>
#include <aws/core/utils/crypto/SecureRandom.h>
#include <iomanip>

namespace Aws
{
    namespace Utils
    {
        static const size_t UUID_STR_SIZE = 0x24u; // 36 characters
        static const size_t VERSION_LOCATION = 0x06u;
        static const size_t VARIANT_LOCATION = 0x08u;
        static const unsigned char VERSION = 0x40u;
        static const unsigned char VERSION_MASK = 0x0Fu;
        static const unsigned char VARIANT = 0x80u;
        static const unsigned char VARIANT_MASK = 0x3Fu;

        static void hexify(Aws::String& ss, const unsigned char* toWrite, size_t min, size_t max)
        {
            for (size_t i = min; i < max; ++i)
            {
                ss.push_back("0123456789ABCDEF"[toWrite[i] >> 4]);
                ss.push_back("0123456789ABCDEF"[toWrite[i] & 0x0F]);
            }
        }

        UUID::UUID(const Aws::String& uuidToConvert)
        {
            //GUID has 2 characters per byte + 4 dashes = 36 bytes
            assert(uuidToConvert.length() == UUID_STR_SIZE);
            memset(m_uuid, 0, sizeof(m_uuid));
            Aws::String escapedHexStr(uuidToConvert);
            StringUtils::Replace(escapedHexStr, "-", "");
            assert(escapedHexStr.length() == UUID_BINARY_SIZE * 2);
            ByteBuffer&& rawUuid = HashingUtils::HexDecode(escapedHexStr);
            memcpy(m_uuid, rawUuid.GetUnderlyingData(), rawUuid.GetLength());
        }

        UUID::UUID(const unsigned char toCopy[UUID_BINARY_SIZE])
        {
            memcpy(m_uuid, toCopy, sizeof(m_uuid));
        }

        UUID::operator Aws::String() const
        {
            Aws::String ss;
            ss.reserve(UUID_STR_SIZE);
            hexify(ss, m_uuid, 0, 4);
            ss.push_back('-');

            hexify(ss, m_uuid, 4, 6);
            ss.push_back('-');

            hexify(ss, m_uuid, 6, 8);
            ss.push_back('-');

            hexify(ss, m_uuid, 8, 10);
            ss.push_back('-');

            hexify(ss, m_uuid, 10, 16);

            return ss;
        }

        UUID UUID::RandomUUID()
        {
            auto secureRandom = Crypto::CreateSecureRandomBytesImplementation();
            assert(secureRandom);

            unsigned char randomBytes[UUID_BINARY_SIZE];
            memset(randomBytes, 0, UUID_BINARY_SIZE);
            secureRandom->GetBytes(randomBytes, UUID_BINARY_SIZE);
            //Set version bits to 0100
            //https://tools.ietf.org/html/rfc4122#section-4.1.3
            randomBytes[VERSION_LOCATION] = (randomBytes[VERSION_LOCATION] & VERSION_MASK) | VERSION;
            //set variant bits to 10
            //https://tools.ietf.org/html/rfc4122#section-4.1.1
            randomBytes[VARIANT_LOCATION] = (randomBytes[VARIANT_LOCATION] & VARIANT_MASK) | VARIANT;

            return UUID(randomBytes);
        }
    }
}


text:
package com.example.cloud.controller

import com.example.cloud.model.User
import com.example.cloud.repository.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation._
import scala.collection.JavaConversions._

@RequestMapping(path = Array("/user"))
@RestController
class UserController {
  @Autowired
  var userRepository: UserRepository = _

  @RequestMapping(path = Array("/{userId}"))
  def getUser(@PathVariable("userId") userId: String): User = {
    userRepository.findOne(userId)
  }

  @RequestMapping(path = Array("/"))
  def getUsersByPage(@RequestParam("page") page: Int = 0): Seq[User] = {
    userRepository.findAll()
  }

  @RequestMapping(path = Array("/"), method = Array(RequestMethod.POST))
  def saveUser(@RequestBody user: User): Unit = {
    userRepository.save(user)
  }
}


text:
function varargout = newface(varargin)
% NEWFACE M-file for newface.fig
%      NEWFACE, by itself, creates a new NEWFACE or raises the existing
%      singleton*.
%
%      H = NEWFACE returns the handle to a new NEWFACE or the handle to
%      the existing singleton*.
%
%      NEWFACE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in NEWFACE.M with the given input arguments.
%
%      NEWFACE('Property','Value',...) creates a new NEWFACE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before newface_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to newface_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Copyright 2002-2003 The MathWorks, Inc.

% Edit the above text to modify the response to help newface

% Last Modified by GUIDE v2.5 01-Oct-2010 12:19:04

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @newface_OpeningFcn, ...
                   'gui_OutputFcn',  @newface_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before newface is made visible.
function newface_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to newface (see VARARGIN)

% Choose default command line output for newface
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes newface wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = newface_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in input.
function input_Callback(hObject, eventdata, handles)
% hObject    handle to input (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[FileName,PathName] = uigetfile('*.pgm','Select any image ');
if(PathName~=0)
y= [PathName,FileName];
img=imread(y);
%img=imread('C:\SUGEEV (H)\naveen project\Pgm\database\s1\1.pgm');
%a=img;
axes(handles.axes1)
imshow(img)
% --- Executes on button press in clear.
function clear_Callback(hObject, eventdata, handles)
% hObject    handle to clear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in processing.
function processing_Callback(hObject, eventdata, handles)
% hObject    handle to processing (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


text:
package antlr.preprocessor;

/* ANTLR Translator Generator
 * Project led by Terence Parr at http://www.jGuru.com
 * Software rights: http://www.antlr.org/license.html
 *
 * $Id: //depot/code/org.antlr/release/antlr-2.7.5/antlr/preprocessor/Option.java#1 $
 */

import antlr.collections.impl.Vector;

class Option {
    protected String name;
    protected String rhs;
    protected Grammar enclosingGrammar;

    public Option(String n, String rhs, Grammar gr) {
        name = n;
        this.rhs = rhs;
        setEnclosingGrammar(gr);
    }

    public Grammar getEnclosingGrammar() {
        return enclosingGrammar;
    }

    public String getName() {
        return name;
    }

    public String getRHS() {
        return rhs;
    }

    public void setEnclosingGrammar(Grammar g) {
        enclosingGrammar = g;
    }

    public void setName(String n) {
        name = n;
    }

    public void setRHS(String rhs) {
        this.rhs = rhs;
    }

    public String toString() {
        return "\t" + name + "=" + rhs;
    }
}


text:
#include "WeatherBasedSimulationString.h"

namespace WBSF
{

	const char* CDimension::DIMENSION_NAME[NB_DIMENSION] = { "Location", "Parameter", "Replication", "Temporal", "Variable" };

	StringVector CDimension::DIMENSION_TITLE;
	const char * CDimension::GetDimensionTitle(size_t d)
	{
		ASSERT(d >= 0 && d < NB_DIMENSION);

		if (DIMENSION_TITLE.empty())
			DIMENSION_TITLE = Tokenize(GetString(IDS_SIM_RESULT_HEAD), ";|");

		return DIMENSION_TITLE.empty() ? GetDimensionName(d) : DIMENSION_TITLE[d].c_str();
	}

}


text:
/*
 *
 * LegendShop 多用户商城系统
 *
 *  版权所有,并保留所有权利。
 *
 */
package com.legendshop.core.security;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.RedirectStrategy;

import com.legendshop.core.AttributeKeys;
import com.legendshop.core.UserManager;
import com.legendshop.core.constant.FunctionEnum;
import com.legendshop.util.AppUtils;

/**
 * LegendShop 版权所有 2009-2011,并保留所有权利。
 *
 * 官方网站:http://www.legendesign.net
 */
public class OriginUrlRedirectStrategy implements RedirectStrategy {

	/** The logger. */
	protected final Log logger = LogFactory.getLog(getClass());

	/** The context relative. */
	private boolean contextRelative;

	// 如果用户是一个商家,则跳转到后台
	private boolean forwardToBackEndForBusiness;

	/**
	 * Redirects the response to the supplied URL.
	 * <p>
	 * If <tt>contextRelative</tt> is set, the redirect value will be the value
	 * after the request context path. Note that this will result in the loss of
	 * protocol information (HTTP or HTTPS), so will cause problems if a
	 * redirect is being performed to change to HTTPS, for example.
	 *
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param url
	 *            the url
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */

	public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
		String service = request.getParameter(AttributeKeys.RETURN_URL);
		if (AppUtils.isNotBlank(service)) {
			response.sendRedirect(service);
			return;
		}
		// 如果用户是一个商家,则跳转到后台
		if (forwardToBackEndForBusiness) {
			if (UserManager.hasFunction(request, FunctionEnum.FUNCTION_F_ADMIN.value())) {
				response.sendRedirect(request.getContextPath() + "/admin/index");
				return;
			}
		}

		String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
		redirectUrl = response.encodeRedirectURL(redirectUrl);

		if (logger.isDebugEnabled()) {
			logger.debug("Redirecting to '" + redirectUrl + "'");
		}

		response.sendRedirect(redirectUrl);
	}

	/**
	 * Calculate redirect url.
	 *
	 * @param contextPath
	 *            the context path
	 * @param url
	 *            the url
	 * @return the string
	 */
	private String calculateRedirectUrl(String contextPath, String url) {
		if (url != null && !url.startsWith("http://")) {
			if (contextRelative) {
				return url;
			} else {
				return contextPath + url;
			}
		}

		// Full URL, including http(s)://

		if (!contextRelative) {
			return url;
		}

		// Calculate the relative URL from the fully qualified URL, minus the
		// scheme and base context.
		url = url.substring(url.indexOf("://") + 3); // strip off scheme
		url = url.substring(url.indexOf(contextPath) + contextPath.length());

		if (url.length() > 1 && url.charAt(0) == '/') {
			url = url.substring(1);
		}

		return url;
	}

	/**
	 * If <tt>true</tt>, causes any redirection URLs to be calculated minus the
	 * protocol and context path (defaults to <tt>false</tt>).
	 *
	 * @param useRelativeContext
	 *            the new context relative
	 */
	public void setContextRelative(boolean useRelativeContext) {
		this.contextRelative = useRelativeContext;
	}

	/**
	 * @param forwardToBackEndForBusiness
	 *            the forwardToBackEndForBusiness to set
	 */
	public void setForwardToBackEndForBusiness(boolean forwardToBackEndForBusiness) {
		this.forwardToBackEndForBusiness = forwardToBackEndForBusiness;
	}

}