text:
using System;
using System.Runtime.InteropServices;
using Newbe.Mahua.CQP.MahuaEventOutputs;

namespace Newbe.Mahua.CQP.Native
{
    /// <summary>
    /// 暴露非托管代码的api集合
    /// </summary>
    public sealed class PluginApiExporter : IPluginApiExporter
    {
        private const string CoolApiVersion = "9";

        /// <summary>
        /// 此函数会在插件被开启时发生。
        /// </summary>
        /// <returns>返回处理过程是否成功的值。</returns>
        [DllExport("_eventEnable", CallingConvention.StdCall)]
        public static int Enabled()
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new Enabled());
            return 0;
        }

        /// <summary>
        /// 此函数会在插件被禁用时发生。
        /// </summary>
        /// <returns>返回处理过程是否成功的值。</returns>
        [DllExport("_eventDisable", CallingConvention.StdCall)]
        public static int Disabled()
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new Disabled());
            return 0;
        }

        /// <summary>
        /// 向酷Q提供插件信息。
        /// </summary>
        /// <returns>一个固定格式字符串。</returns>
        [DllExport("AppInfo", CallingConvention.StdCall)]
        public static string AppInfo()
        {
            return $"{CoolApiVersion},{AgentInfo.Instance.Id}".ToLowerInvariant();
        }

        /// <summary>
        /// 获取此插件的AuthCode。
        /// </summary>
        /// <param name="authcode">由酷Q提供的AuthCode。</param>
        /// <returns></returns>
        [DllExport("Initialize", CallingConvention.StdCall)]
        public static int Initialize(int authcode)
        {
            CqpAuthCodeContainer.StaticAuthCode = authcode;
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new Initialize
            {
                AuthCode = authcode
            });
            return 0;
        }

        /// <summary>
        /// 此函数会在酷Q退出时被调用。
        /// </summary>
        /// <returns></returns>
        [DllExport("_eventExit", CallingConvention.StdCall)]
        public static int CoolQExited()
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new CoolQExited());
            return 0;
        }

        /// <summary>
        /// 处理私聊消息。
        /// </summary>
        /// <param name="subType">私聊消息类型。11代表消息来自好友;1代表消息来自在线状态;2代表消息来自群;3代表消息来自讨论组。</param>
        /// <param name="msgId">消息Id。</param>
        /// <param name="fromQQ">发送此消息的QQ号码。</param>
        /// <param name="msg">消息的内容。</param>
        /// <param name="font">消息所使用的字体。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventPrivateMsg", CallingConvention.StdCall)]
        public static int ProcessPrivateMessage(int subType, int msgId, long fromQQ, string msg, int font)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessPrivateMessage
            {
                SubType = subType,
                FromQQ = fromQQ,
                Msg = msg,
                MsgId = msgId,
                Font = font,
            });
            return 0;
        }

        /// <summary>
        /// 处理群聊消息。
        /// </summary>
        /// <param name="subType">消息类型,目前固定为1。</param>
        /// <param name="msgId">消息Id</param>
        /// <param name="fromGroup">消息来源群号。</param>
        /// <param name="fromQQ">发送此消息的QQ号码。</param>
        /// <param name="fromAnonymous">发送此消息的匿名用户。</param>
        /// <param name="msg">消息内容。</param>
        /// <param name="font">消息所使用字体。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventGroupMsg", CallingConvention.StdCall)]
        public static int ProcessGroupMessage(
            int subType,
            int msgId,
            long fromGroup,
            long fromQQ,
            string fromAnonymous,
            string msg,
            int font)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessGroupMessage
            {
                SubType = subType,
                Message = msg,
                FromGroup = fromGroup,
                FromAnonymous = fromAnonymous,
                FromQQ = fromQQ,
                MsgId = msgId,
                Font = font,
            });
            return 0;
        }

        /// <summary>
        /// 处理讨论组消息。
        /// </summary>
        /// <param name="subType">消息类型,目前固定为1。</param>
        /// <param name="msgId">消息Id</param>
        /// <param name="fromDiscuss">消息来源讨论组号。</param>
        /// <param name="fromQQ">发送此消息的QQ号码。</param>
        /// <param name="msg">消息内容。</param>
        /// <param name="font">消息所使用字体。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventDiscussMsg", CallingConvention.StdCall)]
        public static int ProcessDiscussGroupMessage(
            int subType,
            int msgId,
            long fromDiscuss,
            long fromQQ,
            string msg,
            int font)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessDiscussGroupMessage
            {
                SubType = subType,
                Msg = msg,
                FromDiscuss = fromDiscuss,
                FromQQ = fromQQ,
                MsgId = msgId,
                Font = font,
            });
            return 0;
        }

        /// <summary>
        /// 处理群文件上传事件。
        /// </summary>
        /// <param name="subType">消息类型,目前固定为1。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromGroup">事件来源群号。</param>
        /// <param name="fromQQ">上传此文件的QQ号码。</param>
        /// <param name="file">上传的文件的信息。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventGroupUpload", CallingConvention.StdCall)]
        public static int ProcessGroupUpload(int subType, int sendTime, long fromGroup, long fromQQ, string file)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessGroupUpload
            {
                SubType = subType,
                SendTime = sendTime,
                FromGroup = fromGroup,
                FromQQ = fromQQ,
                File = file
            });
            return 0;
        }

        /// <summary>
        /// 处理群管理员变动事件。
        /// </summary>
        /// <param name="subType">事件类型。1为被取消管理员,2为被设置管理员。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromGroup">事件来源群号。</param>
        /// <param name="target">被操作的QQ。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventSystem_GroupAdmin", CallingConvention.StdCall)]
        public static int ProcessGroupAdminChange(int subType, int sendTime, long fromGroup, long target)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessGroupAdminChange
            {
                SubType = subType,
                SendTime = sendTime,
                Target = target,
                FromGroup = fromGroup
            });
            return 0;
        }

        /// <summary>
        /// 处理群成员数量减少事件。
        /// </summary>
        /// <param name="subType">事件类型。1为群员离开;2为群员被踢为;3为自己(即登录号)被踢。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromGroup">事件来源群号。</param>
        /// <param name="fromQQ">事件来源QQ。</param>
        /// <param name="target">被操作的QQ。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventSystem_GroupMemberDecrease", CallingConvention.StdCall)]
        public static int ProcessGroupMemberDecrease(
            int subType,
            int sendTime,
            long fromGroup,
            long fromQQ,
            long target)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessGroupMemberDecrease
            {
                SubType = subType,
                SendTime = sendTime,
                Target = target,
                FromGroup = fromGroup,
                FromQQ = fromQQ,
            });
            return 0;
        }

        /// <summary>
        /// 处理群成员添加事件。
        /// </summary>
        /// <param name="subType">事件类型。1为管理员已同意;2为管理员邀请。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromGroup">事件来源群号。</param>
        /// <param name="fromQQ">事件来源QQ。</param>
        /// <param name="target">被操作的QQ。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventSystem_GroupMemberIncrease", CallingConvention.StdCall)]
        public static int ProcessGroupMemberIncrease(
            int subType,
            int sendTime,
            long fromGroup,
            long fromQQ,
            long target)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessGroupMemberIncrease
            {
                SubType = subType,
                SendTime = sendTime,
                Target = target,
                FromGroup = fromGroup,
                FromQQ = fromQQ,
            });
            return 0;
        }

        /// <summary>
        /// 处理好友已添加事件。
        /// </summary>
        /// <param name="subType">事件类型。固定为1。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromQQ">事件来源QQ。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventFriend_Add", CallingConvention.StdCall)]
        public static int ProcessFriendsAdded(int subType, int sendTime, long fromQQ)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessFriendsAdded
            {
                SubType = subType,
                SendTime = sendTime,
                FromQQ = fromQQ
            });
            return 0;
        }

        /// <summary>
        /// 处理好友添加请求。
        /// </summary>
        /// <param name="subType">事件类型。固定为1。</param>
        /// <param name="sendTime">事件发生时间的时间戳。</param>
        /// <param name="fromQQ">事件来源QQ。</param>
        /// <param name="msg">附言内容。</param>
        /// <param name="font">消息所使用字体。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventRequest_AddFriend", CallingConvention.StdCall)]
        public static int ProcessAddFriendRequest(int subType, int sendTime, long fromQQ, string msg, int font)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessAddFriendEventOutput
            {
                SubType = subType,
                SendTime = sendTime,
                FromQQ = fromQQ,
                Msg = msg,
                Font = font,
            });
            return 0;
        }

        /// <summary>
        /// 处理加群请求。
        /// </summary>
        /// <param name="subType">请求类型。1为他人申请入群;2为自己(即登录号)受邀入群。</param>
        /// <param name="sendTime">请求发送时间戳。</param>
        /// <param name="fromGroup">要加入的群的群号。</param>
        /// <param name="fromQQ">发送此请求的QQ号码。</param>
        /// <param name="msg">附言内容。</param>
        /// <param name="responseMark">用于处理请求的标识。</param>
        /// <returns>是否拦截消息的值,0为忽略消息,1为拦截消息。</returns>
        [DllExport("_eventRequest_AddGroup", CallingConvention.StdCall)]
        public static int ProcessJoinGroupRequest(
            int subType,
            int sendTime,
            long fromGroup,
            long fromQQ,
            string msg,
            string responseMark)
        {
            PluginInstanceManager.GetInstance().HandleMahuaOutput(new ProcessJoinGroupEventOutput
            {
                SubType = subType,
                SendTime = sendTime,
                FromQQ = fromQQ,
                FromGroup = fromGroup,
                Msg = msg,
                ResponseMark = responseMark,
            });
            return 0;
        }

        /// <summary>
        /// 设置中心菜单
        /// </summary>
        /// <returns></returns>
        [DllExport("_menuA", CallingConvention.StdCall)]
        public static int ProcessMenuClickA()
        {
            // TODO 点击设置中心,暂时没有任何作用
            Console.WriteLine("nothing");
            return 0;
        }
    }
}


