text:
'use strict';

const { DateTime } = require('luxon');
const chai  = require('chai');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);

const assert = chai.assert;

describe('displayRevisions plugin', function() {
  let subject, mockUi, config;

  beforeEach(function() {
    subject = require('../index');
    mockUi = {
      verbose: true,
      messages: [],
      write() { },
      writeLine(message) {
        this.messages.push(message);
      }
    };
  });

  it('has a name', function() {
    let plugin = subject.createDeployPlugin({
      name: 'test-plugin'
    });

    assert.equal(plugin.name, 'test-plugin');
  });

  it('implements the correct hooks', function() {
    let plugin = subject.createDeployPlugin({
      name: 'test-plugin'
    });

    assert.equal(typeof plugin.displayRevisions, 'function');
  });

  describe('configure hook', function() {
    let plugin, context;
    describe('without providing config', function () {
      beforeEach(function() {
        config = { };
        plugin = subject.createDeployPlugin({
          name: 'displayRevisions'
        });
        context = {
          ui: mockUi,
          config: config
        };
        plugin.beforeHook(context);
      });
      it('warns about missing optional config', function() {
        plugin.configure(context);
        let messages = mockUi.messages.reduce(function(previous, current) {
          if (/- Missing config:\s.*, using default:\s/.test(current)) {
            previous.push(current);
          }

          return previous;
        }, []);

        assert.equal(messages.length, 2);
      });

      it('adds default config to the config object', function() {
        plugin.configure(context);
        assert.isDefined(config.displayRevisions.amount);
      });
    });

    describe('with an amount provided', function () {
      beforeEach(function() {
        config = {
          displayRevisions: {
            amount: 20
          }
        };
        plugin = subject.createDeployPlugin({
          name: 'displayRevisions'
        });
        context = {
          ui: mockUi,
          config: config
        };
        plugin.beforeHook(context);
      });
      it('does not warn about missing optional config', function() {
        plugin.configure(context);
        let messages = mockUi.messages.reduce(function(previous, current) {
          if (/- Missing config:\s.*, using default:\s/.test(current)) {
            previous.push(current);
          }

          return previous;
        }, []);
        assert.equal(messages.length, 1);
      });
    });
  });
  describe('displayRevisions hook with revisionData', function() {
    let plugin, context;

    beforeEach(function() {
      plugin = subject.createDeployPlugin({
        name: 'display-revisions'
      });

      context = {
        ui: mockUi,
        config: { },
        commandOptions: {
          amount: 3
        },
        revisions: [
          { revision: "rev:first", revisionData: {revisionKey: 'rev:first', scm: {sha: '99ee96e7ee7d36717524bd6489d2eff966c83c3d', email: 'mattia@mail.com', branch: 'foo'}, timestamp: 1032123125000}},
          { revision: "rev:second", revisionData: {revisionKey: 'rev:second', scm: {sha: 'eeee96e7ee7d36717524bd6489d2eff966c83c3d', email: 'aaron@mail.com', branch: 'bar'}, timestamp: 1032123127000}},
          { revision: "rev:third", revisionData: {revisionKey: 'rev:third', scm: {sha: 'ffee96e7ee7d36717524bd6489d2eff966c83c3d', email: 'luke@mail.com', branch: 'foo'}, timestamp: 1032123128000}},
        ]
      };
      plugin.beforeHook(context);
      plugin.configure(context);
    });

    it('lists revisions', function() {
      plugin.displayRevisions(context);
      let messages = mockUi.messages.reduce(function(previous, current) {
        if (current.indexOf("rev:") !== -1) {
          previous.push(current);
        }

        return previous;
      }, []);
      assert.equal(messages.length, 1); // logs a single message as table
      let message = messages[0];
      assert.match(message, /RevisionKey/);
      assert.match(message, /Commit/);
      assert.match(message, /User/);
      assert.match(message, /Branch/);

      let lines = message.split("\n");
      assert.equal(lines.length, 4); // logs headers and 3 revisions
      let revisionLine = lines[1];
      assert.match(revisionLine, /rev:first/);
      assert.match(revisionLine, /mattia@mail.com/);
    });
  });

  describe('displayRevisions hook', function() {
    let plugin, context;

    beforeEach(function() {
      plugin = subject.createDeployPlugin({
        name: 'display-revisions'
      });

      context = {
        ui: mockUi,
        config: { },
        commandOptions: {
          amount: 3
        },
        revisions: [
          { revision: "rev:abcdef", timestamp: 1438232435000, deployer: "My Hamster"},
          { revision: "rev:defghi", timestamp: 1032123125000, deployer: "My Hamster", active: true},
          { revision: "rev:jklmno", timestamp: 1032123128000, deployer: "My Hamster"},
          { revision: "rev:qrstuv", timestamp: 1032123155000, deployer: "My Hamster"},
          { revision: "rev:xyz123", timestamp: 1032123123000, deployer: "My Hamster"}
        ]
      };
      plugin.beforeHook(context);
      plugin.configure(context);
    });

    it('lists revisions limited by the amount specified', function() {
      plugin.displayRevisions(context);
      let messages = mockUi.messages.reduce(function(previous, current) {
        if (current.indexOf("rev:") !== -1) {
          previous.push(current);
        }

        return previous;
      }, []);
      assert.equal(messages.length, 3);
    });

    it('skips unset keys', function() {
      plugin.displayRevisions(context);
      let messages = mockUi.messages.reduce(function(previous, current) {
        if (/ version /.test(current)) {
          previous.push(current);
        }

        return previous;
      }, []);
      assert.equal(messages.length, 0);
    });

    it('transforms timestamps to human-readable dates (yyyy/MM/dd HH:mm:ss)', function() {
      plugin.displayRevisions(context);
      let expectedFormat = ('yyyy/MM/dd HH:mm:ss');
      let expectedDate   = DateTime.fromMillis(1438232435000).toFormat(expectedFormat);

      let messages = mockUi.messages.reduce(function(previous, current) {
        if (current.indexOf(expectedDate) !== -1) {
          previous.push(current);
        }

        return previous;
      }, []);
      assert.equal(messages.length, 1);
    });

    it('highlights the active revision', function() {
      plugin.displayRevisions(context);
      let messages = mockUi.messages.reduce(function(previous, current) {
        if (current.indexOf(">") !== -1) {
          previous.push(current);
        }

        return previous;
      }, []);
      assert.equal(messages.length, 1);
    });
  });
});


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

namespace BilibiliJJ_BarrageSystem.COM
{
    public class JsonInfo
    {
        Dictionary<string, string> _Info = new Dictionary<string, string>();
        /// <summary>
        /// JSON数据
        /// </summary>
        public Dictionary<string, string> Info
        {
            get { return _Info; }
            set { _Info = value; }
        }

    }
    public static class C_Json
    {
        #region JSON数据操作
        /// <summary>
        /// 转换为JSON数据
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static string BuildJsonData(JsonInfo info)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (string item in info.Info.Keys)
            {
                sb.Append(string.Format(", \"{0}\": \"{1}\"", item, info.Info[item].Replace("\"", "\\\"")));
            }
            sb.Append("}");
            return sb.ToString().Replace("{, ", "{");
        }

        public static JsonInfo JsonToFormatString(string info)
        {
            JsonInfo J = new JsonInfo();
            try
            {
                //{"Key":"Value","Key":"Value"}
                MatchCollection Match = Regex.Matches(info, @"""[\s\S]+?"":""[\s\S]+?""");
                for (int i = 0; i < Match.Count; i++)
                {
                    MatchCollection MatchTwo = Regex.Matches(Match[i].ToString(), @"""[\s\S]+?""");
                    try { J.Info.Add(MatchTwo[0].ToString().Replace("\"", ""), MatchTwo[1].ToString().Replace("\"", "")); }
                    catch { }
                }
                return J;
            }
            catch { return J; }

        }
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.zstack.header.host;

import org.zstack.header.message.Message;

import java.util.List;

public interface HostMessageHandlerExtensionPoint<T> {
    List<String> getMessageNameTheExtensionServed();

    void handleMessage(Message msg, T context);
}


text:
function couchapp_load(scripts) {
  for (var i=0; i < scripts.length; i++) {
    document.write('<script src="'+scripts[i]+'"><\/script>')
  }
}

couchapp_load([
  "/_utils/script/sha1.js",
  "/_utils/script/json2.js",
  "/_utils/script/jquery.js",
  "script/lib/wgxpath.install.js",
  "script/lib/jquery.xpath.js",
  "/_utils/script/jquery.couch.js",
  "vendor/couchapp/jquery.couch.app.js",
  "vendor/couchapp/jquery.couch.app.util.js",
  "vendor/couchapp/md5.js",
  "vendor/couchapp/jquery.mustache.js",
  "vendor/couchapp/jquery.evently.js"

]);


text:
/*235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself)."

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
*/
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
         if(root.val > p.val && root.val > q.val){
            return lowestCommonAncestor(root.left, p, q);
        }else if(root.val < p.val && root.val < q.val){
            return lowestCommonAncestor(root.right, p, q);
        }else{
            return root;
        }
    }
}


text:
package com.github.felixgail.gplaymusic.util.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.validation.constraints.NotNull;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import svarzee.gps.gpsoauth.AuthToken;

public class RequestInterceptor implements Interceptor {

  private final Map<String, String> parameters;
  private AuthToken token;

  public RequestInterceptor(@NotNull AuthToken token) {
    parameters = new HashMap<>();
    this.token = token;
  }

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    HttpUrl originalHttpUrl = original.url();

    HttpUrl.Builder httpBuilder = originalHttpUrl.newBuilder();

    for (Map.Entry<String, String> entry : parameters.entrySet()) {
      httpBuilder.addQueryParameter(entry.getKey(), entry.getValue());
    }

    HttpUrl url = httpBuilder.build();

    // Request customization: add request headers
    Request request = original.newBuilder()
        .url(url)
        .addHeader("Authorization", "GoogleLogin auth=" + this.token.getToken())
        .addHeader("Content-Type", "application/json")
        .build();

    return chain.proceed(request);
  }

  public Map<String, String> getParameters() {
    return parameters;
  }

  public RequestInterceptor addParameter(String key, String value) {
    this.parameters.put(key, value);
    return this;
  }

  public RequestInterceptor removeParameter(String key) {
    this.parameters.remove(key);
    return this;
  }

  public RequestInterceptor setToken(@NotNull AuthToken token) {
    this.token = token;
    return this;
  }
}