text:
ConvertFrom-StringData @'
###PSLOC
GroupWithName=Group: {0}
RemoveOperation=Remove
AddOperation=Add
SetOperation=Set
ConfigurationStarted=Configuration of group {0} started.
ConfigurationCompleted=Configuration of group {0} completed successfully.
GroupCreated=Group {0} created successfully.
GroupUpdated=Group {0} properties updated successfully.
GroupRemoved=Group {0} removed successfully.
NoConfigurationRequired=Group {0} exists on this node with the desired properties. No action required.
NoConfigurationRequiredGroupDoesNotExist=Group {0} does not exist on this node. No action required.
CouldNotFindPrincipal=Could not find a principal with the provided name [{0}]
MembersAndIncludeExcludeConflict=The {0} and {1} and/or {2} parameters conflict. The {0} parameter should not be used in any combination with the {1} and {2} parameters.
MembersIsNull=The Members parameter value is null. The {0} parameter must be provided if neither {1} nor {2} is provided.
IncludeAndExcludeConflict=The principal {0} is included in both {1} and {2} parameter values. The same principal must not be included in both {1} and {2} parameter values.
InvalidGroupName=The name {0} cannot be used. Names may not consist entirely of periods and/or spaces, or contain these characters: {1}
GroupExists=A group with the name {0} exists.
GroupDoesNotExist=A group with the name {0} does not exist.
PropertyMismatch=The value of the {0} property is expected to be {1} but it is {2}.
MembersNumberMismatch=Property {0}. The number of provided unique group members {1} is different from the number of actual group members {2}.
MembersMemberMismatch=At least one member {0} of the provided {1} parameter does not have a match in the existing group {2}.
MemberToExcludeMatch=At least one member {0} of the provided {1} parameter has a match in the existing group {2}.
ResolvingLocalAccount=Resolving {0} as a local account.
RedirectDomain=Redirecting to domain {0} for account {1}.
ResolvingDomainAccount=Resolving {0} in the {1} domain.
ResolvingUser=Resolving {0} as a user.
ResolvingGroup=Resolving {0} as a group.
ResolvingComputer=Resolving {0} as a computer.
DomainCredentialsRequired=Credentials are required to resolve the domain account {0}.
###PSLOC

'@

redpajama_set_name: RedPajamaGithub


text:
LEVEL = ../../..
LIBRARYNAME = LLVMRISCVCodeGen
TARGET = RISCV

# Make sure that tblgen is run, first thing.
BUILT_SOURCES = RISCVGenRegisterInfo.inc \
		RISCVGenAsmWriter.inc \
		RISCVGenAsmMatcher.inc \
		RISCVGenCodeEmitter.inc \
		RISCVGenInstrInfo.inc \
		RISCVGenDAGISel.inc \
		RISCVGenSubtargetInfo.inc \
		RISCVGenCallingConv.inc \
		RISCVGenMCCodeEmitter.inc

DIRS = InstPrinter AsmParser TargetInfo MCTargetDesc

include $(LEVEL)/Makefile.common


text:
{% extends "base_registro.html" %}

{% block title %}Alta de Dependencia Funcional{% endblock %}

{% block content %}

Alta de Dependencia Funcional

{% if flash %}
    {% include "flashes.html" %}
{% endif %}

{% include "registro/dependencia_funcional/form.html" %}

    Volver

{% endblock %}


text:
import "../TestInit";
// tslint:disable-next-line:ordered-imports
import test from "ava";
import Texture2D from "../../src/Resource/Texture2D";
import TextureSizeCalculator from "../../src/Util/TextureSizeCalculator";

test("TextureSizeCalculator should works well", (t) => {
  Texture2D.maxTextureSize = 4096;
  t.truthy(TextureSizeCalculator.getPow2Size(100, 100).width === 128);
  t.truthy(TextureSizeCalculator.getPow2Size(128, 128).width === 128);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 1).width === 1);
  t.truthy(TextureSizeCalculator.getPow2Size(2, 2).width === 2);
  t.truthy(TextureSizeCalculator.getPow2Size(200, 200).width === 256);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 256).width === 1);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 256).height === 256);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 255).height === 256);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 5000).width === 1);
  t.truthy(TextureSizeCalculator.getPow2Size(1, 5000).height === 4096);
});


text:
import socket
import ssl
import re

class IRC(object):
    """ An IRC connection """
    def __init__(self, conf):
        """ Connects to a network """
        self.channels = {}
        self.own_hostname = False

        self.conf = conf
        self.charset = conf['charset']

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(
            (conf['network_address'], conf['network_port'])
        )

        if ssl:
            self.socket = ssl.wrap_socket(self.socket)

        self.socket.send(('NICK %s\r\n' % conf['nick']).encode(self.charset))
        self.socket.send(('USER %s %s %s %s\r\n' % (
            conf['username'],
            conf['hostname'],
            conf['servername'],
            conf['realname']
        )).encode(self.charset)
        )

        try:
            self.send(('NICKSERV identify %s' % conf['network_nickserv_pass']))
        except KeyError:
            pass

        self.quit_message = conf['quit_message']

    def pong(self, data):
        """ Send a ping response """
        self.socket.send(('PONG %s\r\n'
                          % data.split()[1]).encode(self.charset))

    def join(self, channel):
        """ Joins a channel. """
        out = 'JOIN %s' % channel
        self.send(out)
        self.getmode(channel)

    def part(self, channel, reason='', kick=False):
        if not kick:
            self.send('PART %s %s' % (channel, reason))

        if channel in self.channels:
            del self.channels[channel]

    def getmode(self, name):
        self.socket.send(('MODE %s\r\n' % name).encode(self.charset))

    def who(self, host):
        self.socket.send('WHO %s\r\n' % host)

    def act(self, target, message, pretty=False, crop=True):
        self.ctcp(target, 'ACTION', message, notice=False, crop=crop)

    def send(self, message):
            print(' >> %s' % message)
            message += '\r\n'
            try:
                self.socket.send(message.encode(self.charset))
            except UnicodeEncodeError:
                print("\n !! Some characters could not be reproduced in the "
                      "proceding output using 'charset': " + self.charset)
                self.socket.send(message.encode(self.charset, 'ignore'))

    def ctcp(self, target, ctcp, message=None, notice=False, crop=True):
        """ Issue a CTCP message """
        if notice:
            message_type = 'NOTICE'
        else:
            message_type = 'PRIVMSG'

        if message:
            message = self.crop(message, message_type+ctcp+'\x01 \x01', target)
            s = ctcp+' '+message
        else:
            s = ctcp

        out = '%s %s :\x01%s\x01' % (message_type, target, s)
        self.send(out)

    def privmsg(self, target, message, pretty=False, crop=True):
        """
        Send a channel or user a message. If the message exceeds the 512
        character limit (and crop is True), truncate it.
        """

        if pretty:
            message = self.beautify(message)

        message = self.add_missing_colours(message)

        try:
            if 'c' in self.channels[target]['modes']:
                message = self.strip_formatting(message)
        except KeyError:
            pass

        message = self.crop(message, 'PRIVMSG', target)

        out = 'PRIVMSG %s :%s' % (target, message)
        self.send(out)

    def crop(self, message, command, target):
        """
        Crop a message based on how long the command will be on the client side
        -- IRC can not exceed 512 characters, we must account for this.

        message is the type of message you're sending. It's only used for
        length, so feel free to include \\x01\\x01 in CTCP messages, etc.
        """

        cruft = len(':%s %s %s :' % (self.own_hostname, command, target))
        excess = (len(message) - (512 - cruft))

        if excess > 0:
            message = message[:-(excess+5)].rstrip()+'...'

        return message

    def beautify(self, message):
        message = message.replace(' : ', ' \x03#:\x03 ')
        message = message.replace(' | ', ' \x03#|\x03 ')
        return message

    def add_missing_colours(self, message):
        assem = ''
        split = message.split('\x03')
        assem = split[0]

        if len(split) > 0:
            for part in split[1:]:
                assem += '\x03'
                if part.startswith('#'):
                    assem += str(self.conf['pigment'])
                    assem += part[1:]
                else:
                    assem += part

        return assem

    def strip_formatting(self, part):
        part = re.sub('\x03\d?\d?((?=[^,])|,\d?\d?)', '', part)
        part = re.sub('[\x01\x02\x0F\x16]', '', part)
        #part = re.sub('\x01', '', part)
        #part = re.sub('\x02', '', part)
        #part = re.sub('\x0F', '', part)
        #part = re.sub('\x16', '', part)

        return part

    def listen(self):
        """ Listens for incoming stuffs and returns them """
        self.data = self.socket.recv(4096)

        if self.data.find(b' '):
            return self.data

    def quit(self, reason=None):
        reason = reason or self.quit_message
        out = 'QUIT :%s' % reason
        self.send(out)
        print()


text:
package httpd_test

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"log"
	"math"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"reflect"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gogo/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/influxdata/influxdb/internal"
	"github.com/influxdata/influxdb/models"
	"github.com/influxdata/influxdb/prometheus/remote"
	"github.com/influxdata/influxdb/query"
	"github.com/influxdata/influxdb/services/httpd"
	"github.com/influxdata/influxdb/services/meta"
	"github.com/influxdata/influxql"
)

// Ensure the handler returns results from a query (including nil results).
func TestHandler_Query(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT * FROM bar` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `foo` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 2, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler returns results from a query passed as a file.
func TestHandler_Query_File(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT * FROM bar` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `foo` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 2, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	var body bytes.Buffer
	writer := multipart.NewWriter(&body)
	part, err := writer.CreateFormFile("q", "")
	if err != nil {
		t.Fatal(err)
	}
	io.WriteString(part, "SELECT * FROM bar")

	if err := writer.Close(); err != nil {
		t.Fatal(err)
	}

	r := MustNewJSONRequest("POST", "/query?db=foo", &body)
	r.Header.Set("Content-Type", writer.FormDataContentType())

	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Test query with user authentication.
func TestHandler_Query_Auth(t *testing.T) {
	// Create the handler to be tested.
	h := NewHandler(true)

	// Set mock meta client functions for the handler to use.
	h.MetaClient.AdminUserExistsFn = func() bool { return true }

	h.MetaClient.UserFn = func(username string) (meta.User, error) {
		if username != "user1" {
			return nil, meta.ErrUserNotFound
		}
		return &meta.UserInfo{
			Name:  "user1",
			Hash:  "abcd",
			Admin: true,
		}, nil
	}

	h.MetaClient.AuthenticateFn = func(u, p string) (meta.User, error) {
		if u != "user1" {
			return nil, fmt.Errorf("unexpected user: exp: user1, got: %s", u)
		} else if p != "abcd" {
			return nil, fmt.Errorf("unexpected password: exp: abcd, got: %s", p)
		}
		return h.MetaClient.User(u)
	}

	// Set mock query authorizer for handler to use.
	h.QueryAuthorizer.AuthorizeQueryFn = func(u meta.User, query *influxql.Query, database string) error {
		return nil
	}

	// Set mock statement executor for handler to use.
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT * FROM bar` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `foo` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 2, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	// Test the handler with valid user and password in the URL parameters.
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?u=user1&p=abcd&db=foo&q=SELECT+*+FROM+bar", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test the handler with valid user and password using basic auth.
	w = httptest.NewRecorder()
	r := MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil)
	r.SetBasicAuth("user1", "abcd")
	h.ServeHTTP(w, r)
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test the handler with valid JWT bearer token.
	req := MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil)
	// Create a signed JWT token string and add it to the request header.
	_, signedToken := MustJWTToken("user1", h.Config.SharedSecret, false)
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signedToken))

	w = httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test the handler with JWT token signed with invalid key.
	req = MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil)
	// Create a signed JWT token string and add it to the request header.
	_, signedToken = MustJWTToken("user1", "invalid key", false)
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signedToken))

	w = httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"error":"signature is invalid"}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test handler with valid JWT token carrying non-existant user.
	_, signedToken = MustJWTToken("bad_user", h.Config.SharedSecret, false)
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signedToken))

	w = httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"error":"user not found"}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test handler with expired JWT token.
	_, signedToken = MustJWTToken("user1", h.Config.SharedSecret, true)
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signedToken))

	w = httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if !strings.Contains(w.Body.String(), `{"error":"Token is expired`) {
		t.Fatalf("unexpected body: %s", w.Body.String())
	}

	// Test handler with JWT token that has no expiration set.
	token, _ := MustJWTToken("user1", h.Config.SharedSecret, false)
	delete(token.Claims.(jwt.MapClaims), "exp")
	signedToken, err := token.SignedString([]byte(h.Config.SharedSecret))
	if err != nil {
		t.Fatal(err)
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signedToken))
	w = httptest.NewRecorder()
	h.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"error":"token expiration required"}` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Test the handler with valid user and password in the url and invalid in
	// basic auth (prioritize url).
	w = httptest.NewRecorder()
	r = MustNewJSONRequest("GET", "/query?u=user1&p=abcd&db=foo&q=SELECT+*+FROM+bar", nil)
	r.SetBasicAuth("user1", "efgh")
	h.ServeHTTP(w, r)
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d: %s", w.Code, w.Body.String())
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]},{"statement_id":2,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler returns results from a query (including nil results).
func TestHandler_QueryRegex(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT * FROM test WHERE url =~ /http\:\/\/www.akamai\.com/` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `test` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		ctx.Results <- nil
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("GET", "/query?db=test&q=SELECT%20%2A%20FROM%20test%20WHERE%20url%20%3D~%20%2Fhttp%5C%3A%5C%2F%5C%2Fwww.akamai%5C.com%2F", nil))
}

// Ensure the handler merges results from the same statement.
func TestHandler_Query_MergeResults(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series0"},{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler merges results from the same statement.
func TestHandler_Query_MergeEmptyResults(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows{}}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":1,"series":[{"name":"series1"}]}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler can parse chunked and chunk size query parameters.
func TestHandler_Query_Chunked(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if ctx.ChunkSize != 2 {
			t.Fatalf("unexpected chunk size: %d", ctx.ChunkSize)
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar&chunked=true&chunk_size=2", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if w.Body.String() != `{"results":[{"statement_id":1,"series":[{"name":"series0"}]}]}
{"results":[{"statement_id":1,"series":[{"name":"series1"}]}]}
` {
		t.Fatalf("unexpected body: %s", w.Body.String())
	}
}

// Ensure the handler can accept an async query.
func TestHandler_Query_Async(t *testing.T) {
	done := make(chan struct{})
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT * FROM bar` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `foo` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{{Name: "series0"}})}
		ctx.Results <- &query.Result{StatementID: 2, Series: models.Rows([]*models.Row{{Name: "series1"}})}
		close(done)
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SELECT+*+FROM+bar&async=true", nil))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `` {
		t.Fatalf("unexpected body: %s", body)
	}

	// Wait to make sure the async query runs and completes.
	timer := time.NewTimer(100 * time.Millisecond)
	defer timer.Stop()

	select {
	case <-timer.C:
		t.Fatal("timeout while waiting for async query to complete")
	case <-done:
	}
}

// Ensure the handler returns a status 400 if the query is not passed in.
func TestHandler_Query_ErrQueryRequired(t *testing.T) {
	h := NewHandler(false)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query", nil))
	if w.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"error":"missing required parameter \"q\""}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler returns a status 400 if the query cannot be parsed.
func TestHandler_Query_ErrInvalidQuery(t *testing.T) {
	h := NewHandler(false)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?q=SELECT", nil))
	if w.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"error":"error parsing query: found EOF, expected identifier, string, number, bool at line 1, char 8"}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure the handler returns an appropriate 401 or 403 status when authentication or authorization fails.
func TestHandler_Query_ErrAuthorize(t *testing.T) {
	h := NewHandler(true)
	h.QueryAuthorizer.AuthorizeQueryFn = func(u meta.User, q *influxql.Query, db string) error {
		return errors.New("marker")
	}
	h.MetaClient.AdminUserExistsFn = func() bool { return true }
	h.MetaClient.AuthenticateFn = func(u, p string) (meta.User, error) {

		users := []meta.UserInfo{
			{
				Name:  "admin",
				Hash:  "admin",
				Admin: true,
			},
			{
				Name: "user1",
				Hash: "abcd",
				Privileges: map[string]influxql.Privilege{
					"db0": influxql.ReadPrivilege,
				},
			},
		}

		for _, user := range users {
			if u == user.Name {
				if p == user.Hash {
					return &user, nil
				}
				return nil, meta.ErrAuthenticate
			}
		}
		return nil, meta.ErrUserNotFound
	}

	for i, tt := range []struct {
		user     string
		password string
		query    string
		code     int
	}{
		{
			query: "/query?q=SHOW+DATABASES",
			code:  http.StatusUnauthorized,
		},
		{
			user:     "user1",
			password: "abcd",
			query:    "/query?q=SHOW+DATABASES",
			code:     http.StatusForbidden,
		},
		{
			user:     "user2",
			password: "abcd",
			query:    "/query?q=SHOW+DATABASES",
			code:     http.StatusUnauthorized,
		},
	} {
		w := httptest.NewRecorder()
		r := MustNewJSONRequest("GET", tt.query, nil)
		params := r.URL.Query()
		if tt.user != "" {
			params.Set("u", tt.user)
		}
		if tt.password != "" {
			params.Set("p", tt.password)
		}
		r.URL.RawQuery = params.Encode()

		h.ServeHTTP(w, r)
		if w.Code != tt.code {
			t.Errorf("%d. unexpected status: got=%d exp=%d\noutput: %s", i, w.Code, tt.code, w.Body.String())
		}
	}
}