text:
.heading-font {
  font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
  font-weight: 200;
  letter-spacing: 1px;
}
.body-font {
  font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}
.alt-font {
  font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
  text-transform: uppercase;
  letter-spacing: 2px;
}
html,
body {
  height: 100%;
  width: 100%;
}
body {
  font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}

/* yellow color it changes upon hovering button */
a:hover,
a:focus {
  color: #fcbd20;
}

hr.light {
  border-color: white;
}

h1,
h2,
h3,
h4,
h6 {
  font-family: 'Helvetica', 'Arial', 'sans-serif';
  font-weight: 100;
  letter-spacing: 1px;
}

h5 {
  font-family: 'Helvetica', 'Arial', 'sans-serif';
  font-weight: 100;
  letter-spacing: 1px;
  text-align: center;
}

/* extending the background */
@media (min-width: 768px) {
  .navbar-default {
    background-color: transparent;
    border-color: transparent;
  }

}
header {
  position: relative;
  width: 100%;
  min-height: auto;
  overflow-y: hidden;
  background: url("../images/bg-pattern.png"), #B1810B;
  /* fallback for old browsers */
  background: url("../images/bg-pattern.png"), -webkit-linear-gradient(to left, #403B4A, #E7E9BB);
  /* Chrome 10-25, Safari 5.1-6 */
  background: url("../images/bg-pattern.png"), linear-gradient(to right, #000000, #B1810B);
  color: white;
}

/* space between the title and the button (30px) */
header .header-content .header-content-inner h1 {
  margin-top: 0;
  margin-bottom: 0px;
  font-size: 0px;
}

/* extending the background to cover the footer area (fullscreen) */
@media (min-width: 768px) {
  header {
    min-height: 100%;
  }
  header .header-content {
    text-align: left;
    padding: 0;
    height: 100vh;
    font-size: 25px;
  }
  header .header-content .header-content-inner {
    max-width: none;
    margin: 0;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }
  header .header-content .header-content-inner h1 {
    font-size: 40px;
  }
}
@media (min-width: 992px) {
  header .header-content .header-content-inner h1 {
    font-size: 50px;
	letter-spacing: 3px;
  }
}
section {
  padding: 100px 0;
}
section h2 {
  font-size: 50px;
}

.no-gutter > [class*='col-'] {
  padding-right: 0;
  padding-left: 0;
}
.btn {
  font-family: 'Helvetica', 'Arial', 'sans-serif';
  letter-spacing: 0px;
  border-radius: 10px;
  padding: 0px;
}
.btn-xl {
  padding: 15px 45px;
  font-size: 11px;
}


text:
number: 309
date: 2021-09-15 09:00:00

title: "Design for Safety, An Excerpt"
authors: "Eva PenzeyMoog"
tags:
- Research
- Safety

site: "A List Apart"
address: "https://alistapart.com/article/design-for-safety-excerpt/"
---

The goal with this step is to exhaust every effort of identifying harms your product could cause. You aren't worrying about how to prevent the harm yet—that comes in the next step.


text:
Coursework 3 Contact Manager
@ author BBK-PiJ-2015-74 (LucieCBurgess, Birkbeck username Lburge01)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico>
    <titulo>Consolidação dos Lançamentos Efetuados - Rede Arrecadadora</titulo>
    <descricao>
        <![CDATA[Consolidar os lançamentos efetuados pelo agente arrecadador à Conta Única do Tesouro Nacional, a título de recolhimento do produto arrecadado, devolução, remuneração e encargos, relativos a uma data de arrecadação, para verificar eventual existência de saldo residual. Contempla somente os lançamentos relativos a data de arrecadação posterior a 01/01/2001.]]>
    </descricao>
    <requisitos/>
    <etapas></etapas>
    <canaisPrestacaoServico>
        <canalPrestacaoServico>
            <tipoCanalPrestacaoServico>
                <titulo>Web</titulo>
            </tipoCanalPrestacaoServico>
            <descricao>Endereço eletrônico do serviço</descricao>
            <url>http://www.receita.fazenda.gov.br/aplicacoes/atspo/redearrecadadora/InicialConsolidacao.asp</url>
        </canalPrestacaoServico>
    </canaisPrestacaoServico>
    <taxa></taxa>
    <informacoesUteis/>
    <compromissosAtendimento></compromissosAtendimento>
    <legislacoes></legislacoes>
    <palavrasChave></palavrasChave>
    <orgaoResponsavel>
        <titulo>Receita Federal</titulo>
    </orgaoResponsavel>
    <orgaoPrestador>
        <titulo>Receital Federal</titulo>
        <endereco></endereco>
        <telefone></telefone>
    </orgaoPrestador>
    <publicosAlvo>
        <publicoAlvo>
            <titulo>Serviços às empresas</titulo>
            <linhasDaViva>
                <linhaDaVida>
                    <titulo>Meu Negócio</titulo>
                    <eventoslinhaDaVida>
                        <eventolinhaDaVida>
                            <titulo>Pagar impostos</titulo>
                        </eventolinhaDaVida>
                    </eventoslinhaDaVida>
                </linhaDaVida>
            </linhasDaViva>
        </publicoAlvo>
    </publicosAlvo>
    <areasInteresse>
        <area>
            <titulo>Economia e Finanças</titulo>
        </area>
    </areasInteresse>
</servico>


text:
namespace RawRabbit.Operations.Request.Core
{
	public static class RequestKey
	{
		public const string IncommingMessageType = "IncommingMessageType";
		public const string CorrelationId = "CorrelationId";
		public const string SerializedResponse = "SerializedResponse";
		public const string OutgoingMessageType = "OutgoingMessageType";
		public const string ResponseMessage = "ResponseMessage";
		public const string RequestMessage = "RequestMessage";
		public const string Configuration = "RequestConfiguration";
		public const string PublicationAddress = "PublicationAddress";
		public const string ResponseQueueConfig = "ResponseQueueConfig";
	}
}


text:
import re
from typing import Iterable

from httpie.output.writer import MESSAGE_SEPARATOR
from .tokens import Expect
from ...utils import CRLF

SEPARATOR_RE = re.compile(f'^{MESSAGE_SEPARATOR}')
KEY_VALUE_RE = re.compile(r'[\n]*((.*?):(.+)[\n]?)+[\n]*')

def make_headers_re(message_type: Expect):
    assert message_type in {Expect.REQUEST_HEADERS, Expect.RESPONSE_HEADERS}

    # language=RegExp
    crlf = r'[\r][\n]'
    non_crlf = rf'[^{CRLF}]'

    # language=RegExp
    http_version = r'HTTP/\d+\.\d+'
    if message_type is Expect.REQUEST_HEADERS:
        # POST /post HTTP/1.1
        start_line_re = fr'{non_crlf}*{http_version}{crlf}'
    else:
        # HTTP/1.1 200 OK
        start_line_re = fr'{http_version}{non_crlf}*{crlf}'

    return re.compile(
        fr'''
            ^
            {start_line_re}
            ({non_crlf}+:{non_crlf}+{crlf})+
            {crlf}
        ''',
        flags=re.VERBOSE
    )

BODY_ENDINGS = [
    MESSAGE_SEPARATOR,
    CRLF,  # Not really but useful for testing (just remember not to include it in a body).
]
TOKEN_REGEX_MAP = {
    Expect.REQUEST_HEADERS: make_headers_re(Expect.REQUEST_HEADERS),
    Expect.RESPONSE_HEADERS: make_headers_re(Expect.RESPONSE_HEADERS),
    Expect.RESPONSE_META: KEY_VALUE_RE,
    Expect.SEPARATOR: SEPARATOR_RE,
}

class OutputMatchingError(ValueError):
    pass

def expect_tokens(tokens: Iterable[Expect], s: str):
    for token in tokens:
        s = expect_token(token, s)
    if s:
        raise OutputMatchingError(f'Unmatched remaining output for {tokens} in {s!r}')

def expect_token(token: Expect, s: str) -> str:
    if token is Expect.BODY:
        s = expect_body(s)
    else:
        s = expect_regex(token, s)
    return s

def expect_regex(token: Expect, s: str) -> str:
    match = TOKEN_REGEX_MAP[token].match(s)
    if not match:
        raise OutputMatchingError(f'No match for {token} in {s!r}')
    return s[match.end():]

def expect_body(s: str) -> str:
    """
    We require some text, and continue to read until we find an ending or until the end of the string.

    """
    if 'content-disposition:' in s.lower():
        # Multipart body heuristic.
        final_boundary_re = re.compile('\r\n--[^-]+?--\r\n')
        match = final_boundary_re.search(s)
        if match:
            return s[match.end():]

    endings = [s.index(sep) for sep in BODY_ENDINGS if sep in s]
    if not endings:
        s = ''  # Only body
    else:
        end = min(endings)
        if end == 0:
            raise OutputMatchingError(f'Empty body: {s!r}')
        s = s[end:]
    return s


text:
package com.greenpepper.maven.runner;

import java.io.PrintStream;

import org.apache.maven.embedder.AbstractMavenEmbedderLogger;

public class Logger extends AbstractMavenEmbedderLogger
{
    private final PrintStream out;

    public Logger(PrintStream out)
    {
        this.out = out;
    }

	public final PrintStream getOut() {
		return out;
	}

	public final void debug(String message, Throwable throwable)
    {
        if (isDebugEnabled())
        {
            out.print( "[ maven embedder DEBUG] " );
            out.println( message );

            if (null != throwable)
            {
                throwable.printStackTrace( out );
            }
        }
    }

    public final void info(String message, Throwable throwable)
    {
        if (isInfoEnabled())
        {
            out.print( "[ maven embedder INFO] " );
            out.println( message );

            if (null != throwable)
            {
                throwable.printStackTrace( out );
            }
        }
    }

    public final void warn(String message, Throwable throwable)
    {
        if (isWarnEnabled())
        {
            out.print( "[ maven embedder WARNING] " );
            out.println( message );

            if (null != throwable)
            {
                throwable.printStackTrace( out );
            }
        }
    }

    public final void error(String message, Throwable throwable)
    {
        if (isErrorEnabled())
        {
            out.print( "[ maven embedder ERROR] " );
            out.println( message );

            if (null != throwable)
            {
                throwable.printStackTrace( out );
            }
        }
    }

    public final void fatalError(String message, Throwable throwable)
    {
        if (isFatalErrorEnabled())
        {
            out.print( "[ maven embedder FATAL ERROR] " );
            out.println( message );

            if (null != throwable)
            {
                throwable.printStackTrace( out );
            }
        }
    }
}


text:
<!doctype html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>WebcamJS Test Page</title>

WebcamJS Test Page

Demonstrates all features at once

Captures large 480x480 cropped image while displaying live 240x240 preview, flipped horizontally (mirrored), and allows preview before save.

		<form>

				<input type=button value="Take Snapshot" onClick="preview_snapshot()">

				<input type=button value="< Take Another" onClick="cancel_preview()">
				<input type=button value="Save Photo >" onClick="save_photo()" style="font-weight:bold;">

		</form>


text:
import { Test } from 'beater';

import { tests as entryViewerTests } from './entry-viewer';
import { tests as stateTests } from './state';

const tests1: Test[] = ([] as Test[])
  .concat(entryViewerTests)
  .concat(stateTests);

export { tests1 as tests };


text:
{{-- Display Category NavBar --}}

                    {{--For Each Category--}}
                    @foreach($passedData as $category)

{{strtoupper($category['category_name'])}}

                    @endforeach


text:
package client // import "github.com/docker/docker/client"

import (
	"context"
	"encoding/json"
	"errors"
	"net/url"

	"github.com/docker/distribution/reference"
	"github.com/docker/docker/api/types"
)

// ContainerCommit applies changes into a container and creates a new tagged image.
func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) {
	var repository, tag string
	if options.Reference != "" {
		ref, err := reference.ParseNormalizedNamed(options.Reference)
		if err != nil {
			return types.IDResponse{}, err
		}

		if _, isCanonical := ref.(reference.Canonical); isCanonical {
			return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference")
		}
		ref = reference.TagNameOnly(ref)

		if tagged, ok := ref.(reference.Tagged); ok {
			tag = tagged.Tag()
		}
		repository = reference.FamiliarName(ref)
	}

	query := url.Values{}
	query.Set("container", container)
	query.Set("repo", repository)
	query.Set("tag", tag)
	query.Set("comment", options.Comment)
	query.Set("author", options.Author)
	for _, change := range options.Changes {
		query.Add("changes", change)
	}
	if !options.Pause {
		query.Set("pause", "0")
	}

	var response types.IDResponse
	resp, err := cli.post(ctx, "/commit", query, options.Config, nil)
	if err != nil {
		return response, err
	}

	err = json.NewDecoder(resp.body).Decode(&response)
	ensureReaderClosed(resp)
	return response, err
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using DigitalOcean.API.Http;
using DigitalOcean.API.Models.Responses;
using RestSharp;

namespace DigitalOcean.API.Clients {
    public class FirewallsClient : IFirewallsClient {
        private readonly IConnection _connection;

        public FirewallsClient(IConnection connection) {
            _connection = connection;
        }

        /// <summary>
        /// Assign a Droplet to a Cloud Firewall
        /// </summary>
        public Task AddDroplets(string firewallId, Models.Requests.FirewallDroplets droplets) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/droplets", parameters, droplets, Method.POST);
        }

        /// <summary>
        /// Add additional access rules to a Cloud Firewall
        /// </summary>
        public Task AddRules(string firewallId, Models.Requests.FirewallRules rules) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/rules", parameters, rules, Method.POST);
        }

        /// <summary>
        /// Assign a Tag representing a group of Droplets to a Cloud Firewall
        /// </summary>
        public Task AddTags(string firewallId, Models.Requests.FirewallTags tags) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/tags", parameters, tags, Method.POST);
        }

        /// <summary>
        /// Create a new Cloud Firewall
        /// </summary>
        public Task<Firewall> Create(Models.Requests.Firewall firewall) {
            return _connection.ExecuteRequest<Firewall>("firewalls", null, firewall, "firewall", Method.POST);
        }

        /// <summary>
        /// Delete a Cloud Firewall
        /// </summary>
        public Task Delete(string firewallId) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}", parameters, null, Method.DELETE);
        }

        /// <summary>
        /// Retreive an individual Cloud Firewall
        /// </summary>
        public Task<Firewall> Get(string firewallId) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRequest<Firewall>("firewalls/{id}", parameters, null, "firewall");
        }

        /// <summary>
        /// Retreive all Cloud Firewalls available on your account
        /// </summary>
        public Task<IReadOnlyList<Firewall>> GetAll() {
            return _connection.GetPaginated<Firewall>("firewalls", null, "firewalls");
        }

        /// <summary>
        /// Remove a Droplet from a Cloud Firewall,
        /// </summary>
        public Task RemoveDroplets(string firewallId, Models.Requests.FirewallDroplets droplets) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/droplets", parameters, droplets, Method.DELETE);
        }

        /// <summary>
        /// Remove access rules from a Cloud Firewall
        /// </summary>
        public Task RemoveRules(string firewallId, Models.Requests.FirewallRules rules) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/rules", parameters, rules, Method.DELETE);
        }

        /// <summary>
        /// Remove a Tag representing a group of Droplets from a Cloud Firewall
        /// </summary>
        public Task RemoveTags(string firewallId, Models.Requests.FirewallTags tags) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRaw("firewalls/{id}/tags", parameters, tags, Method.DELETE);
        }

        /// <summary>
        /// Update the configuration of an existing Cloud Firewall
        /// </summary>
        public Task<Firewall> Update(string firewallId, Models.Requests.Firewall firewall) {
            var parameters = new List<Parameter> {
                new Parameter("id", firewallId, ParameterType.UrlSegment)
            };
            return _connection.ExecuteRequest<Firewall>("firewalls/{id}", parameters, firewall, "firewall", Method.PUT);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace AsynchronousDownloader.ViewModel
{
    [System.ComponentModel.DesignerCategory("")]
    public class CustomWebClient : WebClient
    {
        public object Data { get; set; }
        public Stopwatch Clock { get; set; }
        public bool Moving { get; set; }
        public DispatcherTimer Timer { get; set; }
    }
}


text:
<?xml version="1.0" ?>
<job>
  <property name="user.input.file">
    <string>foo</string>
  </property>
  <property name="user.input.file.uri">
    <string>foo</string>
  </property>
  <property name="copytotarget2sourcemaplist">
    <map>
      <entry key="baz">
        <string>qux</string>
      </entry>
      <entry key="foo">
        <string>bar</string>
      </entry>
    </map>
  </property>
  <property name="user.input.dir">
    <string>/foo/bar</string>
  </property>
  <property name="user.input.dir.uri">
    <string>file:/foo/bar</string>
  </property>
  <files>
    <file uri="foo2" path="foo2" conref-target="true"/>
    <file uri="bar2" path="bar2" conref-target="true"/>
    <file uri="foo3" path="foo3" copy-to-source="true"/>
    <file uri="foo" path="foo" subjectscheme="true"/>
    <file uri="foo1" path="foo1" format="ditamap" active="true"/>
    <file uri="bar1" path="bar1" format="ditamap" active="true"/>
    <file uri="bar3" path="bar3" copy-to-source="true"/>
    <file uri="bar" path="bar" subjectscheme="true"/>
  </files>
</job>


text:
修改密码

        <form data-ng-submit="changeUserPassword()" class="signin form-vertical" autocomplete="off">
            <fieldset>

                    当前密码
                    <input type="password" id="currentPassword" name="currentPassword" class="form-control" data-ng-model="passwordDetails.currentPassword" placeholder="当前密码">

                    新密码
                    <input type="password" id="newPassword" name="newPassword" class="form-control" data-ng-model="passwordDetails.newPassword" placeholder="新密码">

                    确认新密码
                    <input type="password" id="verifyPassword" name="verifyPassword" class="form-control" data-ng-model="passwordDetails.verifyPassword" placeholder="确认新密码">

                    <button type="submit" class="btn btn-large btn-primary">修改</button>

                    密码修改成功

            </fieldset>
        </form>


text:
PHP_TokenStream
===============

Installation
------------

PHP_TokenStream should be installed using the [PEAR Installer](http://pear.php.net/). This installer is the backbone of PEAR, which provides a distribution system for PHP packages, and is shipped with every release of PHP since version 4.3.0.

The PEAR channel (`pear.phpunit.de`) that is used to distribute PHP_TokenStream needs to be registered with the local PEAR environment:

    sb@ubuntu ~ % pear channel-discover pear.phpunit.de
    Adding Channel "pear.phpunit.de" succeeded
    Discovery of channel "pear.phpunit.de" succeeded

This has to be done only once. Now the PEAR Installer can be used to install packages from the PHPUnit channel:

    sb@ubuntu tokenstream % pear install phpunit/PHP_TokenStream-beta
    downloading PHP_TokenStream-0.9.1.tgz ...
    Starting to download PHP_TokenStream-0.9.1.tgz (5,113 bytes)
    ...done: 5,113 bytes
    install ok: channel://pear.phpunit.de/PHP_TokenStream-0.9.1

After the installation you can find the PHP_TokenStream source files inside your local PEAR directory; the path is usually `/usr/lib/php/PHP`.


text:
    <refentry id="pixfmt-srggb10">
      <refmeta>
	<refentrytitle>V4L2_PIX_FMT_SRGGB10 ('RG10'),
	 V4L2_PIX_FMT_SGRBG10 ('BA10'),
	 V4L2_PIX_FMT_SGBRG10 ('GB10'),
	 V4L2_PIX_FMT_SBGGR10 ('BG10'),
	 </refentrytitle>
	&manvol;
      </refmeta>
      <refnamediv>
	<refname id="V4L2-PIX-FMT-SRGGB10"><constant>V4L2_PIX_FMT_SRGGB10</constant></refname>
	<refname id="V4L2-PIX-FMT-SGRBG10"><constant>V4L2_PIX_FMT_SGRBG10</constant></refname>
	<refname id="V4L2-PIX-FMT-SGBRG10"><constant>V4L2_PIX_FMT_SGBRG10</constant></refname>
	<refname id="V4L2-PIX-FMT-SBGGR10"><constant>V4L2_PIX_FMT_SBGGR10</constant></refname>
	<refpurpose>10-bit Bayer formats expanded to 16 bits</refpurpose>
      </refnamediv>
      <refsect1>
	<title>Description</title>

	<para>The following four pixel formats are raw sRGB / Bayer formats with
10 bits per colour. Each colour component is stored in a 16-bit word, with 6
unused high bits filled with zeros. Each n-pixel row contains n/2 green samples
and n/2 blue or red samples, with alternating red and blue rows. Bytes are
stored in memory in little endian order. They are conventionally described
as GRGR... BGBG..., RGRG... GBGB..., etc. Below is an example of one of these
formats</para>

    <example>
      <title><constant>V4L2_PIX_FMT_SBGGR10</constant> 4 × 4
pixel image</title>

      <formalpara>
	<title>Byte Order.</title>
	<para>Each cell is one byte, high 6 bits in high bytes are 0.
	  <informaltable frame="none">
	    <tgroup cols="5" align="center">
	      <colspec align="left" colwidth="2*" />
	      <tbody valign="top">
		<row>
		  <entry>start + 0:</entry>
		  <entry>B<subscript>00low</subscript></entry>
		  <entry>B<subscript>00high</subscript></entry>
		  <entry>G<subscript>01low</subscript></entry>
		  <entry>G<subscript>01high</subscript></entry>
		  <entry>B<subscript>02low</subscript></entry>
		  <entry>B<subscript>02high</subscript></entry>
		  <entry>G<subscript>03low</subscript></entry>
		  <entry>G<subscript>03high</subscript></entry>
		</row>
		<row>
		  <entry>start + 8:</entry>
		  <entry>G<subscript>10low</subscript></entry>
		  <entry>G<subscript>10high</subscript></entry>
		  <entry>R<subscript>11low</subscript></entry>
		  <entry>R<subscript>11high</subscript></entry>
		  <entry>G<subscript>12low</subscript></entry>
		  <entry>G<subscript>12high</subscript></entry>
		  <entry>R<subscript>13low</subscript></entry>
		  <entry>R<subscript>13high</subscript></entry>
		</row>
		<row>
		  <entry>start + 16:</entry>
		  <entry>B<subscript>20low</subscript></entry>
		  <entry>B<subscript>20high</subscript></entry>
		  <entry>G<subscript>21low</subscript></entry>
		  <entry>G<subscript>21high</subscript></entry>
		  <entry>B<subscript>22low</subscript></entry>
		  <entry>B<subscript>22high</subscript></entry>
		  <entry>G<subscript>23low</subscript></entry>
		  <entry>G<subscript>23high</subscript></entry>
		</row>
		<row>
		  <entry>start + 24:</entry>
		  <entry>G<subscript>30low</subscript></entry>
		  <entry>G<subscript>30high</subscript></entry>
		  <entry>R<subscript>31low</subscript></entry>
		  <entry>R<subscript>31high</subscript></entry>
		  <entry>G<subscript>32low</subscript></entry>
		  <entry>G<subscript>32high</subscript></entry>
		  <entry>R<subscript>33low</subscript></entry>
		  <entry>R<subscript>33high</subscript></entry>
		</row>
	      </tbody>
	    </tgroup>
	  </informaltable>
	</para>
      </formalpara>
    </example>
  </refsect1>
</refentry>


text:
//
//  StringExtensions.m
//  Vienna
//
//  Created by Steve on Wed Mar 17 2004.
//  Copyright (c) 2004-2005 Steve Palmer. All rights reserved.
//
//  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.
//

#import "StringExtensions.h"
#import "HelperFunctions.h"

@implementation NSMutableString (MutableStringExtensions)

/* replaceString
 * Replaces one string with another. This is just a simpler version of the standard
 * NSMutableString replaceOccurrencesOfString function with NSLiteralString implied
 * and the range set to the entire string.
 */
-(void)vna_replaceString:(NSString *)source withString:(NSString *)dest
{
	[self replaceOccurrencesOfString:source withString:dest options:NSLiteralSearch range:NSMakeRange(0, self.length)];
}

/* fixupRelativeImgTags
 * Scans the text for <img...> tags that have relative links in the src attribute and fixes
 * up the relative links to be absolute to the base URL.
 */
-(void)vna_fixupRelativeImgTags:(NSString *)baseURL
{
	baseURL = [NSString vna_stringByCleaningURLString:baseURL];
	if (baseURL == nil)
		return;
	NSURL * imgBaseURL = [NSURL URLWithString:baseURL];

	NSUInteger textLength = self.length;
	NSRange srchRange;

	srchRange.location = 0;
	srchRange.length = textLength;
    while ((void)((srchRange = [self rangeOfString:@"<img" options:NSLiteralSearch range:srchRange])), srchRange.location != NSNotFound)
    {
        srchRange.length = textLength - srchRange.location;
        NSRange srcRange = [self rangeOfString:@"src=\"" options:NSLiteralSearch range:srchRange];
        if (srcRange.location != NSNotFound)
        {
            // Find the src parameter range.
            NSUInteger index = srcRange.location + srcRange.length;
            srcRange.location += srcRange.length;
            srcRange.length = 0;
            while (index < textLength && [self characterAtIndex:index] != '"')
            {
                ++index;
                ++srcRange.length;
            }

            // Now extract the source parameter
            NSString * srcPath = [self substringWithRange:srcRange];
            if (![srcPath hasPrefix:@"http:"] && ![srcPath hasPrefix:@"https:"] && ![srcPath hasPrefix:@"data:"])
            {
                NSURL * imgURL = [NSURL URLWithString:srcPath relativeToURL:imgBaseURL];
                if (imgURL != nil)
                {
                    srcPath = imgURL.absoluteString;
                    [self replaceCharactersInRange:srcRange withString:srcPath];
                    textLength = self.length;
                }
            }

            // Start searching again from beyond the URL
            srchRange.location = srcRange.location + srcPath.length;
        }
        else
            ++srchRange.location;
        srchRange.length = textLength - srchRange.location;
    }
}

/* fixupRelativeAnchorTags
 * Scans the text for <a...> tags that have relative links in the src attribute and fixes
 * up the relative links to be absolute to the base URL.
 */
-(void)vna_fixupRelativeAnchorTags:(NSString *)baseURL
{
	baseURL = [NSString vna_stringByCleaningURLString:baseURL];
	if (baseURL == nil)
		return;
	NSURL * anchorBaseURL = [NSURL URLWithString:baseURL];

	NSUInteger textLength = self.length;
	NSRange srchRange;

	srchRange.location = 0;
	srchRange.length = textLength;
    while ((void)((srchRange = [self rangeOfString:@"<a " options:NSLiteralSearch range:srchRange])), srchRange.location != NSNotFound)
	{
		srchRange.length = textLength - srchRange.location;
		NSRange srcRange = [self rangeOfString:@"href=\"" options:NSLiteralSearch range:srchRange];
		if (srcRange.location != NSNotFound)
		{
			// Find the src parameter range.
			NSUInteger index = srcRange.location + srcRange.length;
			srcRange.location += srcRange.length;
			srcRange.length = 0;
			while (index < textLength && [self characterAtIndex:index] != '"')
			{
				++index;
				++srcRange.length;
			}

			// Now extract the source parameter
			NSString * srcPath = [self substringWithRange:srcRange];
			if (![srcPath hasPrefix:@"http:"] && ![srcPath hasPrefix:@"https:"] && ![srcPath hasPrefix:@"#"])
			{
                NSURL * anchorURL = [NSURL URLWithString:srcPath relativeToURL:anchorBaseURL];
                if (anchorURL != nil)
                {
                    srcPath = anchorURL.absoluteString;
                    [self replaceCharactersInRange:srcRange withString:srcPath];
                    textLength = self.length;
                }
			}

			// Start searching again from beyond the URL
			srchRange.location = srcRange.location + srcPath.length;
		}
		else
			++srchRange.location;
		srchRange.length = textLength - srchRange.location;
	}
}

/* fixupRelativeIframeTags
 * Scans the text for <iframe...> tags that have relative links in the src attribute and fixes
 * up the relative links to be absolute to the base URL.
 */
-(void)vna_fixupRelativeIframeTags:(NSString *)baseURL
{
	baseURL = [NSString vna_stringByCleaningURLString:baseURL];
	if (baseURL == nil)
		return;
	NSURL * imgBaseURL = [NSURL URLWithString:baseURL];

	NSUInteger textLength = self.length;
	NSRange srchRange;

	srchRange.location = 0;
	srchRange.length = textLength;
    while ((void)((srchRange = [self rangeOfString:@"<iframe" options:NSLiteralSearch range:srchRange])), srchRange.location != NSNotFound)
	{
		srchRange.length = textLength - srchRange.location;
		NSRange srcRange = [self rangeOfString:@"src=\"" options:NSLiteralSearch range:srchRange];
		if (srcRange.location != NSNotFound)
		{
			// Find the src parameter range.
			NSUInteger index = srcRange.location + srcRange.length;
			srcRange.location += srcRange.length;
			srcRange.length = 0;
			while (index < textLength && [self characterAtIndex:index] != '"')
			{
				++index;
				++srcRange.length;
			}

			// Now extract the source parameter
			NSString * srcPath = [self substringWithRange:srcRange];
			if (![srcPath hasPrefix:@"http:"] && ![srcPath hasPrefix:@"https:"])
			{
                NSURL * iframeURL = [NSURL URLWithString:srcPath relativeToURL:imgBaseURL];
                if (iframeURL != nil)
                {
                    srcPath = iframeURL.absoluteString;
                    [self replaceCharactersInRange:srcRange withString:srcPath];
                    textLength = self.length;
                }
			}

			// Start searching again from beyond the URL
			srchRange.location = srcRange.location + srcPath.length;
		}
		else
			++srchRange.location;
		srchRange.length = textLength - srchRange.location;
	}
}
@end

// Used for mapping entities to their representations
static NSMutableDictionary * entityMap = nil;

@implementation NSString (StringExtensions)

/* hexValue
 * A counterpart to integerValue, but parses a hexadecimal number.
 */
-(NSInteger)vna_hexValue
{
	NSInteger count = self.length;
	NSInteger intValue = 0;
	NSInteger index = 0;

	while (index < count)
	{
		unichar ch = [self characterAtIndex:index];
		if (ch >= '0' && ch <= '9')
			intValue = (intValue * 16) + (ch - '0');
		else if (ch >= 'A' && ch <= 'F')
			intValue = (intValue * 16) + (ch - 'A' + 10);
		else if (ch >= 'a' && ch <= 'f')
			intValue = (intValue * 16) + (ch - 'a' + 10);
		else
			break;
		++index;
	}
	return intValue;
}

/* summaryTextFromHTML
 * Create a summary text string from raw HTML. We strip out the HTML and convert the entity
 * characters to their unicode equivalents. Newlines are replaced with spaces then the string
 * is truncated to the given number of characters.
 */
-(NSString *)vna_summaryTextFromHTML
{
	return [NSString vna_stringByRemovingHTML:self].vna_normalised;
}

/* titleTextFromHTML
 * Create a title from a description which may be HTML. The HTML is stripped out and entity
 * characters are converted to their unicode equivalents. Then the first newline is returned up to
 * the given number of characters.
 */
-(NSString *)vna_titleTextFromHTML
{
	return [NSString vna_stringByRemovingHTML:self].vna_firstNonBlankLine;
}

/* stringByRemovingHTML
 * Returns an autoreleased instance of the specified string with all HTML tags removed.
 */
+(NSString *)vna_stringByRemovingHTML:(NSString *)theString
{
    NSMutableString *aString = [NSMutableString stringWithString:theString];
    NSInteger maxChrs = theString.length;
    NSInteger cutOff = 600;
    NSInteger indexOfChr = 0;
    NSInteger tagLength = 0;
    NSInteger tagStartIndex = 0;
    BOOL isInQuote = NO;
    BOOL isInTag = NO;

    // Rudimentary HTML tag parsing. This could be done by initWithHTML on an attributed string
    // and extracting the raw string but initWithHTML cannot be invoked within an NSURLConnection
    // callback which is where this is probably liable to be used.
    while (indexOfChr < maxChrs) {
        unichar ch = [aString characterAtIndex:indexOfChr];
        if (isInTag) {
            ++tagLength;
        } else if (indexOfChr >= cutOff) {
            break;
        }

        if (ch == '"') {
            isInQuote = !isInQuote;
        } else if (ch == '<' && !isInQuote) {
            isInTag = YES;
            tagStartIndex = indexOfChr;
            tagLength = 0;
        } else if (ch == '>' && isInTag) {
            if (tagLength > 1) {
                ++tagLength;                 // Include the start tag
                NSRange tagRange = NSMakeRange(tagStartIndex, tagLength);
                NSString *tag = [aString substringWithRange:tagRange].lowercaseString;
                NSInteger indexOfTagName = 1;

                // Extract the tag name
                if ([tag characterAtIndex:indexOfTagName] == '/') {
                    ++indexOfTagName;
                }

                NSInteger chIndex = indexOfTagName;
                unichar ch = [tag characterAtIndex:chIndex];
                while (chIndex < tagLength && [[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:ch]) {
                    ch = [tag characterAtIndex:++chIndex];
                }

                NSString *tagName = [tag substringWithRange:NSMakeRange(indexOfTagName, chIndex - indexOfTagName)];
                [aString deleteCharactersInRange:tagRange];

                // Replace <br> and </p> with newlines
                if ([tagName isEqualToString:@"br"] || [tag isEqualToString:@"<p>"] || [tag isEqualToString:@"<div>"]) {
                    [aString insertString:@"\n" atIndex:tagRange.location];
                }

                // Reset scan to the point where the tag started minus one because
                // we bump up indexOfChr at the end of the loop.
                indexOfChr = tagStartIndex - 1;
                maxChrs = aString.length;
                isInTag = NO;
                isInQuote = NO;                 // Fix problem with Tribe.net feeds that have bogus quotes in HTML tags
            } else if (!isInQuote) {
                isInTag = NO;
            }
        }
        ++indexOfChr;
    }

    if (maxChrs > cutOff) {
        [aString deleteCharactersInRange:NSMakeRange(cutOff, maxChrs - cutOff)];
    }

    return aString.vna_stringByUnescapingExtendedCharacters;
} // stringByRemovingHTML

/* normalised
 * Returns the current string normalised. Newlines are removed and replaced with spaces and multiple
 * spaces are collapsed to one.
 */
-(NSString *)vna_normalised
{
	NSMutableString * string = [NSMutableString stringWithString:self];
	BOOL isInWhitespace = YES;
	NSInteger length = string.length;
	NSInteger index = 0;

	while (index < length)
	{
		unichar ch = [string characterAtIndex:index];
		if (ch == '\r' || ch == '\n' || ch == '\t')
		{
			if (!isInWhitespace)
				[string replaceCharactersInRange:NSMakeRange(index, 1) withString:@" "];
			ch = ' ';
		}
		if (ch == ' ' && isInWhitespace)
		{
			[string deleteCharactersInRange:NSMakeRange(index, 1)];
			--index;
			--length;
		}
		isInWhitespace = (ch == ' ');
		++index;
	}
	return string;
}

/* firstNonBlankLine
 * Returns the first line of the string that isn't entirely spaces or tabs. If all lines in the string are
 * empty, we return an empty string.
 */
-(NSString *)vna_firstNonBlankLine
{
	BOOL hasNonEmptyChars = NO;
	NSUInteger indexOfFirstChr = 0;
	NSUInteger indexOfLastChr = 0;

	NSUInteger indexOfChr = 0;
	NSUInteger length = self.length;
	while (indexOfChr < length)
	{
		unichar ch = [self characterAtIndex:indexOfChr];
		if (ch == '\r' || ch == '\n')
		{
			if (hasNonEmptyChars)
			{
				break;
			}
		}
		else
		{
			if (ch != ' ' && ch != '\t')
			{
				if (!hasNonEmptyChars)
				{
					hasNonEmptyChars = YES;
					indexOfFirstChr = indexOfChr;
				}
				indexOfLastChr = indexOfChr;
			}
		}
		++indexOfChr;
	}
	return hasNonEmptyChars ? [self substringWithRange:NSMakeRange(indexOfFirstChr, 1u + (indexOfLastChr - indexOfFirstChr))] : @"";
}

/* stringByAppendingURLComponent
 * Appends the specified component to the end of our URL. It is similar to stringByAppendingPathComponent
 * but it doesn't attempt to interpret the current string as a file path and 'fixup' slashes.
 */
-(NSString *)vna_stringByAppendingURLComponent:(NSString *)newComponent
{
	NSMutableString * newString = [NSMutableString stringWithString:self];
	NSInteger index = newString.length - 1;
	NSInteger newIndex = 0;

	if (index >= 0 && [newString characterAtIndex:index] != '/')
		[newString appendString:@"/"];
	if (newComponent.length > 0 && [newComponent characterAtIndex:0] == '/')
		++newIndex;
	[newString appendString:[newComponent substringFromIndex:newIndex]];
	return newString;
}

/* stringByEscapingExtendedCharacters
 * Returns a string that consisted of the receiver but with all extended characters
 * escaped in the format &#code; where code is the character code.
 */
-(NSString *)vna_stringByEscapingExtendedCharacters
{
	NSMutableString * escapedString = [NSMutableString stringWithString:self];
	NSInteger length = escapedString.length;
	NSInteger index = 0;

	while (index < length)
	{
		unichar ch = [escapedString characterAtIndex:index];
		if (ch <= 127)
			++index;
		else
		{
			NSString * escapedCharacter = [NSString stringWithFormat:@"&#%d;", ch];
			[escapedString replaceCharactersInRange:NSMakeRange(index, 1) withString:escapedCharacter];
			index += escapedCharacter.length;
			length = escapedString.length;
		}
	}
	return escapedString;
}

/* stringByUnescapingExtendedCharacters
 * Scan the specified string and convert attribute characters to their literals. Also trim leading and trailing
 * whitespace.
 */
-(NSString *)vna_stringByUnescapingExtendedCharacters
{
	NSMutableString * processedString = [[NSMutableString alloc] initWithString:self];
	NSUInteger entityStart;
	NSUInteger entityEnd;

	entityStart = [processedString vna_indexOfCharacterInString:'&' afterIndex:0];
	while (entityStart != NSNotFound)
	{
		entityEnd = [processedString vna_indexOfCharacterInString:';' afterIndex:entityStart + 1];
		if (entityEnd != NSNotFound)
		{
			NSRange entityRange = NSMakeRange(entityStart, (entityEnd - entityStart) + 1);
			NSRange innerEntityRange = NSMakeRange(entityRange.location + 1, entityRange.length - 2);
			NSString * entityString = [processedString substringWithRange:innerEntityRange];
			[processedString replaceCharactersInRange:entityRange withString:[NSString vna_mapEntityToString:entityString]];
		}
		entityStart = [processedString vna_indexOfCharacterInString:'&' afterIndex:entityStart + 1];
	}

	NSString * returnString = processedString.vna_trimmed;
	return returnString;
}

/* mapEntityToString
 * Maps an entity sequence to its character equivalent.
 */
+(NSString *)vna_mapEntityToString:(NSString *)entityString
{
	if (entityMap == nil)
	{
		entityMap = [@{
					   @"lt":		@"<",
					   @"gt":		@">",
					   @"quot":		@"\"",
					   @"amp":		@"&",
					   @"rsquo":	@"'",
					   @"lsquo":	@"'",
					   @"apos":		@"'",
					   @"hellip":	@"...",
					   @"nbsp":		@" ",
					   } mutableCopy];

		// Add entities that map to non-ASCII characters
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA1] forKey:@"iexcl"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA2] forKey:@"cent"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA3] forKey:@"pound"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA4] forKey:@"curren"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA5] forKey:@"yen"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA6] forKey:@"brvbar"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA7] forKey:@"sect"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA8] forKey:@"uml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xA9] forKey:@"copy"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xAA] forKey:@"ordf"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xAB] forKey:@"laquo"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xAC] forKey:@"not"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xAE] forKey:@"reg"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xAF] forKey:@"macr"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB0] forKey:@"deg"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB1] forKey:@"plusmn"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB2] forKey:@"sup2"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB3] forKey:@"sup3"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB4] forKey:@"acute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB5] forKey:@"micro"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB6] forKey:@"para"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB7] forKey:@"middot"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB8] forKey:@"cedil"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xB9] forKey:@"sup1"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBA] forKey:@"ordm"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBB] forKey:@"raquo"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBC] forKey:@"frac14"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBD] forKey:@"frac12"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBE] forKey:@"frac34"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xBF] forKey:@"iquest"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC0] forKey:@"Agrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC1] forKey:@"Aacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC3] forKey:@"Atilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC4] forKey:@"Auml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC5] forKey:@"Aring"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC6] forKey:@"AElig"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC7] forKey:@"Ccedil"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC8] forKey:@"Egrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC9] forKey:@"Eacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCA] forKey:@"Ecirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCB] forKey:@"Euml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCC] forKey:@"Igrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCD] forKey:@"Iacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCE] forKey:@"Icirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCF] forKey:@"Iuml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD0] forKey:@"ETH"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD1] forKey:@"Ntilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD2] forKey:@"Ograve"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD3] forKey:@"Oacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD4] forKey:@"Ocirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD5] forKey:@"Otilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD6] forKey:@"Ouml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD7] forKey:@"times"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD8] forKey:@"Oslash"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xD9] forKey:@"Ugrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDA] forKey:@"Uacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDB] forKey:@"Ucirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDC] forKey:@"Uuml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDD] forKey:@"Yacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDE] forKey:@"THORN"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xDF] forKey:@"szlig"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE0] forKey:@"agrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE1] forKey:@"aacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE2] forKey:@"acirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE3] forKey:@"atilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE4] forKey:@"auml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE5] forKey:@"aring"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE6] forKey:@"aelig"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE7] forKey:@"ccedil"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE8] forKey:@"egrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xE9] forKey:@"eacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xEA] forKey:@"ecirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xEB] forKey:@"euml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xEC] forKey:@"igrave"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xED] forKey:@"iacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xEE] forKey:@"icirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xEF] forKey:@"iuml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF0] forKey:@"eth"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF1] forKey:@"ntilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF2] forKey:@"ograve"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF3] forKey:@"oacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF4] forKey:@"ocirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF5] forKey:@"otilde"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF6] forKey:@"ouml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF7] forKey:@"divide"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF8] forKey:@"oslash"];
        [entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xF9] forKey:@"ugrave"];
        [entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xFA] forKey:@"uacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xFB] forKey:@"ucirc"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xFC] forKey:@"uuml"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xFD] forKey:@"yacute"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xFE] forKey:@"thorn"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xC3C] forKey:@"sigma"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0xCA3] forKey:@"Sigma"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0x2022] forKey:@"bull"];
		[entityMap setValue:[NSString stringWithFormat:@"%C", (unsigned short)0x20AC] forKey:@"euro"];
	}

	// Parse off numeric codes of the format #xxx
	if (entityString.length > 1 && [entityString characterAtIndex:0] == '#')
	{
		NSInteger intValue;
		if ([entityString characterAtIndex:1] == 'x')
			intValue = [entityString substringFromIndex:2].vna_hexValue;
		else
			intValue = [entityString substringFromIndex:1].integerValue;
		return [NSString stringWithFormat:@"%C", (unsigned short)MAX(intValue, ' ')];
	}

	NSString * mappedString = entityMap[entityString];
	return mappedString ? mappedString : [NSString stringWithFormat:@"&%@;", entityString];
}