// Ensure the handler returns a status 200 if an error is returned in the result.
func TestHandler_Query_ErrResult(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		return errors.New("measurement not found")
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewJSONRequest("GET", "/query?db=foo&q=SHOW+SERIES+from+bin", nil))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	} else if body := strings.TrimSpace(w.Body.String()); body != `{"results":[{"statement_id":0,"error":"measurement not found"}]}` {
		t.Fatalf("unexpected body: %s", body)
	}
}

// Ensure that closing the HTTP connection causes the query to be interrupted.
func TestHandler_Query_CloseNotify(t *testing.T) {
	// Avoid leaking a goroutine when this fails.
	done := make(chan struct{})
	defer close(done)

	interrupted := make(chan struct{})
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		select {
		case <-ctx.Done():
		case <-done:
		}
		close(interrupted)
		return nil
	}

	s := httptest.NewServer(h)
	defer s.Close()

	// Parse the URL and generate a query request.
	u, err := url.Parse(s.URL)
	if err != nil {
		t.Fatal(err)
	}
	u.Path = "/query"

	values := url.Values{}
	values.Set("q", "SELECT * FROM cpu")
	values.Set("db", "db0")
	values.Set("rp", "rp0")
	values.Set("chunked", "true")
	u.RawQuery = values.Encode()

	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		t.Fatal(err)
	}

	// Perform the request and retrieve the response.
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}

	// Validate that the interrupted channel has NOT been closed yet.
	timer := time.NewTimer(100 * time.Millisecond)
	select {
	case <-interrupted:
		timer.Stop()
		t.Fatal("query interrupted unexpectedly")
	case <-timer.C:
	}

	// Close the response body which should abort the query in the handler.
	resp.Body.Close()

	// The query should abort within 100 milliseconds.
	timer.Reset(100 * time.Millisecond)
	select {
	case <-interrupted:
		timer.Stop()
	case <-timer.C:
		t.Fatal("timeout while waiting for query to abort")
	}
}

// Ensure the prometheus remote write works
func TestHandler_PromWrite(t *testing.T) {
	req := &remote.WriteRequest{
		Timeseries: []*remote.TimeSeries{
			{
				Labels: []*remote.LabelPair{
					{Name: "host", Value: "a"},
					{Name: "region", Value: "west"},
				},
				Samples: []*remote.Sample{
					{TimestampMs: 1, Value: 1.2},
					{TimestampMs: 2, Value: math.NaN()},
				},
			},
		},
	}

	data, err := proto.Marshal(req)
	if err != nil {
		t.Fatal("couldn't marshal prometheus request")
	}
	compressed := snappy.Encode(nil, data)

	b := bytes.NewReader(compressed)
	h := NewHandler(false)
	h.MetaClient.DatabaseFn = func(name string) *meta.DatabaseInfo {
		return &meta.DatabaseInfo{}
	}
	called := false
	h.PointsWriter.WritePointsFn = func(db, rp string, _ models.ConsistencyLevel, _ meta.User, points []models.Point) error {
		called = true
		point := points[0]
		if point.UnixNano() != int64(time.Millisecond) {
			t.Fatalf("Exp point time %d but got %d", int64(time.Millisecond), point.UnixNano())
		}
		tags := point.Tags()
		expectedTags := models.Tags{models.Tag{Key: []byte("host"), Value: []byte("a")}, models.Tag{Key: []byte("region"), Value: []byte("west")}}
		if !reflect.DeepEqual(tags, expectedTags) {
			t.Fatalf("tags don't match\n\texp: %v\n\tgot: %v", expectedTags, tags)
		}

		fields, err := point.Fields()
		if err != nil {
			t.Fatal(err.Error())
		}
		expFields := models.Fields{"f64": 1.2}
		if !reflect.DeepEqual(fields, expFields) {
			t.Fatalf("fields don't match\n\texp: %v\n\tgot: %v", expFields, fields)
		}
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/api/v1/prom/write?db=foo", b))
	if !called {
		t.Fatal("WritePoints: expected call")
	}
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

// Ensure Prometheus remote read requests are converted to the correct InfluxQL query and
// data is returned
func TestHandler_PromRead(t *testing.T) {
	req := &remote.ReadRequest{
		Queries: []*remote.Query{{
			Matchers: []*remote.LabelMatcher{
				{Type: remote.MatchType_EQUAL, Name: "eq", Value: "a"},
				{Type: remote.MatchType_NOT_EQUAL, Name: "neq", Value: "b"},
				{Type: remote.MatchType_REGEX_MATCH, Name: "regex", Value: "c"},
				{Type: remote.MatchType_REGEX_NO_MATCH, Name: "neqregex", Value: "d"},
			},
			StartTimestampMs: 1,
			EndTimestampMs:   2,
		}},
	}
	data, err := proto.Marshal(req)
	if err != nil {
		t.Fatal("couldn't marshal prometheus request")
	}
	compressed := snappy.Encode(nil, data)
	b := bytes.NewReader(compressed)

	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		if stmt.String() != `SELECT f64 FROM foo.._ WHERE eq = 'a' AND neq != 'b' AND regex =~ /c/ AND neqregex !~ /d/ AND time >= '1970-01-01T00:00:00.001Z' AND time <= '1970-01-01T00:00:00.002Z' GROUP BY *` {
			t.Fatalf("unexpected query: %s", stmt.String())
		} else if ctx.Database != `foo` {
			t.Fatalf("unexpected db: %s", ctx.Database)
		}
		row := &models.Row{
			Name:    "_",
			Tags:    map[string]string{"foo": "bar"},
			Columns: []string{"time", "f64"},
			Values:  [][]interface{}{{time.Unix(23, 0), 1.2}},
		}
		ctx.Results <- &query.Result{StatementID: 1, Series: models.Rows([]*models.Row{row})}
		return nil
	}

	w := httptest.NewRecorder()

	h.ServeHTTP(w, MustNewJSONRequest("POST", "/api/v1/prom/read?db=foo", b))
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	}

	reqBuf, err := snappy.Decode(nil, w.Body.Bytes())
	if err != nil {
		t.Fatal(err.Error())
	}

	var resp remote.ReadResponse
	if err := proto.Unmarshal(reqBuf, &resp); err != nil {
		t.Fatal(err.Error())
	}

	expLabels := []*remote.LabelPair{{Name: "foo", Value: "bar"}}
	expSamples := []*remote.Sample{{TimestampMs: 23000, Value: 1.2}}

	ts := resp.Results[0].Timeseries[0]

	if !reflect.DeepEqual(expLabels, ts.Labels) {
		t.Fatalf("unexpected labels\n\texp: %v\n\tgot: %v", expLabels, ts.Labels)
	}
	if !reflect.DeepEqual(expSamples, ts.Samples) {
		t.Fatalf("unexpectd samples\n\texp: %v\n\tgot: %v", expSamples, ts.Samples)
	}
}

// Ensure the handler handles ping requests correctly.
// TODO: This should be expanded to verify the MetaClient check in servePing is working correctly
func TestHandler_Ping(t *testing.T) {
	h := NewHandler(false)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("GET", "/ping", nil))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
	h.ServeHTTP(w, MustNewRequest("HEAD", "/ping", nil))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

// Ensure the handler returns the version correctly from the different endpoints.
func TestHandler_Version(t *testing.T) {
	h := NewHandler(false)
	h.StatementExecutor.ExecuteStatementFn = func(stmt influxql.Statement, ctx *query.ExecutionContext) error {
		return nil
	}
	tests := []struct {
		method   string
		endpoint string
		body     io.Reader
	}{
		{
			method:   "GET",
			endpoint: "/ping",
			body:     nil,
		},
		{
			method:   "GET",
			endpoint: "/query?db=foo&q=SELECT+*+FROM+bar",
			body:     nil,
		},
		{
			method:   "POST",
			endpoint: "/write",
			body:     bytes.NewReader(make([]byte, 10)),
		},
		{
			method:   "GET",
			endpoint: "/notfound",
			body:     nil,
		},
	}

	for _, test := range tests {
		w := httptest.NewRecorder()
		h.ServeHTTP(w, MustNewRequest(test.method, test.endpoint, test.body))
		if v := w.HeaderMap["X-Influxdb-Version"]; len(v) > 0 {
			if v[0] != "0.0.0" {
				t.Fatalf("unexpected version: %s", v)
			}
		} else {
			t.Fatalf("Header entry 'X-Influxdb-Version' not present")
		}

		if v := w.HeaderMap["X-Influxdb-Build"]; len(v) > 0 {
			if v[0] != "OSS" {
				t.Fatalf("unexpected BuildType: %s", v)
			}
		} else {
			t.Fatalf("Header entry 'X-Influxdb-Build' not present")
		}
	}
}

// Ensure the handler handles status requests correctly.
func TestHandler_Status(t *testing.T) {
	h := NewHandler(false)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("GET", "/status", nil))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
	h.ServeHTTP(w, MustNewRequest("HEAD", "/status", nil))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

// Ensure write endpoint can handle bad requests
func TestHandler_HandleBadRequestBody(t *testing.T) {
	b := bytes.NewReader(make([]byte, 10))
	h := NewHandler(false)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/write", b))
	if w.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

func TestHandler_Write_EntityTooLarge_ContentLength(t *testing.T) {
	b := bytes.NewReader(make([]byte, 100))
	h := NewHandler(false)
	h.Config.MaxBodySize = 5
	h.MetaClient.DatabaseFn = func(name string) *meta.DatabaseInfo {
		return &meta.DatabaseInfo{}
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/write?db=foo", b))
	if w.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

func TestHandler_Write_SuppressLog(t *testing.T) {
	var buf bytes.Buffer
	c := httpd.NewConfig()
	c.SuppressWriteLog = true
	h := NewHandlerWithConfig(c)
	h.CLFLogger = log.New(&buf, "", log.LstdFlags)
	h.MetaClient.DatabaseFn = func(name string) *meta.DatabaseInfo {
		return &meta.DatabaseInfo{}
	}
	h.PointsWriter.WritePointsFn = func(database, retentionPolicy string, consistencyLevel models.ConsistencyLevel, user meta.User, points []models.Point) error {
		return nil
	}

	b := strings.NewReader("cpu,host=server01 value=2\n")
	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/write?db=foo", b))
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}

	// If the log has anything in it, this failed.
	if buf.Len() > 0 {
		t.Fatalf("expected no bytes to be written to the log, got %d", buf.Len())
	}
}

// onlyReader implements io.Reader only to ensure Request.ContentLength is not set
type onlyReader struct {
	r io.Reader
}

func (o onlyReader) Read(p []byte) (n int, err error) {
	return o.r.Read(p)
}

func TestHandler_Write_EntityTooLarge_NoContentLength(t *testing.T) {
	b := onlyReader{bytes.NewReader(make([]byte, 100))}
	h := NewHandler(false)
	h.Config.MaxBodySize = 5
	h.MetaClient.DatabaseFn = func(name string) *meta.DatabaseInfo {
		return &meta.DatabaseInfo{}
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/write?db=foo", b))
	if w.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

// TestHandler_Write_NegativeMaxBodySize verifies no error occurs if MaxBodySize is < 0
func TestHandler_Write_NegativeMaxBodySize(t *testing.T) {
	b := bytes.NewReader([]byte(`foo n=1`))
	h := NewHandler(false)
	h.Config.MaxBodySize = -1
	h.MetaClient.DatabaseFn = func(name string) *meta.DatabaseInfo {
		return &meta.DatabaseInfo{}
	}
	called := false
	h.PointsWriter.WritePointsFn = func(_, _ string, _ models.ConsistencyLevel, _ meta.User, _ []models.Point) error {
		called = true
		return nil
	}

	w := httptest.NewRecorder()
	h.ServeHTTP(w, MustNewRequest("POST", "/write?db=foo", b))
	if !called {
		t.Fatal("WritePoints: expected call")
	}
	if w.Code != http.StatusNoContent {
		t.Fatalf("unexpected status: %d", w.Code)
	}
}

// Ensure X-Forwarded-For header writes the correct log message.
func TestHandler_XForwardedFor(t *testing.T) {
	var buf bytes.Buffer
	h := NewHandler(false)
	h.CLFLogger = log.New(&buf, "", 0)

	req := MustNewRequest("GET", "/query", nil)
	req.Header.Set("X-Forwarded-For", "192.168.0.1")
	req.RemoteAddr = "127.0.0.1"
	h.ServeHTTP(httptest.NewRecorder(), req)

	parts := strings.Split(buf.String(), " ")
	if parts[0] != "192.168.0.1,127.0.0.1" {
		t.Errorf("unexpected host ip address: %s", parts[0])
	}
}

func TestHandler_XRequestId(t *testing.T) {
	var buf bytes.Buffer
	h := NewHandler(false)
	h.CLFLogger = log.New(&buf, "", 0)

	cases := []map[string]string{
		{"X-Request-Id": "abc123", "Request-Id": ""},          // X-Request-Id is used.
		{"X-REQUEST-ID": "cde", "Request-Id": ""},             // X-REQUEST-ID is used.
		{"X-Request-Id": "", "Request-Id": "foobarzoo"},       // Request-Id is used.
		{"X-Request-Id": "abc123", "Request-Id": "foobarzoo"}, // X-Request-Id takes precedence.
		{"X-Request-Id": "", "Request-Id": ""},                // v1 UUID generated.
	}

	for _, c := range cases {
		t.Run(fmt.Sprint(c), func(t *testing.T) {
			buf.Reset()
			req := MustNewRequest("GET", "/ping", nil)
			req.RemoteAddr = "127.0.0.1"

			// Set the relevant request ID headers
			var allEmpty = true
			for k, v := range c {
				req.Header.Set(k, v)
				if v != "" {
					allEmpty = false
				}
			}

			w := httptest.NewRecorder()
			h.ServeHTTP(w, req)

			// Split up the HTTP log line. The request ID is currently located in
			// index 12. If the log line gets changed in the future, this test
			// will likely break and the index will need to be updated.
			parts := strings.Split(buf.String(), " ")
			i := 12

			// If neither header is set then we expect a v1 UUID to be generated.
			if allEmpty {
				if got, exp := len(parts[i]), 36; got != exp {
					t.Fatalf("got ID of length %d, expected one of length %d", got, exp)
				}
			} else if c["X-Request-Id"] != "" {
				if got, exp := parts[i], c["X-Request-Id"]; got != exp {
					t.Fatalf("got ID of %q, expected %q", got, exp)
				}
			} else if c["X-REQUEST-ID"] != "" {
				if got, exp := parts[i], c["X-REQUEST-ID"]; got != exp {
					t.Fatalf("got ID of %q, expected %q", got, exp)
				}
			} else {
				if got, exp := parts[i], c["Request-Id"]; got != exp {
					t.Fatalf("got ID of %q, expected %q", got, exp)
				}
			}

			// Check response headers
			if got, exp := w.Header().Get("Request-Id"), parts[i]; got != exp {
				t.Fatalf("Request-Id header was %s, expected %s", got, exp)
			} else if got, exp := w.Header().Get("X-Request-Id"), parts[i]; got != exp {
				t.Fatalf("X-Request-Id header was %s, expected %s", got, exp)
			}
		})
	}
}

func TestThrottler_Handler(t *testing.T) {
	t.Run("OK", func(t *testing.T) {
		throttler := httpd.NewThrottler(2, 98)

		// Send the total number of concurrent requests to the channel.
		var concurrentN int32
		concurrentCh := make(chan int)

		h := throttler.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			atomic.AddInt32(&concurrentN, 1)
			concurrentCh <- int(atomic.LoadInt32(&concurrentN))
			time.Sleep(1 * time.Millisecond)
			atomic.AddInt32(&concurrentN, -1)
		}))

		// Execute requests concurrently.
		const n = 100
		for i := 0; i < n; i++ {
			go func() { h.ServeHTTP(nil, nil) }()
		}

		// Read the number of concurrent requests for every execution.
		for i := 0; i < n; i++ {
			if v := <-concurrentCh; v > 2 {
				t.Fatalf("concurrent requests exceed maximum: %d", v)
			}
		}
	})

	t.Run("ErrTimeout", func(t *testing.T) {
		throttler := httpd.NewThrottler(2, 1)
		throttler.EnqueueTimeout = 1 * time.Millisecond

		resp := make(chan struct{})
		h := throttler.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			resp <- struct{}{}
		}))

		pending := make(chan struct{}, 2)

		// First two requests should execute immediately.
		go func() { pending <- struct{}{}; h.ServeHTTP(nil, nil) }()
		go func() { pending <- struct{}{}; h.ServeHTTP(nil, nil) }()

		<-pending
		<-pending

		// Third request should be enqueued but timeout.
		w := httptest.NewRecorder()
		h.ServeHTTP(w, nil)
		if w.Code != http.StatusServiceUnavailable {
			t.Fatalf("unexpected status code: %d", w.Code)
		} else if body := w.Body.String(); body != "request throttled, exceeds timeout\n" {
			t.Fatalf("unexpected response body: %q", body)
		}

		// Allow 2 existing requests to complete.
		<-resp
		<-resp
	})

	t.Run("ErrFull", func(t *testing.T) {
		delay := 100 * time.Millisecond
		if os.Getenv("CI") != "" {
			delay = 2 * time.Second
		}

		throttler := httpd.NewThrottler(2, 1)

		resp := make(chan struct{})
		h := throttler.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			resp <- struct{}{}
		}))

		// First two requests should execute immediately and third should be queued.
		go func() { h.ServeHTTP(nil, nil) }()
		go func() { h.ServeHTTP(nil, nil) }()
		go func() { h.ServeHTTP(nil, nil) }()
		time.Sleep(delay)

		// Fourth request should fail when trying to enqueue.
		w := httptest.NewRecorder()
		h.ServeHTTP(w, nil)
		if w.Code != http.StatusServiceUnavailable {
			t.Fatalf("unexpected status code: %d", w.Code)
		} else if body := w.Body.String(); body != "request throttled, queue full\n" {
			t.Fatalf("unexpected response body: %q", body)
		}

		// Allow 3 existing requests to complete.
		<-resp
		<-resp
		<-resp
	})
}