/* indexOfCharacterInString
 * Returns the index of the first occurrence of the specified character at or after
 * the starting index. If no occurrence is found, returns NSNotFound.
 */
-(NSUInteger)vna_indexOfCharacterInString:(char)ch afterIndex:(NSUInteger)startIndex
{
	NSUInteger length = self.length;
	NSUInteger index;

	if (startIndex < length - 1)
		for (index = startIndex; index < length; ++index)
		{
			if ([self characterAtIndex:index] == ch)
				return index;
		}
	return NSNotFound;
}

/* hasCharacter
 * Returns YES if the specified character appears in the string. NO otherwise.
 */
-(BOOL)vna_hasCharacter:(char)ch
{
	return [self vna_indexOfCharacterInString:ch afterIndex:0] != NSNotFound;
}

/* trim
 * Removes leading and trailing whitespace from the string.
 */
-(NSString *)vna_trimmed
{
	return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

/* isBlank
 * Returns YES if the string is blank. No otherwise. A blank string is defined
 * as one comprising entirely one or more combination of spaces, tabs or newlines.
 */
-(BOOL)vna_isBlank
{
	return self.vna_trimmed.length == 0;
}

/* convertStringToValidPath
 * This function normalises a string to make it suitable for use as a path. It converts any part
 * of the string that is a 'path' separator to an underscore.
 */
-(NSString *)vna_convertStringToValidPath
{
	NSMutableString * baseURLString = [NSMutableString stringWithString:self];
    [baseURLString replaceOccurrencesOfString:@":" withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, baseURLString.length)];
	[baseURLString replaceOccurrencesOfString:@"." withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, baseURLString.length)];
	[baseURLString replaceOccurrencesOfString:@"/" withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, baseURLString.length)];
	[baseURLString replaceOccurrencesOfString:@"?" withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, baseURLString.length)];
	[baseURLString replaceOccurrencesOfString:@"*" withString:@"_" options:NSLiteralSearch range:NSMakeRange(0, baseURLString.length)];
	return baseURLString;
}