// NewHandler represents a test wrapper for httpd.Handler.
type Handler struct {
	*httpd.Handler
	MetaClient        *internal.MetaClientMock
	StatementExecutor HandlerStatementExecutor
	QueryAuthorizer   HandlerQueryAuthorizer
	PointsWriter      HandlerPointsWriter
}

// NewHandler returns a new instance of Handler.
func NewHandler(requireAuthentication bool) *Handler {
	config := httpd.NewConfig()
	config.AuthEnabled = requireAuthentication
	config.SharedSecret = "super secret key"
	return NewHandlerWithConfig(config)
}

func NewHandlerWithConfig(config httpd.Config) *Handler {
	h := &Handler{
		Handler: httpd.NewHandler(config),
	}

	h.MetaClient = &internal.MetaClientMock{}

	h.Handler.MetaClient = h.MetaClient
	h.Handler.QueryExecutor = query.NewExecutor()
	h.Handler.QueryExecutor.StatementExecutor = &h.StatementExecutor
	h.Handler.QueryAuthorizer = &h.QueryAuthorizer
	h.Handler.PointsWriter = &h.PointsWriter
	h.Handler.Version = "0.0.0"
	h.Handler.BuildType = "OSS"
	return h
}

// HandlerStatementExecutor is a mock implementation of Handler.StatementExecutor.
type HandlerStatementExecutor struct {
	ExecuteStatementFn func(stmt influxql.Statement, ctx *query.ExecutionContext) error
}

func (e *HandlerStatementExecutor) ExecuteStatement(stmt influxql.Statement, ctx *query.ExecutionContext) error {
	return e.ExecuteStatementFn(stmt, ctx)
}

// HandlerQueryAuthorizer is a mock implementation of Handler.QueryAuthorizer.
type HandlerQueryAuthorizer struct {
	AuthorizeQueryFn func(u meta.User, query *influxql.Query, database string) error
}

func (a *HandlerQueryAuthorizer) AuthorizeQuery(u meta.User, query *influxql.Query, database string) error {
	return a.AuthorizeQueryFn(u, query, database)
}

type HandlerPointsWriter struct {
	WritePointsFn func(database, retentionPolicy string, consistencyLevel models.ConsistencyLevel, user meta.User, points []models.Point) error
}

func (h *HandlerPointsWriter) WritePoints(database, retentionPolicy string, consistencyLevel models.ConsistencyLevel, user meta.User, points []models.Point) error {
	return h.WritePointsFn(database, retentionPolicy, consistencyLevel, user, points)
}

// MustNewRequest returns a new HTTP request. Panic on error.
func MustNewRequest(method, urlStr string, body io.Reader) *http.Request {
	r, err := http.NewRequest(method, urlStr, body)
	if err != nil {
		panic(err.Error())
	}
	return r
}

// MustNewRequest returns a new HTTP request with the content type set. Panic on error.
func MustNewJSONRequest(method, urlStr string, body io.Reader) *http.Request {
	r := MustNewRequest(method, urlStr, body)
	r.Header.Set("Accept", "application/json")
	return r
}

// MustJWTToken returns a new JWT token and signed string or panics trying.
func MustJWTToken(username, secret string, expired bool) (*jwt.Token, string) {
	token := jwt.New(jwt.GetSigningMethod("HS512"))
	token.Claims.(jwt.MapClaims)["username"] = username
	if expired {
		token.Claims.(jwt.MapClaims)["exp"] = time.Now().Add(-time.Second).Unix()
	} else {
		token.Claims.(jwt.MapClaims)["exp"] = time.Now().Add(time.Minute * 10).Unix()
	}
	signed, err := token.SignedString([]byte(secret))
	if err != nil {
		panic(err)
	}
	return token, signed
}


text:
package com.android.foodbook.widgets;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class StarRatingWidget
{
	private Context mContext;

	public StarRatingWidget(final Context context)
	{
		mContext = context;
	}

	public View setStarRating(View v ,Double rating)
	{
		LinearLayout layout = (LinearLayout) v;
		for(int index = 0 ; index < rating.intValue() ; index ++)
		{
			ImageView imageView = new ImageView(mContext);
			LayoutParams layoutParams = new LayoutParams(40, 40);
			imageView.setLayoutParams(layoutParams);
			imageView.setBackgroundResource(android.R.drawable.btn_star_big_on);
			layout.addView(imageView);
		}
		return v;

	}
}


text:
This is my personal website which I am constantly updating and changing.

If you any have questions, suggestions or just want to say hi feel free connect with me on twitter - [@vladshap](http://twitter.com/vladshap)

If you've found a bug, it would be awesome if you created an issue!

#### Colophon:
* Preprocessed via [node-sass](https://github.com/sass/node-sass)
* CSS vendor prefixes via [Autoprefixer](https://github.com/ai/autoprefixer)
* VS logo design by [Nicole Hammonds](http://nicole-hammonds.com)
* Brandon Grotesque font via [TypeKit](https://typekit.com/fonts/brandon-grotesque)
* Social Icons generated via [IcoMoon](http://icomoon.io/app/)


text:
<?php

namespace precore\util;

use PHPUnit_Framework_TestCase;

/**
 * Class ProfilerTest
 *
 * @package precore\util
 * @author Janos Szurovecz <szjani@szjani.hu>
 */
class ProfilerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     * @expectedException \precore\lang\IllegalStateException
     */
    public function shouldThrowExceptionStopWithoutStart()
    {
        $profiler = new Profiler(__METHOD__);
        $profiler->stop();
    }

    /**
     * @test
     */
    public function shouldStartStopDoFourTicks()
    {
        $ticker = IncrementedTicker::instance();
        $profiler = new Profiler(__METHOD__, $ticker);
        $profiler->start('t1');
        $profiler->stop();
        self::assertEquals(4, $ticker->counter());
    }

    /**
     * @test
     */
    public function shouldToStringContainAllInfo()
    {
        $ticker = IncrementedTicker::instance();
        $profiler = new Profiler('p1', $ticker);
        $profiler->start('t1');
        $profiler->start('t2');
        $profiler->stop();
        $expected = <<<'EOT'
 + Profiler [p1]
 |-- elapsed time                           [t1]     1 µs.
 |-- elapsed time                           [t2]     1 µs.
 |-- Total                                  [p1]     5 µs.

EOT;
        self::assertEquals($expected, $profiler->toString());
    }

    /**
     * @test
     */
    public function shouldToStringContainNestedProfiler()
    {
        $ticker = IncrementedTicker::instance();
        $profiler = new Profiler('p1', $ticker);
        $profiler->start('t1');
        $profiler->startNested('np1');
        $nested = ProfilerRegistry::instance()->get('np1');
        $nested->start('np1-t1');
        $nested->stop();
        $profiler->start('t2');
        $profiler->stop();
        $expected = <<<'EOT'
 + Profiler [p1]
    + Profiler [np1]
    |-- elapsed time                       [np1-t1]     1 µs.
    |-- Subtotal                              [np1]     3 µs.
 |-- elapsed time                           [t1]     5 µs.
 |-- elapsed time                           [t2]     1 µs.
 |-- Total                                  [p1]     9 µs.

EOT;
        self::assertEquals($expected, $profiler->toString());
    }
};


text:
package executors

import (
	"encoding/json"

	"github.com/dselans/pagerduty"
)

func init() {
	Register("PagerDuty", NewPagerDuty)
}

func NewPagerDuty() IExecutor {
	pd := &PagerDuty{}
	pd.Data = make(map[string]interface{})

	return pd
}

type PagerDuty struct {
	Base
	Data        map[string]interface{}
	ServiceKey  string
	Description string
	IncidentKey string
}

// Run shells out external program and store the output on c.Data.
func (pd *PagerDuty) Run() error {
	pd.Data["Conditions"] = pd.Conditions

	if pd.IsConditionMet() && pd.LowThresholdExceeded() && !pd.HighThresholdExceeded() {
		event := pagerduty.NewTriggerEvent(pd.ServiceKey, pd.Description)

		if pd.IncidentKey != "" {
			event.IncidentKey = pd.IncidentKey
		}

		response, statusCode, err := pagerduty.Submit(event)

		pd.Data["IncidentKey"] = response.IncidentKey
		pd.Data["Status"] = response.Status
		pd.Data["StatusCode"] = statusCode
		pd.Data["Message"] = response.Message
		pd.Data["Errors"] = response.Errors

		if err != nil {
			return err
		}
	}

	return nil
}

// ToJson serialize Data field to JSON.
func (pd *PagerDuty) ToJson() ([]byte, error) {
	return json.Marshal(pd.Data)
}


text:
import os
import urllib
import uuid

from pymongo import MongoClient
import requests

from framework.mongo.utils import to_mongo_key

from website import settings
from website.addons.wiki import settings as wiki_settings
from website.addons.wiki.exceptions import InvalidVersionError

def generate_private_uuid(node, wname):
    """
    Generate private uuid for internal use in sharejs namespacing.
    Note that this will NEVER be passed to to the client or sharejs.
    """

    private_uuid = str(uuid.uuid1())
    wiki_key = to_mongo_key(wname)
    node.wiki_private_uuids[wiki_key] = private_uuid
    node.save()

    return private_uuid

def get_sharejs_uuid(node, wname):
    """
    Format private uuid into the form used in mongo and sharejs.
    This includes node's primary ID to prevent fork namespace collision
    """
    wiki_key = to_mongo_key(wname)
    private_uuid = node.wiki_private_uuids.get(wiki_key)
    return str(uuid.uuid5(
        uuid.UUID(private_uuid),
        str(node._id)
    )) if private_uuid else None

def delete_share_doc(node, wname):
    """Deletes share document and removes namespace from model."""

    db = share_db()
    sharejs_uuid = get_sharejs_uuid(node, wname)

    db['docs'].remove({'_id': sharejs_uuid})
    db['docs_ops'].remove({'name': sharejs_uuid})

    wiki_key = to_mongo_key(wname)
    del node.wiki_private_uuids[wiki_key]
    node.save()

def migrate_uuid(node, wname):
    """Migrates uuid to new namespace."""

    db = share_db()
    old_sharejs_uuid = get_sharejs_uuid(node, wname)

    broadcast_to_sharejs('lock', old_sharejs_uuid)

    generate_private_uuid(node, wname)
    new_sharejs_uuid = get_sharejs_uuid(node, wname)

    doc_item = db['docs'].find_one({'_id': old_sharejs_uuid})
    if doc_item:
        doc_item['_id'] = new_sharejs_uuid
        db['docs'].insert(doc_item)
        db['docs'].remove({'_id': old_sharejs_uuid})

    ops_items = [item for item in db['docs_ops'].find({'name': old_sharejs_uuid})]
    if ops_items:
        for item in ops_items:
            item['_id'] = item['_id'].replace(old_sharejs_uuid, new_sharejs_uuid)
            item['name'] = new_sharejs_uuid
        db['docs_ops'].insert(ops_items)
        db['docs_ops'].remove({'name': old_sharejs_uuid})

    write_contributors = [
        user._id for user in node.contributors
        if node.has_permission(user, 'write')
    ]
    broadcast_to_sharejs('unlock', old_sharejs_uuid, data=write_contributors)

def share_db():
    """Generate db client for sharejs db"""
    client = MongoClient(settings.DB_HOST, settings.DB_PORT)
    return client[wiki_settings.SHAREJS_DB_NAME]

def get_sharejs_content(node, wname):
    db = share_db()
    sharejs_uuid = get_sharejs_uuid(node, wname)

    doc_item = db['docs'].find_one({'_id': sharejs_uuid})
    return doc_item['_data'] if doc_item else ''

def broadcast_to_sharejs(action, sharejs_uuid, node=None, wiki_name='home', data=None):
    """
    Broadcast an action to all documents connected to a wiki.
    Actions include 'lock', 'unlock', 'redirect', and 'delete'
    'redirect' and 'delete' both require a node to be specified
    'unlock' requires data to be a list of contributors with write permission
    """

    url = 'http://{host}:{port}/{action}/{id}/'.format(
        host=wiki_settings.SHAREJS_HOST,
        port=wiki_settings.SHAREJS_PORT,
        action=action,
        id=sharejs_uuid
    )

    if action == 'redirect' or action == 'delete':
        redirect_url = urllib.quote(
            node.web_url_for('project_wiki_view', wname=wiki_name, _guid=True),
            safe='',
        )
        url = os.path.join(url, redirect_url)

    try:
        requests.post(url, json=data)
    except requests.ConnectionError:
        pass    # Assume sharejs is not online

def format_wiki_version(version, num_versions, allow_preview):
    """
    :param str version: 'preview', 'current', 'previous', '1', '2', ...
    :param int num_versions:
    :param allow_preview: True if view, False if compare
    """

    if not version:
        return

    if version.isdigit():
        version = int(version)
        if version > num_versions or version < 1:
            raise InvalidVersionError
        elif version == num_versions:
            return 'current'
        elif version == num_versions - 1:
            return 'previous'
    elif version != 'current' and version != 'previous':
        if allow_preview and version == 'preview':
            return version
        raise InvalidVersionError
    elif version == 'previous' and num_versions == 0:
        raise InvalidVersionError

    return version


text:
package raml.tools.traversal;

import org.raml.model.Raml;
import org.raml.model.Resource;
import raml.tools.model.ApiInformation;

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

public class RamlTraversal {
  Raml raml;
  List<RamlTraversalListener> traversalListeners = new ArrayList<RamlTraversalListener>();

  public RamlTraversal(Raml raml) {
    if (raml == null) throw new IllegalArgumentException("raml must not be null");
    if (traversalListeners == null) throw new IllegalArgumentException("listeners must not be null");

    this.raml = raml;
  }

  public RamlTraversal withListener(RamlTraversalListener listener) {
    traversalListeners.add(listener);
    return this;
  }

  public void traverse() {
    notifyStartTraversal();
    notifyStartApiInformation();

    for (final Map.Entry<String, Resource> resource : raml.getResources().entrySet()) {
      eachListener(new ListenerFunction() {
        @Override
        public void apply(RamlTraversalListener listener) {
          listener.startResource(resource.getKey(), resource.getValue());
          // ACTIONS etc.
          listener.endResource(resource.getKey(), resource.getValue());
        }
      });
    }

    notifyEndTraversal();
  }

  private void notifyEndTraversal() {
    eachListener(new ListenerFunction() {
      @Override
      public void apply(RamlTraversalListener listener) {
        listener.endTraversal(raml);
      }
    });
  }

  private void notifyStartApiInformation() {
    eachListener(new ListenerFunction() {
      @Override
      public void apply(RamlTraversalListener listener) {
        listener.startApiInformation(new ApiInformation(raml.getTitle(), raml.getVersion(), raml.getBaseUri()));
      }
    });
  }

  private void notifyStartTraversal() {
    eachListener(new ListenerFunction() {
      @Override
      public void apply(RamlTraversalListener listener) {
        listener.startTraversal(raml);
      }
    });
  }

  public void eachListener(ListenerFunction listenerFunction) {
    for (RamlTraversalListener listener :  traversalListeners) {
      listenerFunction.apply(listener);
    }
  }

  public interface ListenerFunction {
    public void apply(RamlTraversalListener listener);
  }
}


text:
//---------------------------------------------------------------------
// <copyright file="ODataEdmNullValue.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Core.Evaluation
{
    #region Namespaces
    using Microsoft.OData.Edm;
    using Microsoft.OData.Edm.Library.Values;
    using Microsoft.OData.Edm.Values;
    #endregion Namespaces

    /// <summary>
    /// An <see cref="IEdmValue"/> implementation of an OData entry or complex value.
    /// </summary>
    internal sealed class ODataEdmNullValue : EdmValue, IEdmNullValue
    {
        /// <summary>Static, un-typed <see cref="IEdmNullValue"/> instance for use in ODataLib.</summary>
        internal static ODataEdmNullValue UntypedInstance = new ODataEdmNullValue(/*type*/ null);

        /// <summary>
        /// Creates a new Edm null value with the specified type.
        /// </summary>
        /// <param name="type">The type of the null value (if available).</param>
        internal ODataEdmNullValue(IEdmTypeReference type)
            : base(type)
        {
        }

        /// <summary>
        /// Gets the kind of this value.
        /// </summary>
        public override EdmValueKind ValueKind
        {
            get
            {
                return EdmValueKind.Null;
            }
        }
    }
}


text:
<?php

defined('_JEXEC') or die;

// Get the mime type class.
$mime = !empty($this->result->mime) ? 'mime-' . $this->result->mime : null;

// Get the base url.
$base = JUri::getInstance()->toString(array('scheme', 'host', 'port'));

// Calculate number of characters to display around the result
$length = $this->params->get('description_length', 255) - strlen($this->query->input);

// Get the route with highlighting information.
if (!empty($this->query->highlight) && empty($this->result->mime) && $this->params->get('highlight_terms', 1) && JPluginHelper::isEnabled('system', 'highlight'))
{
	$route = $this->result->route . '&highlight=' . base64_encode(json_encode($this->query->highlight));
} else {
	$route = $this->result->route;
}
?>

	<h4 class="result-title <?php echo $mime; ?>"><a href="<?php echo JRoute::_($route); ?>"><?php echo $this->result->title; ?>

	<?php if ($this->params->get('show_description', 1)) : ?>
	<p class="result-text<?php echo $this->pageclass_sfx; ?>">
		<?php preg_match('/(?:.){0,' . $length . '}' . $this->query->input . '(?:.){0,' . $length . '}/s', $this->result->description, $description); ?>
		<?php if(!empty($description[0])) : ?>
			<?php echo $description[0]; ?>
		<?php else: ?>
			<?php echo JHtml::_('string.truncate', $this->result->description, $this->params->get('description_length', 255)); ?>
		<?php endif; ?>

	<?php endif; ?>
	<?php if ($this->params->get('show_url', 1)) : ?>
	<div class="small result-url<?php echo $this->pageclass_sfx; ?>"><?php echo $base . JRoute::_($this->result->route); ?>

	<?php endif; ?>


text:
package de.j4velin.picturechooser.util;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SquareImageView extends ImageView {

    public SquareImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    }

}


text:
<?php
/* $Id$ */

$tpl = new Dwoo_Template_File( template("host_view.tpl") );
$data = new Dwoo_Data();
$data->assign("extra", template("host_extra.tpl"));

$data->assign("cluster", $clustername);
$data->assign("host", $hostname);
$data->assign("node_image", node_image($metrics));
$data->assign("sort",$sort);
$data->assign("range",$range);

if($hosts_up)
      $data->assign("node_msg", "This host is up and running.");
else
      $data->assign("node_msg", "This host is down.");

$cluster_url=rawurlencode($clustername);
$data->assign("cluster_url", $cluster_url);
$data->assign("graphargs", "h=$hostname&$get_metric_string&st=$cluster[LOCALTIME]");

# For the node view link.
$data->assign("node_view","./?p=2&c=$cluster_url&h=$hostname");

# No reason to go on if this node is down.
if ($hosts_down)
   {
      $dwoo->output($tpl, $data);
      return;
   }

$data->assign("ip", $hosts_up['IP']);
$data->assign('columns_dropdown', 1);
$data->assign("metric_cols_menu", $metric_cols_menu);
$data->assign("size_menu", $size_menu);
$g_metrics_group = array();

foreach ($metrics as $name => $v)
   {
       if ($v['TYPE'] == "string" or $v['TYPE']=="timestamp" or
           (isset($always_timestamp[$name]) and $always_timestamp[$name]))
          {
             $s_metrics[$name] = $v;
          }
       elseif ($v['SLOPE'] == "zero" or
               (isset($always_constant[$name]) and $always_constant[$name]))
          {
             $c_metrics[$name] = $v;
          }
       else if (isset($reports[$name]) and $reports[$metric])
          continue;
       else
          {
             $size = isset($clustergraphsize) ? $clustergraphsize : 'default';
             $size = $size == 'medium' ? 'default' : $size; //set to 'default' to preserve old behavior
             $graphargs = "c=$cluster_url&h=$hostname&v=$v[VAL]"
               ."&m=$name&r=$range&z=$size&jr=$jobrange"
               ."&js=$jobstart&st=$cluster[LOCALTIME]";
             if ($cs)
                $graphargs .= "&cs=" . rawurlencode($cs);
             if ($ce)
                $graphargs .= "&ce=" . rawurlencode($ce);
             # Adding units to graph 2003 by Jason Smith <smithj4@bnl.gov>.
             if ($v['UNITS']) {
                $encodeUnits = rawurlencode($v['UNITS']);
                $graphargs .= "&vl=$encodeUnits";
             }
             if (isset($v['TITLE'])) {
                $title = $v['TITLE'];
                $graphargs .= "&ti=$title";
             }
             $g_metrics[$name]['graph'] = $graphargs;
             $g_metrics[$name]['description'] = isset($v['DESC']) ? $v['DESC'] : '';

             # Setup an array of groups that can be used for sorting in group view
             if ( isset($metrics[$name]['GROUP']) ) {
                $groups = $metrics[$name]['GROUP'];
             } else {
                $groups = array("");
             }

             foreach ( $groups as $group) {
                if ( isset($g_metrics_group[$group]) ) {
                   $g_metrics_group[$group] = array_merge($g_metrics_group[$group], (array)$name);
                } else {
                   $g_metrics_group[$group] = array($name);
                }
             }
          }
   }

# in case this is not defined, set to LOCALTIME so uptime will be 0 in the display
if ( !isset($metrics['boottime']['VAL']) ){ $metrics['boottime']['VAL'] = $cluster['LOCALTIME'];}

# Add the uptime metric for this host. Cannot be done in ganglia.php,
# since it requires a fully-parsed XML tree. The classic contructor problem.
$s_metrics['uptime']['TYPE'] = "string";
$s_metrics['uptime']['VAL'] = uptime($cluster['LOCALTIME'] - $metrics['boottime']['VAL']);
$s_metrics['uptime']['TITLE'] = "Uptime";

# Add the gmond started timestamps & last reported time (in uptime format) from
# the HOST tag:
$s_metrics['gmond_started']['TYPE'] = "timestamp";
$s_metrics['gmond_started']['VAL'] = $hosts_up['GMOND_STARTED'];
$s_metrics['gmond_started']['TITLE'] = "Gmond Started";
$s_metrics['last_reported']['TYPE'] = "string";
$s_metrics['last_reported']['VAL'] = uptime($cluster['LOCALTIME'] - $hosts_up['REPORTED']);
$s_metrics['last_reported']['TITLE'] = "Last Reported";

$s_metrics['ip_address']['TITLE'] = "IP Address";
$s_metrics['ip_address']['VAL'] = $hosts_up['IP'];
$s_metrics['ip_address']['TYPE'] = "string";
$s_metrics['location']['TITLE'] = "Location";
$s_metrics['location']['VAL'] = $hosts_up['LOCATION'];
$s_metrics['location']['TYPE'] = "string";

# Show string metrics
if (is_array($s_metrics))
   {
      $s_metrics_data = array();
      ksort($s_metrics);
      foreach ($s_metrics as $name => $v )
      {
        # RFM - If units aren't defined for metric, make it be the empty string
        ! array_key_exists('UNITS', $v) and $v['UNITS'] = "";
        if (isset($v['TITLE']))
           {
              $s_metrics_data[$name]["name"] = $v['TITLE'];
           }
        else
           {
              $s_metrics_data[$name]["name"] = $name;
           }
        if( $v['TYPE']=="timestamp" or (isset($always_timestamp[$name]) and $always_timestamp[$name]))
           {
              $s_metrics_data[$name]["value"] = date("r", $v['VAL']);
           }
        else
           {
              $s_metrics_data[$name]["value"] = $v['VAL'] . " " . $v['UNITS'];
           }
     }
   }
$data->assign("s_metrics_data", $s_metrics_data);

# Add the average node utilization to the time & string metrics section:
$avg_cpu_num = find_avg($clustername, $hostname, "cpu_num");
if ($avg_cpu_num == 0) $avg_cpu_num = 1;
$cluster_util = sprintf("%.0f", ((double) find_avg($clustername, $hostname, "load_one") / $avg_cpu_num ) * 100);
$data->assign("name", "Avg Utilization (last $range)");
$data->assign("value", "$cluster_util%");

# Show constant metrics.
if (isset($c_metrics) and is_array($c_metrics))
   {
      $c_metrics_data = array();
      ksort($c_metrics);
      foreach ($c_metrics as $name => $v )
     {
        if (isset($v['TITLE']))
           {
              $c_metrics_data[$name]["name"] =  $v['TITLE'];
           }
        else
           {
              $c_metrics_data[$name]["name"] = $name;
           }
        $c_metrics_data[$name]["value"] = "$v[VAL] $v[UNITS]";
     }
   }
$data->assign("c_metrics_data", $c_metrics_data);

# Show graphs.
if ( is_array($g_metrics) && is_array($g_metrics_group) )
   {
      $g_metrics_group_data = array();
      ksort($g_metrics_group);

      foreach ( $g_metrics_group as $group => $metric_array )
         {
            if ( $group == "" ) {
               $group = "no_group";
            }
            $c = count($metric_array);
            $g_metrics_group_data[$group]["group_metric_count"] = $c;
            $i = 0;
            ksort($g_metrics);
            foreach ( $g_metrics as $name => $v )
               {
                  if ( in_array($name, $metric_array) ) {
                     $g_metrics_group_data[$group]["metrics"][$name]["graphargs"] = $v['graph'];
                     $g_metrics_group_data[$group]["metrics"][$name]["alt"] = "$hostname $name";
                     $g_metrics_group_data[$group]["metrics"][$name]["desc"] = "";
                     if (isset($v['description']))
                        $g_metrics_group_data[$group]["metrics"][$name]["desc"] = $v['description'];
                     $g_metrics_group_data[$group]["metrics"][$name]["new_row"] = "";
                     if ( !(++$i % $metriccols) && ($i != $c) )
                        $g_metrics_group_data[$group]["metrics"][$name]["new_row"] = "</TR><TR>";
                  }
               }
         }

   }
$data->assign("g_metrics_group_data", $g_metrics_group_data);
$dwoo->output($tpl, $data);
?>