/* baseURL
 * Given a URL, this function returns the base URL.
 * Thus if the string is:
 *
 *  http://www.livejournal.com/users/stevewpalmer
 *
 * Then it returns http://www.livejournal.com. If the URL itself is the root or
 * we can't parse anything, we just return ourselves. Thus we're guaranteed to
 * return a non-nil value.
 */
-(NSString *)vna_baseURL
{
	NSURL * url = [NSURL URLWithString:self];
	return (url && url.host) ? [NSString stringWithFormat:@"%@://%@", url.scheme, url.host] : self;
}

/* host
 * Given a URL, this function returns the root of the URL minus the scheme and
 * any path. Thus if the string is:
 *
 *  http://www.livejournal.com/users/stevewpalmer
 *
 * Then it returns www.livejournal.com. If the URL itself is the root or
 * we can't parse anything, we just return ourselves. Thus we're guaranteed to
 * return a non-nil value.
 */
-(NSString *)vna_host
{
	NSURL * url = [NSURL URLWithString:self];
	return (url && url.host) ? url.host : self;
}

/* vna_caseInsensitiveNumericCompare
 * Compares two strings using both case insensitivity and numeric comparisons.
 */
- (NSComparisonResult)vna_caseInsensitiveNumericCompare:(NSString *)string
{
    return [self compare:string options:NSCaseInsensitiveSearch | NSNumericSearch];
}

/* convertHTMLEntities
 * Scan the specified string and convert HTML literal characters to their entity equivalents.
 */
+(NSString *)vna_stringByConvertingHTMLEntities:(NSString *)stringToProcess
{
    NSMutableString * newString = [NSMutableString stringWithString:stringToProcess];
    [newString vna_replaceString:@"&" withString:@"&"];
    [newString vna_replaceString:@"<" withString:@"<"];
    [newString vna_replaceString:@">" withString:@">"];
    [newString vna_replaceString:@"\"" withString:@"""];
    [newString vna_replaceString:@"'" withString:@"'"];
    return newString;
}

/* stringByCleaningURLString
 * Percent escape invalid and reserved URL characters and return a legal URL string.
 *   Should handle unescaped or partially escaped URL strings where sequences are unpredictable,
 *   for instance will preserve # announcing fragment from being escaped.
 *   User-entered URLs might contain umlauts, diacritics and other
 *   IDNA related stuff in the domain, or God knows what in filenames and arguments.
 */
+(nonnull NSString *)vna_stringByCleaningURLString:(nullable NSString *) urlString
{
    NSString * newString;
    if (urlString == nil) {
        newString = @"";
    } else {
        NSURL *url = urlFromUserString(urlString);
        if (url != nil) {
            newString = url.absoluteString;
        } else {
            newString = @"";
        }
    }
    return newString;
}

+ (NSString *)vna_toBase64String:(NSString *)string {
    NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSString * ret = [data base64EncodedStringWithOptions:0];
    return ret;
}

+ (NSString *)vna_fromBase64String:(NSString *)string {
    NSData * base64Data = [[NSData alloc] initWithBase64EncodedString:string options:0];
    NSString * decryptedStr = [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
    return decryptedStr;
}

@end


text:
package org.apache.lucene.index;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.FreqProxTermsWriterPerField.FreqProxPostingsArray;
import org.apache.lucene.util.AttributeSource; // javadocs
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;

/** Implements limited (iterators only, no stats) {@link
 *  Fields} interface over the in-RAM buffered
 *  fields/terms/postings, to flush postings through the
 *  PostingsFormat. */

class FreqProxFields extends Fields {
  final Map<String,FreqProxTermsWriterPerField> fields = new LinkedHashMap<String,FreqProxTermsWriterPerField>();

  public FreqProxFields(List<FreqProxTermsWriterPerField> fieldList) {
    // NOTE: fields are already sorted by field name
    for(FreqProxTermsWriterPerField field : fieldList) {
      fields.put(field.fieldInfo.name, field);
    }
  }

  public Iterator<String> iterator() {
    return fields.keySet().iterator();
  }

  @Override
  public Terms terms(String field) throws IOException {
    FreqProxTermsWriterPerField perField = fields.get(field);
    return perField == null ? null : new FreqProxTerms(perField);
  }

  @Override
  public int size() {
    //return fields.size();
    throw new UnsupportedOperationException();
  }

  private static class FreqProxTerms extends Terms {
    final FreqProxTermsWriterPerField terms;

    public FreqProxTerms(FreqProxTermsWriterPerField terms) {
      this.terms = terms;
    }

    @Override
    public TermsEnum iterator(TermsEnum reuse) {
      FreqProxTermsEnum termsEnum;
      if (reuse instanceof FreqProxTermsEnum && ((FreqProxTermsEnum) reuse).terms == this.terms) {
        termsEnum = (FreqProxTermsEnum) reuse;
      } else {
        termsEnum = new FreqProxTermsEnum(terms);
      }
      termsEnum.reset();
      return termsEnum;
    }

    @Override
    public long size() {
      //return terms.termsHashPerField.bytesHash.size();
      throw new UnsupportedOperationException();
    }

    @Override
    public long getSumTotalTermFreq() {
      //return terms.sumTotalTermFreq;
      throw new UnsupportedOperationException();
    }

    @Override
    public long getSumDocFreq() {
      //return terms.sumDocFreq;
      throw new UnsupportedOperationException();
    }

    @Override
    public int getDocCount() {
      //return terms.docCount;
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean hasFreqs() {
      return terms.fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
    }

    @Override
    public boolean hasOffsets() {
      // NOTE: the in-memory buffer may have indexed offsets
      // because that's what FieldInfo said when we started,
      // but during indexing this may have been downgraded:
      return terms.fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
    }

    @Override
    public boolean hasPositions() {
      // NOTE: the in-memory buffer may have indexed positions
      // because that's what FieldInfo said when we started,
      // but during indexing this may have been downgraded:
      return terms.fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
    }

    @Override
    public boolean hasPayloads() {
      return terms.hasPayloads;
    }
  }

  private static class FreqProxTermsEnum extends TermsEnum {
    final FreqProxTermsWriterPerField terms;
    final int[] sortedTermIDs;
    final FreqProxPostingsArray postingsArray;
    final BytesRef scratch = new BytesRef();
    final int numTerms;
    int ord;

    public FreqProxTermsEnum(FreqProxTermsWriterPerField terms) {
      this.terms = terms;
      this.numTerms = terms.termsHashPerField.bytesHash.size();
      sortedTermIDs = terms.sortedTermIDs;
      assert sortedTermIDs != null;
      postingsArray = (FreqProxPostingsArray) terms.termsHashPerField.postingsArray;
    }

    public void reset() {
      ord = -1;
    }

    public SeekStatus seekCeil(BytesRef text) {

      // TODO: we could instead keep the BytesRefHash
      // intact so this is a hash lookup

      // binary search:
      int lo = 0;
      int hi = numTerms - 1;
      while (hi >= lo) {
        int mid = (lo + hi) >>> 1;
        int textStart = postingsArray.textStarts[sortedTermIDs[mid]];
        terms.termsHashPerField.bytePool.setBytesRef(scratch, textStart);
        int cmp = scratch.compareTo(text);
        if (cmp < 0) {
          lo = mid + 1;
        } else if (cmp > 0) {
          hi = mid - 1;
        } else {
          // found:
          ord = mid;
          return SeekStatus.FOUND;
        }
      }

      // not found:
      ord = lo + 1;
      if (ord == numTerms) {
        return SeekStatus.END;
      } else {
        return SeekStatus.NOT_FOUND;
      }
    }

    public void seekExact(long ord) {
      this.ord = (int) ord;
      int textStart = postingsArray.textStarts[sortedTermIDs[this.ord]];
      terms.termsHashPerField.bytePool.setBytesRef(scratch, textStart);
    }

    @Override
    public BytesRef next() {
      ord++;
      if (ord >= numTerms) {
        return null;
      } else {
        int textStart = postingsArray.textStarts[sortedTermIDs[ord]];
        terms.termsHashPerField.bytePool.setBytesRef(scratch, textStart);
        return scratch;
      }
    }

    @Override
    public BytesRef term() {
      return scratch;
    }

    @Override
    public long ord() {
      return ord;
    }

    @Override
    public int docFreq() {
      // We do not store this per-term, and we cannot
      // implement this at merge time w/o an added pass
      // through the postings:
      throw new UnsupportedOperationException();
    }

    @Override
    public long totalTermFreq() {
      // We do not store this per-term, and we cannot
      // implement this at merge time w/o an added pass
      // through the postings:
      throw new UnsupportedOperationException();
    }

    @Override
    public DocsEnum docs(Bits liveDocs, DocsEnum reuse, int flags) {
      if (liveDocs != null) {
        throw new IllegalArgumentException("liveDocs must be null");
      }

      FreqProxDocsEnum docsEnum;

      if (!terms.hasFreq && (flags & DocsEnum.FLAG_FREQS) != 0) {
        // Caller wants freqs but we didn't index them;
        // don't lie:
        throw new IllegalArgumentException("did not index freq");
      }

      if (reuse instanceof FreqProxDocsEnum) {
        docsEnum = (FreqProxDocsEnum) reuse;
        if (docsEnum.postingsArray != postingsArray) {
          docsEnum = new FreqProxDocsEnum(terms, postingsArray);
        }
      } else {
        docsEnum = new FreqProxDocsEnum(terms, postingsArray);
      }
      docsEnum.reset(sortedTermIDs[ord]);
      return docsEnum;
    }

    @Override
    public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) {
      if (liveDocs != null) {
        throw new IllegalArgumentException("liveDocs must be null");
      }
      FreqProxDocsAndPositionsEnum posEnum;

      if (!terms.hasProx) {
        // Caller wants positions but we didn't index them;
        // don't lie:
        throw new IllegalArgumentException("did not index positions");
      }

      if (!terms.hasOffsets && (flags & DocsAndPositionsEnum.FLAG_OFFSETS) != 0) {
        // Caller wants offsets but we didn't index them;
        // don't lie:
        throw new IllegalArgumentException("did not index offsets");
      }

      if (reuse instanceof FreqProxDocsAndPositionsEnum) {
        posEnum = (FreqProxDocsAndPositionsEnum) reuse;
        if (posEnum.postingsArray != postingsArray) {
          posEnum = new FreqProxDocsAndPositionsEnum(terms, postingsArray);
        }
      } else {
        posEnum = new FreqProxDocsAndPositionsEnum(terms, postingsArray);
      }
      posEnum.reset(sortedTermIDs[ord]);
      return posEnum;
    }

    /**
     * Expert: Returns the TermsEnums internal state to position the TermsEnum
     * without re-seeking the term dictionary.
     * <p>
     * NOTE: A seek by {@link TermState} might not capture the
     * {@link AttributeSource}'s state. Callers must maintain the
     * {@link AttributeSource} states separately
     *
     * @see TermState
     * @see #seekExact(BytesRef, TermState)
     */
    public TermState termState() throws IOException {
      return new TermState() {
        @Override
        public void copyFrom(TermState other) {
          throw new UnsupportedOperationException();
        }
      };
    }
  }

  private static class FreqProxDocsEnum extends DocsEnum {

    final FreqProxTermsWriterPerField terms;
    final FreqProxPostingsArray postingsArray;
    final ByteSliceReader reader = new ByteSliceReader();
    final boolean readTermFreq;
    int docID;
    int freq;
    boolean ended;
    int termID;

    public FreqProxDocsEnum(FreqProxTermsWriterPerField terms, FreqProxPostingsArray postingsArray) {
      this.terms = terms;
      this.postingsArray = postingsArray;
      this.readTermFreq = terms.hasFreq;
    }

    public void reset(int termID) {
      this.termID = termID;
      terms.termsHashPerField.initReader(reader, termID, 0);
      ended = false;
      docID = 0;
    }

    @Override
    public int docID() {
      return docID;
    }

    @Override
    public int freq() {
      // Don't lie here ... don't want codecs writings lots
      // of wasted 1s into the index:
      if (!readTermFreq) {
        throw new IllegalStateException("freq was not indexed");
      } else {
        return freq;
      }
    }

    @Override
    public int nextDoc() throws IOException {
      if (reader.eof()) {
        if (ended) {
          return NO_MORE_DOCS;
        } else {
          ended = true;
          docID = postingsArray.lastDocIDs[termID];
          if (readTermFreq) {
            freq = postingsArray.termFreqs[termID];
          }
        }
      } else {
        int code = reader.readVInt();
        if (!readTermFreq) {
          docID += code;
        } else {
          docID += code >>> 1;
          if ((code & 1) != 0) {
            freq = 1;
          } else {
            freq = reader.readVInt();
          }
        }

        assert docID != postingsArray.lastDocIDs[termID];
      }

      return docID;
    }

    @Override
    public int advance(int target) {
      throw new UnsupportedOperationException();
    }

    @Override
    public long cost() {
      throw new UnsupportedOperationException();
    }
  }

  private static class FreqProxDocsAndPositionsEnum extends DocsAndPositionsEnum {

    final FreqProxTermsWriterPerField terms;
    final FreqProxPostingsArray postingsArray;
    final ByteSliceReader reader = new ByteSliceReader();
    final ByteSliceReader posReader = new ByteSliceReader();
    final boolean readOffsets;
    int docID;
    int freq;
    int pos;
    int startOffset;
    int endOffset;
    int posLeft;
    int termID;
    boolean ended;
    boolean hasPayload;
    BytesRef payload = new BytesRef();

    public FreqProxDocsAndPositionsEnum(FreqProxTermsWriterPerField terms, FreqProxPostingsArray postingsArray) {
      this.terms = terms;
      this.postingsArray = postingsArray;
      this.readOffsets = terms.hasOffsets;
      assert terms.hasProx;
      assert terms.hasFreq;
    }

    public void reset(int termID) {
      this.termID = termID;
      terms.termsHashPerField.initReader(reader, termID, 0);
      terms.termsHashPerField.initReader(posReader, termID, 1);
      ended = false;
      docID = 0;
      posLeft = 0;
    }

    @Override
    public int docID() {
      return docID;
    }

    @Override
    public int freq() {
      return freq;
    }

    @Override
    public int nextDoc() throws IOException {
      while (posLeft != 0) {
        nextPosition();
      }

      if (reader.eof()) {
        if (ended) {
          return NO_MORE_DOCS;
        } else {
          ended = true;
          docID = postingsArray.lastDocIDs[termID];
          freq = postingsArray.termFreqs[termID];
        }
      } else {
        int code = reader.readVInt();
        docID += code >>> 1;
        if ((code & 1) != 0) {
          freq = 1;
        } else {
          freq = reader.readVInt();
        }

        assert docID != postingsArray.lastDocIDs[termID];
      }

      posLeft = freq;
      pos = 0;
      startOffset = 0;
      return docID;
    }

    @Override
    public int advance(int target) {
      throw new UnsupportedOperationException();
    }

    @Override
    public long cost() {
      throw new UnsupportedOperationException();
    }

    @Override
    public int nextPosition() throws IOException {
      assert posLeft > 0;
      posLeft--;
      int code = posReader.readVInt();
      pos += code >>> 1;
      if ((code & 1) != 0) {
        hasPayload = true;
        // has a payload
        payload.length = posReader.readVInt();
        if (payload.bytes.length < payload.length) {
          payload.grow(payload.length);
        }
        posReader.readBytes(payload.bytes, 0, payload.length);
      } else {
        hasPayload = false;
      }

      if (readOffsets) {
        startOffset += posReader.readVInt();
        endOffset = startOffset + posReader.readVInt();
      }

      return pos;
    }

    @Override
    public int startOffset() {
      if (!readOffsets) {
        throw new IllegalStateException("offsets were not indexed");
      }
      return startOffset;
    }

    @Override
    public int endOffset() {
      if (!readOffsets) {
        throw new IllegalStateException("offsets were not indexed");
      }
      return endOffset;
    }

    @Override
    public BytesRef getPayload() {
      if (hasPayload) {
        return payload;
      } else {
        return null;
      }
    }
  }
}


text:
import math

class Heap:
	def __init__(self,values):
		self.values = values
		self.build_max_heap()

	def __str__(self):
		return str(self.values)

	def size(self):
		return len(self.values)

	def leftChild(self,node):
		return 2*node

	def rightChild(self,node):
		return 2*node+1

	def max_heapify(self,node):
		left = self.leftChild(node)
		right = self.rightChild(node)

		if (left <= self.size() and self.values[left-1] > self.values[node-1]):
			largestNode = left
		else:
			largestNode = node

		if (right<= self.size() and self.values[right-1] > self.values[largestNode-1]):
			largestNode = right

		if (largestNode != node):
			self.values[node-1],self.values[largestNode-1] = self.values[largestNode-1],self.values[node-1]
			self.max_heapify(largestNode)

	def build_max_heap(self):
		node=int(len(self.values)/2)
		print "Node: %s" % ((node,))
		while (node > 0):
			self.max_heapify(node)
			node -= 1

def copyToPrintTuple(self,printList,spaceNumber):
	for x in xrange(spaceNumber):
		spaceStr += " "

	for x in printList:
		printTuple += (spaceStr,x)

	return printTuple

def draw(self):
	levels = int(math.log(self.size(),2))

	for x in xrange(levels+1):
		printStr = " "
		for y in xrange(2**x):
			printStr += "%s%s"
		print printStr % (self.copyToPrintTuple(self.values[2**(levels-1))

myList=[1,2,3,4,5,6,11,21,12,15,19,20,4,5,7,2,20]
#myList=[1,2,3]
print myList
myHeap = Heap(myList)
print myHeap


text:
#!/usr/bin/env node
var commandLineArgs = require("command-line-args")
, colors = require('colors')
, options = commandLineArgs([
  { name: "port", alias: "P", type: Number, defaultValue: 3000 },
  { name: "allowCORS", alias: "C", type: Boolean, defaultValue: false },
  { name: "help", alias: "H", type: Boolean, defaultValue: false }
])
, directory = process.argv[2] || "."
, commandLineUsage = require('command-line-usage')
, usage = commandLineUsage(/*templateData*/)
  ;

if(options.help){
  console.log(usage);
  console.log("# ".gray + "json-rest-server ../mydirectory -P 3000\n".cyan);
}else{
  try{
    require("./index.js")(directory, options.port, options.allowCORS)();
  }catch(err){
    console.error("You must insert a valid path as parameter".red + "\nTry with something like this: ".grey + "json-rest-server ../mydirectory".cyan);
    console.log(usage)
  }
}


text:
module GolfSwitch
  class CoursePolicyResponse
    attr_accessor :ret_cd,:ret_msg,:note,:cxl_policy,:rate_policy,:misc_policies
    def initialize(attributes={})
      attributes.each do |name, value|
        begin
          if  name.to_s =="cxl_policy"
            @cxl_policy = GolfSwitch::CoursePolicy.new(value)
          else
            send("#{name}=", value)
          end
        rescue
          puts "Add #{name} is accessor in course policy response"
        end
      end
    end
  end
end


text:
package org.drools.workbench.screens.guided.dtable.client.wizard.column.pages;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.gwtbootstrap3.client.ui.ListBox;
import org.jboss.errai.common.client.dom.Div;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class AttributeColumnPageViewTest {

    @Mock
    private AttributeColumnPage page;

    private AttributeColumnPageView view;

    @Before
    public void setUp() throws Exception {
        view  = spy(new AttributeColumnPageView(mock(ListBox.class), mock(Div.class)));
        view.init(page);
    }

    @Test
    public void testInitView() throws Exception {
        verify(view).hideAttributeDescription();
    }

    @Test
    public void testAttributeSelectedFirstTime() throws Exception {
        when(view.isAttributeDescriptionHidden()).thenReturn(true);
        view.onSelectAttribute(null);

        verify(view).showAttributeDescription();
    }

    @Test
    public void testAttributeSelectedNotFirstTime() throws Exception {
        when(view.isAttributeDescriptionHidden()).thenReturn(false);
        view.onSelectAttribute(null);

        verify(view, never()).showAttributeDescription();
    }
}


text:
title: "Fullstack Academy - Week 6 & Review Week"
date: 2015-07-25
description: "July 13th to July 17th. There are 52 days of Fullstack Academy. These are days 29 through 33 (Week 6). There's also review week, which is from July 20th to July 24. Review week doesn't count as Fullstack Academy. ❤🃏"
image: https://i.imgur.com/zuKA2c2.jpg
aliases:
  - /2015/07/25/fullstack-academy-week-6-review-week/
categories:
  - blog
---

> July 13th to July 17th
>
> There are ~~57~~ 52 days of [**Fullstack Academy**](https://www.fullstackacademy.com).
>
> These are days 29 through 33 (Week 6).
>
> There's also review week, which is from July 20th to July 24. Review week doesn't count as Fullstack Academy. ;)
>
> ❤

## Day One - Monday

- This is my last week as a junior. I guess I could go all cliche here and say that time flew by, but eh, to be honest, I've time traveled in a pretty normal way, which does surprise me.
- I didn't go to school today. I was super sick. :(

![Shaping up with
Angular](https://s3.amazonaws.com/accredible_courses/images/11072/original/shaping-up-with-angular-js-ec0c2defe370994018c29f0b65e56a3b.jpg)

- Thankfully, since we covered angular directives and `ng-model` today, it wasn't that bad since I finished that **Shaping up with Angular.js** Code School course.

## Day Two - Tuesday

- More work on the flashcards application.

## Day Three - Wednesday

- Today, my partner Yves and I were the only team that showcased a flashcard design. So by default, we both won and lost the mini-competition for the best flashcard design. We each get a Fullstack t-shirt (I still haven't gotten this yet -\_\_-).
- Here's how the home page for our design ended up looking like, more or less: ![HomePage](https://i.imgur.com/8Lh7IJw.png)
- We used [FlatUI](https://designmodo.github.io/Flat-UI/), naturally.

## Day Four - Thursday

- Spelunking.
- Second day working on authentication.
- Learning team lunch today. I'm getting better at Avalon. 😈

## Day Five - Friday

- More auth stuff.
- Last day of being a junior!!!
- My contribution to Fullstack so far has been this [Google Slide deck](https://www.slideshare.net/FVCproductions/2015-0618-awesome-web-dev-tips-amp-tricks-fullstack-academy) showcasing a bunch of web dev stuff I feel is relevant. I should probably update it soon. ![Fullstack Web Dev Tips and Tricks](https://i.imgur.com/hDbtU5A.png)
- We go over what's going to be in senior phase.
  - Unfortunately, I think I will only be able to work with other college of code students on my final project, since we have 2 less weeks. I don't know how I feel about this since I wanted to work with Yves, who isn't in the summer of code program, since we have complementary skills (my strong suite is front-end, his is back-end). Darn.

> :arrow: **Overall Conclusion?**
>
> > I'm a senior in every aspect now!
> >
> > ![Keep Calm Terminal
Style](https://sd.keepcalm-o-matic.co.uk/i/keep-calm-because-finally-i-m-senior-8.png)

## Review Week!

### A week where we get a break from Fullstack, take some review assessments, and get the opportunity to revitalize for the intense project phase ahead of us.

> Monday through Wednesday

- Normally, I publish my posts every Friday, but since review week is right after my last junior week, I figured I'd just publish the Friday or Saturday of review week instead.
- I went back home and relaxed for most of this week.
  - Thankfully, the first three assessments for this week weren't mandatory.

> Thursday

- I'm the only person from 1506 who went to Game Night today. I played this creepy and descriptive house game. It was terribly complicated, but it was macabre enough to be somewhat enjoyable. 😈

> Friday

- I got to 4 kyu on [Codewars](https://codewars.com/users/fvcproductions) today. FINALLLLLLYYYY.
- While working late, I come across this show called [**Dating Naked**](https://www.wikiwand.com/en/Dating_Naked) and I'm just blown away. `#reviewweeksurprise`
- I'm pretty excited for the project phase. :)

> Saturday

- This Saturday, I'll be attending the [Sally Conference](https://www.meetup.com/WomenWhoCodeNYC/events/223064683/). The tickets are **300 DOLLARS**, but Shanna G., who is part of the hiring team here at Fullstack, had some free tickets to give out - so to you, Shanna, I say...

![Thank you.](https://media.giphy.com/media/3oEduJnper1UdNqreg/giphy.gif)

![Sally Conference](https://i.imgur.com/WYxXPZQ.png)


text:
class AddAnonymousToComments < ActiveRecord::Migration
  def change
      add_column :comments, :anonymous, :string
  end
end


text:
package com.izforge.izpack.panels.licence;

import com.izforge.izpack.api.resource.Resources;
import com.izforge.izpack.installer.console.ConsolePanel;
import com.izforge.izpack.installer.panel.PanelView;

/**
 * Console based Licence Panel.
 */
public class LicenceConsolePanel extends AbstractLicenceConsolePanel
{
    /**
     * Constructs a {@code LicenceConsolePanel}.
     *
     * @param resources the resources
     * @param panel     the parent panel/view. May be {@code null}
     */
    public LicenceConsolePanel(Resources resources, PanelView<ConsolePanel> panel)
    {
        super(panel, resources);
    }

    /**
     * Returns the text to display.
     *
     * @return the text. A <tt>null</tt> indicates failure
     */
    @Override
    protected String getText()
    {
        return loadLicenceAsString();
    }

}


text:
using System;
using MvvmCross.Binding.BindingContext;
using MvvmCross.Binding.iOS.Views;
using MvvmCross.iOS.Views;
using MvvmCross.Platform;
using TwilightImperiumMasterCompanion.Core.ViewModels;
using UIKit;

namespace TwilightImperiumMasterCompanion.iOS.ViewControllers.Planet
{
    public partial class AddPlanetView : MvxTableViewController<AddPlanetViewModel>
    {
        public AddPlanetView()
        {
			this.Title = AddPlanetViewModel.Title;
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var source = new MvxStandardTableViewSource(TableView, "TitleText Name;");
            TableView.Source = source;

            //Bindings
            var set = this.CreateBindingSet<AddPlanetView, AddPlanetViewModel>();
            set.Bind(source).For(v => v.ItemsSource).To(vm => vm.Planets);
            set.Apply();
        }
    }
}