text:
module Fog
  module Compute
    class VcloudDirector
      class Real
        require 'fog/vcloud_director/generators/compute/org_vdc_network'

        # Update an Org vDC network.
        #
        # This operation is asynchronous and returns a task that you can
        # monitor to track the progress of the request.
        #
        # Produce media type(s):
        # application/vnd.vmware.vcloud.orgVdcNetwork+xml
        # Output type:
        # TaskType
        #
        # @param [String] id Object identifier of the network
        # @param [String] name   The name of the entity.
        # @param [Hash] options
        # @option options [String] :Description Optional description.
        # @option options [Hash] :Configuration Network configuration.
        # @option options [Hash] :EdgeGateway  EdgeGateway that connects this
        #   Org vDC network. Applicable only for routed networks.
        # @option options [Hash] :ServiceConfig Specifies the service
        #   configuration for an isolated Org vDC networks.
        # @option options [Boolean] :IsShared True if this network is shared
        #   to multiple Org vDCs.
        #   * :Configuration<~Hash>: NetworkConfigurationType
        #     * :IpScopes<~Hash>:
        #       * :IpScope<~Hash>:
        #         * :IsInherited<~Boolean>: ?
        #         * :Gateway<~String>: IP address of gw
        #         * :Netmask<~String>: Subnet mask of network
        #         * :Dns1<~String>: Primary DNS server.
        #         * :Dns2<~String>: Secondary DNS server.
        #         * :DnsSuffix<~String>: DNS suffix.
        #         * :IsEnabled<~String>: Indicates if subnet is enabled or not.
        #                                Default value is True.
        #         * :IpRanges<~Array>: IP ranges used for static pool allocation
        #                             in the network. Array of Hashes of:
        #                               * :StartAddress - start IP in range
        #                               * :EndAddress - end IP in range
        #   * :EdgeGateway<~Hash>: EdgeGateway that connects this Org vDC
        #                          network. Applicable only for routed networks.
        #   * :ServiceConfig<~Hash>: Specifies the service configuration for an
        #                            isolated network
        #
        # @return [Excon::Response]
        #   * body<~Hash>:
        #
        # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CreateOrgVdcNetwork.html
        # @since vCloud API version 5.1
        def put_network(id, name, options={})
          body = Fog::Generators::Compute::VcloudDirector::OrgVdcNetwork.new(options.merge(:name => name)).generate_xml

          request(
            :body    => body,
            :expects => 202,
            :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'},
            :method  => 'PUT',
            :parser  => Fog::ToHashDocument.new,
            :path    => "admin/network/#{id}"
          )
        end
      end

      class Mock
        def put_network(id, name, options={})
          original_network = data[:networks][id]
          unless original_network
            raise Fog::Compute::VcloudDirector::Forbidden.new(
              "No access to entity \"(com.vmware.vcloud.entity.orgVdcNetwork:#{id})\"."
            )
          end

          type = 'network'

          # Description
          # Configuration
          #   IpScopes
          #     IpScope
          #       IsInherited
          #       Gateway
          #       Netmask
          #       Dns1
          #       Dns2
          #       DnsSuffix
          #       IsEnabled
          #       IpRanges
          #         IpRange
          #           StartAddress
          #           EndAddress
          #   FenceMode
          # EdgeGateway
          # IsShared
          #
          vdc_id = original_network[:vdc],

          network_body = {
            :name => name,
            :vdc  => vdc_id,
          }

          [:Description, :IsShared].each do |key|
            network_body[key] = options[key] if options.key?(key)
          end

          if options.key?(:EdgeGateway)
            network_body[:EdgeGateway] =
              options[:EdgeGateway][:href].split('/').last
          end

          if configuration = options[:Configuration]
            if ip_scopes = configuration[:IpScopes]
              if ip_scope = ip_scopes[:IpScope]
                [:IsInherited, :Gateway, :Netmask,
                  :Dns1, :Dns2, :DnsSuffix, :IsEnabled].each do |key|
                    network_body[key] = ip_scope[key] if ip_scope.key?(key)
                end
                if ip_ranges = ip_scope[:IpRanges]
                  network_body[:IpRanges] = []
                  ip_ranges.each do |ipr|
                    network_body[:IpRanges] << {
                      :StartAddress => ipr[:IpRange][:StartAddress],
                      :EndAddress   => ipr[:IpRange][:EndAddress]
                    }
                  end
                end
              end
            end
            network_body[:FenceMode] = configuration[:FenceMode] if ip_scope.key?(:FenceMode)
          end

          owner = {
            :href => make_href("#{type}/#{id}"),
            :type => "application/vnd.vmware.vcloud.#{type}+xml"
          }
          task_id = enqueue_task(
            "Updating #{type} #{name} (#{id})", 'networkUpdateNetwork', owner,
            :on_success => lambda do
              data[:networks][id] = network_body
            end
          )
          task = task_body(task_id)
          task.delete(:Owner) #known-bug: admin-api does not return owner.
          body = {
              :xmlns => xmlns,
              :xmlns_xsi => xmlns_xsi,
              :xsi_schemaLocation => xsi_schema_location,
          }.merge(task)

          Excon::Response.new(
            :status => 202,
            :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"},
            :body => body
          )

        end
      end
    end
  end
end


text:
#include "connection_lib.h"
#include "wasm_export.h"
#include "native_interface.h"
#include "connection_native_api.h"

/* Note:
 *
 * This file is the consumer of connection lib which is implemented by different
 * platforms
 */

uint32
wasm_open_connection(wasm_exec_env_t exec_env, char *name, char *args_buf,
                     uint32 len)
{
    wasm_module_inst_t module_inst = get_module_inst(exec_env);
    attr_container_t *args;

    args = (attr_container_t *)args_buf;

    if (connection_impl._open != NULL)
        return connection_impl._open(module_inst, name, args);

    return -1;
}

void
wasm_close_connection(wasm_exec_env_t exec_env, uint32 handle)
{
    if (connection_impl._close != NULL)
        connection_impl._close(handle);
}

int
wasm_send_on_connection(wasm_exec_env_t exec_env, uint32 handle, char *data,
                        uint32 len)
{
    if (connection_impl._send != NULL)
        return connection_impl._send(handle, data, len);

    return -1;
}

bool
wasm_config_connection(wasm_exec_env_t exec_env, uint32 handle, char *cfg_buf,
                       uint32 len)
{
    attr_container_t *cfg;

    cfg = (attr_container_t *)cfg_buf;

    if (connection_impl._config != NULL)
        return connection_impl._config(handle, cfg);

    return false;
}

redpajama_set_name: RedPajamaGithub


text:
package consumer.kafka.client;

import java.io.Serializable;
import java.util.Properties;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.Time;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import consumer.kafka.MessageAndMetadata;
import consumer.kafka.ReceiverLauncher;

public class Consumer implements Serializable {

	private static final long serialVersionUID = 4332618245650072140L;

	public void start() throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {

		run();
	}

	private void run() {

		Properties props = new Properties();
		props.put("zookeeper.hosts", "10.252.5.131");
		props.put("zookeeper.port", "2181");
		props.put("zookeeper.broker.path", "/brokers");
		props.put("kafka.topic", "valid_subpub");
		props.put("kafka.consumer.id", "valid_subpub");
		props.put("zookeeper.consumer.connection", "10.252.5.113:2182");
		props.put("zookeeper.consumer.path", "/kafka-new");

		SparkConf _sparkConf = new SparkConf().setAppName("KafkaReceiver")
				.set("spark.streaming.receiver.writeAheadLog.enable", "false");;

		JavaStreamingContext jsc = new JavaStreamingContext(_sparkConf,
				new Duration(10000));

		//Specify number of Receivers you need.
		//It should be less than or equal to number of Partitions of your topic

		int numberOfReceivers = 3;

		JavaDStream<MessageAndMetadata> unionStreams = ReceiverLauncher.launch(jsc, props, numberOfReceivers);

		unionStreams
				.foreachRDD(new Function2<JavaRDD<MessageAndMetadata>, Time, Void>() {

					@Override
					public Void call(JavaRDD<MessageAndMetadata> rdd,
							Time time) throws Exception {

						System.out.println("Number of records in this Batch is " + rdd.count());
						return null;
					}
				});

		jsc.start();
		jsc.awaitTermination();
	}

	public static void main(String[] args) throws Exception {

		Consumer consumer = new Consumer();
		consumer.start();
	}
}


text:
<!DOCTYPE html>

    <title>Overview</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />

json v0.3.0 → Overview

json v0.3.0

Modules

Exceptions

Protocols

Modules summary ↑

  JSON

  JSON.Dynamo.Filter

  JSON.Dynamo.Filter.FilterResultObject

  JSON.Dynamo.Filter.ProcessFilteredResponse

  JSON.Encoder.Helpers

Helper functions for writing JSON.Encoder instances

  JSON.Parser.Bitstring

  JSON.Parser.Bitstring.Array

  JSON.Parser.Bitstring.Number

  JSON.Parser.Bitstring.Object

  JSON.Parser.Bitstring.String

  JSON.Parser.Charlist

  JSON.Parser.Charlist.Array

  JSON.Parser.Charlist.Number

  JSON.Parser.Charlist.Object

  JSON.Parser.Charlist.String

Exceptions summary ↑

  JSON.Decoder.Error

  JSON.Decoder.UnexpectedEndOfBufferError

  JSON.Decoder.UnexpectedTokenError

  JSON.Encoder.Error

Protocols summary ↑

  JSON.Decoder

Defines the protocol required for converting raw JSON into Elixir terms

  JSON.Encoder

Defines the protocol required for converting Elixir types into JSON and inferring their json types


text:
/* @test
 * @bug 6364692
 * @summary When the "java.rmi.server.randomIDs" system property is
 * not defined, the ObjID() constructor should behave as if it were
 * set to "true" and generate random object numbers; if the property
 * is defined to something other than "true" (ignoring case), then
 * ObjID() should still generate sequential object numbers.
 * @author Peter Jones
 *
 * @run main/othervm RandomIDs random
 * @run main/othervm -Djava.rmi.server.randomIDs=true RandomIDs random
 * @run main/othervm -Djava.rmi.server.randomIDs=false RandomIDs sequential
 */

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.rmi.server.ObjID;

public class RandomIDs {
    private static final int COUNT = 10000;

    public static void main(String[] args) throws Exception {
        boolean shouldBeRandom = false;
        boolean shouldBeSequential = false;

        String usage = "Usage: java RandomIDs [random|sequential]";
        if (args.length != 1) {
            System.err.println(usage);
            throw new Error("wrong number of arguments");
        } else if (args[0].equals("random")) {
            shouldBeRandom = true;
        } else if (args[0].equals("sequential")) {
            shouldBeSequential = true;
        } else {
            System.err.println(usage);
            throw new Error("invalid argument");
        }

        System.err.println("\nRegression test for bug 6364692\n");
        String propertyValue = System.getProperty("java.rmi.server.randomIDs");
        System.err.println(
            "Value of java.rmi.server.randomIDs system property: " +
            (propertyValue != null ? "\"" + propertyValue + "\"" : null));
        System.err.println(
            "Expecting object numbers of unique ObjIDs to be: " + args[0]);

        /*
         * Get the 64-bit "object number" component of COUNT number of
         * unique (not "well-known") ObjID instances created in
         * sequence, by writing each to a dummy ObjectOutputStream and
         * trapping the first writeLong invocation on the stream.
         */
        final long[] objnums = new long[COUNT];
        for (int i = 0; i < COUNT; i++) {
            final int j = i;
            class Escape extends RuntimeException { }
            try {
                new ObjID().write(new ObjectOutputStream(new OutputStream() {
                    public void write(int b) { }
                }) {
                    public void writeLong(long val) throws IOException {
                        objnums[j] = val;
                        throw new Escape();
                    }
                });
                throw new Error("writeLong not invoked");
            } catch (Escape e) {
            }
        }

        /*
         * If the object numbers should be random, then verify that
         * they are.  (This verification is certainly not a thorough
         * evaluation of randomness, but it performs a couple of
         * simple checks to catch mistakes in ObjID's application of a
         * CSPRNG: are roughly half the bits set, and can the sequence
         * be used to get a rough Monte Carlo estimate of pi.  Errors
         * up to 5% are tolerated for both checks.)
         */
        if (shouldBeRandom) {
            int bitCount = 0;
            int piHitCount = 0;
            for (int i = 0; i < COUNT; i++) {
                bitCount += Long.bitCount(objnums[i]);
                double x = ((double) (objnums[i] >>> 32)) / (1L << 32);
                double y = ((double) (objnums[i] & 0xFFFFFFFFL)) / (1L << 32);
                if (((x * x) + (y * y)) <= 1.0) {
                    piHitCount++;
                }
            }

            int bitCountTarget = COUNT * 32;
            double bitCountError =
                ((double) (bitCount - bitCountTarget)) / bitCountTarget;
            if (Math.abs(bitCountError) > 0.05) { // tolerate 5% error
                throw new Error("TEST FAILED: " +
                                "bitCount == " + bitCount);
            }

            double piEstimate = ((double) piHitCount / COUNT) * 4.0;
            double piEstimateError = (piEstimate - Math.PI) / Math.PI;
            if (Math.abs(piEstimateError) > 0.05) { // tolerate 5% error
                throw new Error("TEST FAILED: " +
                                "piEstimate == " + piEstimate);
            }
        }

        /*
         * If the object numbers should be sequential, then verify
         * that they are.
         */
        if (shouldBeSequential) {
            long first = objnums[0];
            /*
             * This test currently verifies that the first object
             * number is zero, but that could be false if one or more
             * remote objects get exported as part of VM startup-- if
             * that starts happening, this check could be relaxed.
             */
            if (first != 0) {
                throw new Error("TEST FAILED: " +
                                "first object number == " + first +
                                " (not zero)");
            }
            for (int i = 1; i < COUNT; i++) {
                if (objnums[i] != first + i) {
                    throw new Error("TEST FAILED: first == " + first + ", " +
                                    "objnums[" + i + "] == " + objnums[i]);
                }
            }
        }

        System.err.println("TEST PASSED");
    }
}


text:
package org.radargun.stats;

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

import org.radargun.Operation;

/**
 * Keeps a series of {@link Statistics} instances and records the requests according to current timestamp.
 * Result retrieval needs special handling using the {@link #asList()} method.
 *
 * Useful when the request response time is expected to change during the test execution.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class PeriodicStatistics extends IntervalStatistics {
   private final Statistics prototype;
   private final long period;
   private final List<Statistics> buckets;

   public PeriodicStatistics(Statistics prototype, long period) {
      this.prototype = prototype;
      this.period = period;
      this.buckets = new ArrayList<Statistics>();
   }

   public PeriodicStatistics(PeriodicStatistics other) {
      this.prototype = other.prototype;
      this.period = other.period;
      this.buckets = new ArrayList<Statistics>(other.buckets.size());
      for (Statistics s : other.buckets) {
         this.buckets.add(s.copy());
      }
   }

   private Statistics getCurrentBucket() {
      long currentTime = System.currentTimeMillis();
      int bucket = (int)((currentTime - getBegin()) / period);
      while (buckets.size() <= bucket) {
         buckets.add(prototype.copy());
      }
      return buckets.get(bucket);
   }

   @Override
   public void registerRequest(long responseTime, Operation operation) {
      getCurrentBucket().registerRequest(responseTime, operation);
   }

   @Override
   public void registerError(long responseTime, Operation operation) {
      getCurrentBucket().registerError(responseTime, operation);
   }

   @Override
   public Statistics newInstance() {
      return new PeriodicStatistics(prototype, period);
   }

   @Override
   public void reset() {
      buckets.clear();
   }

   @Override
   public Statistics copy() {
      return new PeriodicStatistics(this);
   }

   @Override
   public void merge(Statistics otherStats) {
      throw new UnsupportedOperationException();
   }

   @Override
   public Map<String, OperationStats> getOperationsStats() {
      throw new UnsupportedOperationException();
   }

   @Override
   public <T> T[] getRepresentations(Class<T> clazz) {
      throw new UnsupportedOperationException();
   }

   public List<Statistics> asList() {
      return Collections.unmodifiableList(buckets);
   }
}


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

namespace NinthChevron.Collections
{
#if !NET40

    public interface IAsyncEnumerable
    {
        IAsyncEnumerator GetEnumerator();
    }

#endif
}


text:
require "passphrase"

module Passphrase
  RSpec.describe DicewareMethod, "implements the Diceware method" do
    it "responds to the class method run() with one argument" do
      expect(DicewareMethod).to respond_to(:run).with(1).argument
    end

    context "initialized with default options" do
      before do
        @diceware = DicewareMethod.new(Default.options)
      end

      it "responds to the run() method with no arguments" do
        expect(@diceware).to respond_to(:run)
      end

      it "does not respond to the get_random_languages() method (private)" do
        expect(@diceware).not_to respond_to(:get_random_languages)
      end

      it "does not respond to the get_random_random_die_rolls() method (private)" do
        expect(@diceware).not_to respond_to(:get_random_random_die_rolls)
      end

      it "does not respond to the select_words_from_wordlist() method (private)" do
        expect(@diceware).not_to respond_to(:select_words_from_wordlist)
      end

      describe "#run" do
        before do
          @result = @diceware.run
        end

        it "returns an array of three arrays" do
          expect(@result).to contain_exactly(
            an_instance_of(Array),
            an_instance_of(Array),
            an_instance_of(Array)
          )
        end

        it "each array contains the default number of words elements" do
          @result.each do |result|
            expect(result.size).to eq(Default.options[:number_of_words])
          end
        end

        it "each array contains String elements" do
          @result.each do |result|
            result.each do |element|
              expect(element).to be_an_instance_of(String)
            end
          end
        end
      end
    end
  end
end


text:
package org.assertj.core.internal.shorts;

import static org.assertj.core.test.TestData.someInfo;

import static org.junit.Assert.assertEquals;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Shorts;
import org.assertj.core.internal.ShortsBaseTest;
import org.junit.Test;

/**
 * Tests for <code>{@link Shorts#assertIsNotZero(AssertionInfo, Comparable)}</code>.
 *
 * @author Alex Ruiz
 * @author Joel Costigliola
 */
public class Shorts_assertIsNotZero_Test extends ShortsBaseTest {

  @Test
  public void should_succeed_since_actual_is_not_zero() {
    shorts.assertIsNotZero(someInfo(), (short) 2);
  }

  @Test
  public void should_fail_since_actual_is_zero() {
    thrown.expectAssertionError("\nExpecting:\n <0>\nnot to be equal to:\n <0>\n");
    shorts.assertIsNotZero(someInfo(), (short) 0);
  }

  @Test
  public void should_succeed_since_actual_is_zero_whatever_custom_comparison_strategy_is() {
    shortsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), (short) 1);
  }

  @Test
  public void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() {
    try {
      shortsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), (short) 0);
    } catch (AssertionError e) {
      assertEquals(e.getMessage(), "\nExpecting:\n <0>\nnot to be equal to:\n <0>\n");
    }
  }

}


text:
package org.multiverse.api.exceptions;

/**
 * An {@link IllegalStateException} throw when there is a conflict with the {@link org.multiverse.api.Txn}
 * propagation. For more information {@link org.multiverse.api.PropagationLevel}.
 *
 * @author Peter Veentjer.
 */
public class PropagationException extends TxnExecutionException {

    private static final long serialVersionUID = 0;

    /**
     * Creates a new PropagationException.
     */
    public PropagationException() {
    }

    /**
     * Creates a new PropagationException with the provided message.
     *
     * @param message the message of the exception.
     */
    public PropagationException(String message) {
        super(message);
    }

    /**
     * Creates a new PropagationException with the provided message and cause.
     *
     * @param message the message of the exception
     * @param cause   the cause of the exception.
     */
    public PropagationException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2010 Tatsuhiro Tsujikawa
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "Cookie.h"

#include <sstream>

#include "A2STR.h"
#include "a2functional.h"
#include "cookie_helper.h"

namespace aria2 {

Cookie::Cookie
(std::string name,
 std::string value,
 time_t  expiryTime,
 bool persistent,
 std::string domain,
 bool hostOnly,
 std::string path,
 bool secure,
 bool httpOnly,
 time_t creationTime):
  name_(std::move(name)),
  value_(std::move(value)),
  expiryTime_(expiryTime),
  persistent_(persistent),
  domain_(std::move(domain)),
  hostOnly_(hostOnly),
  path_(std::move(path)),
  secure_(secure),
  httpOnly_(httpOnly),
  creationTime_(creationTime),
  lastAccessTime_(creationTime) {}

Cookie::Cookie():
  expiryTime_(0),
  persistent_(false),
  hostOnly_(false),
  secure_(false),
  httpOnly_(false),
  creationTime_(0),
  lastAccessTime_(0) {}

std::string Cookie::toString() const
{
  std::string s = name_;
  s += "=";
  s += value_;
  return s;
}

bool Cookie::match
(const std::string& requestHost,
 const std::string& requestPath,
 time_t date, bool secure) const
{
  if((secure_ && !secure) || isExpired(date) ||
     !cookie::pathMatch(requestPath, path_)) {
    return false;
  }
  if(hostOnly_) {
    return requestHost == domain_ ;
  } else {
    return cookie::domainMatch(requestHost, domain_);
  }
}

bool Cookie::operator==(const Cookie& cookie) const
{
  return domain_ == cookie.domain_ && path_ == cookie.path_ &&
    name_ == cookie.name_;
}

bool Cookie::operator!=(const Cookie& cookie) const
{
  return !(*this == cookie);
}

bool Cookie::isExpired(time_t base) const
{
  return persistent_ && base > expiryTime_;
}

std::string Cookie::toNsCookieFormat() const
{
  std::stringstream ss;
  if(!hostOnly_) {
    ss << ".";
  }
  ss << domain_ << "\t";
  if(hostOnly_) {
    ss << "FALSE";
  } else {
    ss << "TRUE";
  }
  ss << "\t";
  ss << path_ << "\t";
  if(secure_) {
    ss << "TRUE";
  } else {
    ss << "FALSE";
  }
  ss << "\t";
  if(persistent_) {
    ss << expiryTime_;
  } else {
    ss << 0;
  }
  ss << "\t";
  ss << name_ << "\t";
  ss << value_;
  return ss.str();
}

void Cookie::setName(std::string name)
{
  name_ = std::move(name);
}

void Cookie::setValue(std::string value)
{
  value_ = std::move(value);
}

void Cookie::setDomain(std::string domain)
{
  domain_ = std::move(domain);
}

void Cookie::setPath(std::string path)
{
  path_ = std::move(path);
}

} // namespace aria2


text:
package ie.macinnes.tvheadend;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.tv.TvContract;
import android.media.tv.TvContract.Channels;
import android.net.Uri;
import android.util.Log;
import android.util.SparseArray;

public class TvContractUtils {
    private static final String TAG = TvContractUtils.class.getName();

    public static final long INVALID_CHANNEL_ID = -1;

    private TvContractUtils() {
        throw new IllegalAccessError("Utility class");
    }

    public static String getInputId() {
        ComponentName componentName = new ComponentName(
                "ie.macinnes.tvheadend",
                ".tvinput.TvInputService");

        return TvContract.buildInputId(componentName);
    }

    public static long getChannelId(Context context, int channelId) {
        ContentResolver resolver = context.getContentResolver();

        Uri channelsUri = TvContract.buildChannelsUriForInput(TvContractUtils.getInputId());

        String[] projection = {TvContract.Channels._ID, TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID};

        try (Cursor cursor = resolver.query(channelsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                if (cursor.getInt(1) == channelId) {
                    return cursor.getLong(0);
                }
            }
        }

        return INVALID_CHANNEL_ID;
    }

    public static String getChannelName(Context context, int channelId) {
        ContentResolver resolver = context.getContentResolver();

        Uri channelsUri = TvContract.buildChannelsUriForInput(TvContractUtils.getInputId());

        String[] projection = {TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID, TvContract.Channels.COLUMN_DISPLAY_NAME};

        try (Cursor cursor = resolver.query(channelsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                if (cursor.getInt(0) == channelId) {
                    return cursor.getString(1);
                }
            }
        }

        return null;
    }

    public static Uri getChannelUri(Context context, int channelId) {
        long androidChannelId = getChannelId(context, channelId);

        if (androidChannelId != INVALID_CHANNEL_ID) {
            return TvContract.buildChannelUri(androidChannelId);
        }

        return null;
    }

    public static Integer getTvhChannelIdFromChannelUri(Context context, Uri channelUri) {
        ContentResolver resolver = context.getContentResolver();

        String[] projection = {Channels._ID, Channels.COLUMN_ORIGINAL_NETWORK_ID};

        // TODO: Handle when more than 1, or 0 results come back
        try (Cursor cursor = resolver.query(channelUri, projection, null,null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                return cursor.getInt(1);
            }
        }

        return null;
    }

    public static void removeChannels(Context context) {
        Uri channelsUri = TvContract.buildChannelsUriForInput(getInputId());

        ContentResolver resolver = context.getContentResolver();

        String[] projection = {Channels._ID, Channels.COLUMN_ORIGINAL_NETWORK_ID};

        try (Cursor cursor = resolver.query(channelsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                long rowId = cursor.getLong(0);
                Log.d(TAG, "Deleting channel: " + rowId);
                resolver.delete(TvContract.buildChannelUri(rowId), null, null);
            }
        }
    }

    public static SparseArray<Uri> buildChannelUriMap(Context context) {
        ContentResolver resolver = context.getContentResolver();

        // Create a map from original network ID to channel row ID for existing channels.
        SparseArray<Uri> channelMap = new SparseArray<>();
        Uri channelsUri = TvContract.buildChannelsUriForInput(TvContractUtils.getInputId());
        String[] projection = {TvContract.Channels._ID, TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID};

        try (Cursor cursor = resolver.query(channelsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                long rowId = cursor.getLong(0);
                int originalNetworkId = cursor.getInt(1);
                channelMap.put(originalNetworkId, TvContract.buildChannelUri(rowId));
            }
        }

        return channelMap;
    }

    public static Uri getProgramUri(Context context, int channelId, int eventId) {
        // TODO: Cache results...
        ContentResolver resolver = context.getContentResolver();

        long androidChannelId = getChannelId(context, channelId);

        if (androidChannelId == INVALID_CHANNEL_ID) {
            Log.w(TAG, "Failed to fetch programUri, unknown channel");
            return null;
        }

        Uri programsUri = TvContract.buildProgramsUriForChannel(androidChannelId);

        String[] projection = {TvContract.Programs._ID, TvContract.Programs.COLUMN_INTERNAL_PROVIDER_DATA};

        String strEventId = String.valueOf(eventId);

        try (Cursor cursor = resolver.query(programsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                if (strEventId.equals(cursor.getString(1))) {
                    return TvContract.buildProgramUri(cursor.getLong(0));
                }
            }
        }

        return null;
    }

    public static SparseArray<Uri> buildProgramUriMap(Context context) {
        ContentResolver resolver = context.getContentResolver();

        // Create a map from event id to program row ID for existing programs.
        SparseArray<Uri> programMap = new SparseArray<>();

        Uri channelsUri = TvContract.buildChannelsUriForInput(TvContractUtils.getInputId());

        String[] channelsProjection = {TvContract.Channels._ID};
        try (Cursor cursor = resolver.query(channelsUri, channelsProjection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                SparseArray<Uri> channelPrgramMap = buildProgramUriMap(context, TvContract.buildChannelUri(cursor.getLong(0)));
                for (int i = 0; i < channelPrgramMap.size(); i++) {
                    int key = channelPrgramMap.keyAt(i);
                    Uri value = channelPrgramMap.valueAt(i);
                    programMap.put(key, value);
                }
            }
        }

        return programMap;
    }

    public static SparseArray<Uri> buildProgramUriMap(Context context, Uri channelUri) {
        ContentResolver resolver = context.getContentResolver();

        // Create a map from event id to program row ID for existing programs.
        SparseArray<Uri> programMap = new SparseArray<>();

        Uri programsUri = TvContract.buildProgramsUriForChannel(channelUri);
        String[] projection = {TvContract.Programs._ID, TvContract.Programs.COLUMN_INTERNAL_PROVIDER_DATA};

        try (Cursor cursor = resolver.query(programsUri, projection, null, null, null)) {
            while (cursor != null && cursor.moveToNext()) {
                long rowId = cursor.getLong(0);
                int tvhEventId = Integer.valueOf(cursor.getString(1));
                programMap.put(tvhEventId, TvContract.buildChannelUri(rowId));
            }
        }

        return programMap;
    }
}


text:
import os
from application import app
from application import db
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask.ext.migrate import MigrateCommand

manager = Manager(app)
migrate = Migrate(app=app, db=db)

manager.add_command('db', MigrateCommand)

if __name__ == "__main__":
    manager.run()


text:
package br.fameg.edu.services;

import br.fameg.edu.domain.model.Aluno;
import br.fameg.edu.domain.model.Matricula;
import br.fameg.edu.domain.repositories.MatriculaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlunoService {

    private MatriculaRepository matriculaRepository;

    public AlunoService(MatriculaRepository repo) {
        this.matriculaRepository = repo;
    }

    public Matricula matricular(Matricula matricula) {
        if(!validarSituacaoDoAluno(matricula.getAluno()))
            throw new RuntimeException("O Nº de matrícula do aluno é inválido.");
        return matriculaRepository.save(matricula);
    }
    private boolean validarSituacaoDoAluno(Aluno aluno) {
        return aluno.getNumeroDeMatricula() > 0;
    }
}


text:
(function () {
    'use strict';

    angular.module('ClientApp')
        .directive('clientBuzzerController', clientBuzzerController);

    /**
     * This is the directive for the buzzer controller.
     * Use:
     * <client-buzzer-controller></client-buzzer-controller>
     * to embed to controller in the html file.
     */

    function clientBuzzerController(){
        return {
            restrict: 'E',
            scope: {},
            templateUrl: 'app/client/clientBuzzer/client-buzzer.html',
            controller: 'initBuzzerController',
            controllerAs: 'buzzerCtrl'
        };
    }

})();


text:
namespace ui {

StubKeyboardLayoutEngine::StubKeyboardLayoutEngine() {
}

StubKeyboardLayoutEngine::~StubKeyboardLayoutEngine() {
}

bool StubKeyboardLayoutEngine::CanSetCurrentLayout() const {
  return false;
}

bool StubKeyboardLayoutEngine::SetCurrentLayoutByName(
    const std::string& layout_name) {
  return false;
}

bool StubKeyboardLayoutEngine::UsesISOLevel5Shift() const {
  return false;
}

bool StubKeyboardLayoutEngine::UsesAltGr() const {
  return true;
}

bool StubKeyboardLayoutEngine::Lookup(DomCode dom_code,
                                      int flags,
                                      DomKey* out_dom_key,
                                      KeyboardCode* out_key_code,
                                      uint32* platform_keycode) const {
  return DomCodeToUsLayoutDomKey(dom_code, flags, out_dom_key, out_key_code);
}

}  // namespace ui


text:
/*******************************************************************************
* Copyright 2004, The Board of Regents of the University of Wisconsin System.
* All rights reserved.
*
* A non-exclusive worldwide royalty-free license is granted for this Software.
* Permission to use, copy, modify, and distribute this Software and its
* documentation, with or without modification, for any purpose is granted
* provided that such redistribution and use in source and binary forms, with or
* without modification meets the following conditions:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgement:
*
* "This product includes software developed by The Board of Regents of
* the University of Wisconsin System.�
*
*THIS SOFTWARE IS PROVIDED BY THE BOARD OF REGENTS OF THE UNIVERSITY OF
*WISCONSIN SYSTEM "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
*BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
*PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE BOARD OF REGENTS OF
*THE UNIVERSITY OF WISCONSIN SYSTEM BE LIABLE FOR ANY DIRECT, INDIRECT,
*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
*PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
*LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
*OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
*ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
package edu.wisc.my.apilayer.portlet;

/**
 * The identifier is passed by a supporting framework into a portlet
 * as a request attribute so the portlet can provide scope level information
 * to other applications.
 *
 * The actual value of any of these identifiers should be meaningless to the
 * calling application other than for testing equality against each other.
 *
 * @author Eric Dalquist edalquist@unicon.net
 * @version $Revision: 1.1.2.1 $
 * @since 1.0
 */
public interface IScopeIdentifier extends Constants {
    /**
     * Gets the system level scope identifier.
     *
     * @return The system level scope identifier.
     */
    public String getSystemIdentifier();

    /**
     * Gets the application level scope identifier.
     *
     * @return The application level scope identifier.
     */
    public String getApplicationIdentifier();

    /**
     * Gets the published level scope identifier.
     *
     * @return The published level scope identifier.
     */
    public String getPublishedIdentifier();

    /**
     * Gets the instance level scope identifier.
     *
     * @return The instance level scope identifier.
     */
    public String getInstanceIdentifier();

    /**
     * Gets the user level scope identifier.
     *
     * @return The user level scope identifier.
     */
    public String getUserIdentifier();
}


text:
<?php

class Mage_Shipping_Exception extends Zend_Exception
{

}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;

namespace System
{
    public partial class String
    {
        private const int TrimHead = 0;
        private const int TrimTail = 1;
        private const int TrimBoth = 2;

        unsafe private static void FillStringChecked(String dest, int destPos, String src)
        {
            if (src.Length > dest.Length - destPos)
            {
                throw new IndexOutOfRangeException();
            }

            fixed (char* pDest = &dest._firstChar)
                fixed (char* pSrc = &src._firstChar)
            {
                wstrcpy(pDest + destPos, pSrc, src.Length);
            }
        }

        public static String Concat(Object arg0)
        {
            if (arg0 == null)
            {
                return String.Empty;
            }
            return arg0.ToString();
        }

        public static String Concat(Object arg0, Object arg1)
        {
            if (arg0 == null)
            {
                arg0 = String.Empty;
            }

            if (arg1 == null)
            {
                arg1 = String.Empty;
            }
            return Concat(arg0.ToString(), arg1.ToString());
        }

        public static String Concat(Object arg0, Object arg1, Object arg2)
        {
            if (arg0 == null)
            {
                arg0 = String.Empty;
            }

            if (arg1 == null)
            {
                arg1 = String.Empty;
            }

            if (arg2 == null)
            {
                arg2 = String.Empty;
            }

            return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString());
        }

        public static string Concat(params object[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (args.Length <= 1)
            {
                return args.Length == 0 ?
                    string.Empty :
                    args[0]?.ToString() ?? string.Empty;
            }

            // We need to get an intermediary string array
            // to fill with each of the args' ToString(),
            // and then just concat that in one operation.

            // This way we avoid any intermediary string representations,
            // or buffer resizing if we use StringBuilder (although the
            // latter case is partially alleviated due to StringBuilder's
            // linked-list style implementation)

            var strings = new string[args.Length];

            int totalLength = 0;

            for (int i = 0; i < args.Length; i++)
            {
                object value = args[i];

                string toString = value?.ToString() ?? string.Empty; // We need to handle both the cases when value or value.ToString() is null
                strings[i] = toString;

                totalLength += toString.Length;

                if (totalLength < 0) // Check for a positive overflow
                {
                    throw new OutOfMemoryException();
                }
            }

            // If all of the ToStrings are null/empty, just return string.Empty
            if (totalLength == 0)
            {
                return string.Empty;
            }

            string result = FastAllocateString(totalLength);
            int position = 0; // How many characters we've copied so far

            for (int i = 0; i < strings.Length; i++)
            {
                string s = strings[i];

                Contract.Assert(s != null);
                Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");

                FillStringChecked(result, position, s);
                position += s.Length;
            }

            return result;
        }

        public static string Concat<T>(IEnumerable<T> values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            using (IEnumerator<T> en = values.GetEnumerator())
            {
                if (!en.MoveNext())
                    return string.Empty;

                // We called MoveNext once, so this will be the first item
                T currentValue = en.Current;

                // Call ToString before calling MoveNext again, since
                // we want to stay consistent with the below loop
                // Everything should be called in the order
                // MoveNext-Current-ToString, unless further optimizations
                // can be made, to avoid breaking changes
                string firstString = currentValue?.ToString();

                // If there's only 1 item, simply call ToString on that
                if (!en.MoveNext())
                {
                    // We have to handle the case of either currentValue
                    // or its ToString being null
                    return firstString ?? string.Empty;
                }

                StringBuilder result = StringBuilderCache.Acquire();

                result.Append(firstString);

                do
                {
                    currentValue = en.Current;

                    if (currentValue != null)
                    {
                        result.Append(currentValue.ToString());
                    }
                }
                while (en.MoveNext());

                return StringBuilderCache.GetStringAndRelease(result);
            }
        }

        public static string Concat(IEnumerable<string> values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            using (IEnumerator<string> en = values.GetEnumerator())
            {
                if (!en.MoveNext())
                    return string.Empty;

                string firstValue = en.Current;

                if (!en.MoveNext())
                {
                    return firstValue ?? string.Empty;
                }

                StringBuilder result = StringBuilderCache.Acquire();
                result.Append(firstValue);

                do
                {
                    result.Append(en.Current);
                }
                while (en.MoveNext());

                return StringBuilderCache.GetStringAndRelease(result);
            }
        }

        public static String Concat(String str0, String str1)
        {
            if (IsNullOrEmpty(str0))
            {
                if (IsNullOrEmpty(str1))
                {
                    return String.Empty;
                }
                return str1;
            }

            if (IsNullOrEmpty(str1))
            {
                return str0;
            }

            int str0Length = str0.Length;

            String result = FastAllocateString(str0Length + str1.Length);

            FillStringChecked(result, 0, str0);
            FillStringChecked(result, str0Length, str1);

            return result;
        }

        public static String Concat(String str0, String str1, String str2)
        {
            if (IsNullOrEmpty(str0))
            {
                return Concat(str1, str2);
            }

            if (IsNullOrEmpty(str1))
            {
                return Concat(str0, str2);
            }

            if (IsNullOrEmpty(str2))
            {
                return Concat(str0, str1);
            }

            int totalLength = str0.Length + str1.Length + str2.Length;

            String result = FastAllocateString(totalLength);
            FillStringChecked(result, 0, str0);
            FillStringChecked(result, str0.Length, str1);
            FillStringChecked(result, str0.Length + str1.Length, str2);

            return result;
        }

        public static String Concat(String str0, String str1, String str2, String str3)
        {
            if (IsNullOrEmpty(str0))
            {
                return Concat(str1, str2, str3);
            }

            if (IsNullOrEmpty(str1))
            {
                return Concat(str0, str2, str3);
            }

            if (IsNullOrEmpty(str2))
            {
                return Concat(str0, str1, str3);
            }

            if (IsNullOrEmpty(str3))
            {
                return Concat(str0, str1, str2);
            }

            int totalLength = str0.Length + str1.Length + str2.Length + str3.Length;

            String result = FastAllocateString(totalLength);
            FillStringChecked(result, 0, str0);
            FillStringChecked(result, str0.Length, str1);
            FillStringChecked(result, str0.Length + str1.Length, str2);
            FillStringChecked(result, str0.Length + str1.Length + str2.Length, str3);

            return result;
        }

        public static String Concat(params String[] values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            if (values.Length <= 1)
            {
                return values.Length == 0 ?
                    string.Empty :
                    values[0] ?? string.Empty;
            }

            // It's possible that the input values array could be changed concurrently on another
            // thread, such that we can't trust that each read of values[i] will be equivalent.
            // Worst case, we can make a defensive copy of the array and use that, but we first
            // optimistically try the allocation and copies assuming that the array isn't changing,
            // which represents the 99.999% case, in particular since string.Concat is used for
            // string concatenation by the languages, with the input array being a params array.

            // Sum the lengths of all input strings
            long totalLengthLong = 0;
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i];
                if (value != null)
                {
                    totalLengthLong += value.Length;
                }
            }

            // If it's too long, fail, or if it's empty, return an empty string.
            if (totalLengthLong > int.MaxValue)
            {
                throw new OutOfMemoryException();
            }
            int totalLength = (int)totalLengthLong;
            if (totalLength == 0)
            {
                return string.Empty;
            }

            // Allocate a new string and copy each input string into it
            string result = FastAllocateString(totalLength);
            int copiedLength = 0;
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i];
                if (!string.IsNullOrEmpty(value))
                {
                    int valueLen = value.Length;
                    if (valueLen > totalLength - copiedLength)
                    {
                        copiedLength = -1;
                        break;
                    }

                    FillStringChecked(result, copiedLength, value);
                    copiedLength += valueLen;
                }
            }

            // If we copied exactly the right amount, return the new string.  Otherwise,
            // something changed concurrently to mutate the input array: fall back to
            // doing the concatenation again, but this time with a defensive copy. This
            // fall back should be extremely rare.
            return copiedLength == totalLength ? result : Concat((string[])values.Clone());
        }

        public static String Format(String format, params Object[] args)
        {
            if (args == null)
            {
                // To preserve the original exception behavior, throw an exception about format if both
                // args and format are null. The actual null check for format is in FormatHelper.
                throw new ArgumentNullException((format == null) ? "format" : "args");
            }

            return FormatHelper(null, format, new ParamsArray(args));
        }

        public static String Format(String format, Object arg0)
        {
            return FormatHelper(null, format, new ParamsArray(arg0));
        }

        public static String Format(String format, Object arg0, Object arg1)
        {
            return FormatHelper(null, format, new ParamsArray(arg0, arg1));
        }

        public static String Format(String format, Object arg0, Object arg1, Object arg2)
        {
            return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
        }

        public static String Format(IFormatProvider provider, String format, params Object[] args)
        {
            if (args == null)
            {
                // To preserve the original exception behavior, throw an exception about format if both
                // args and format are null. The actual null check for format is in FormatHelper.
                throw new ArgumentNullException((format == null) ? "format" : "args");
            }

            return FormatHelper(provider, format, new ParamsArray(args));
        }

        public static String Format(IFormatProvider provider, String format, Object arg0)
        {
            return FormatHelper(provider, format, new ParamsArray(arg0));
        }

        public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1)
        {
            return FormatHelper(provider, format, new ParamsArray(arg0, arg1));
        }

        public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2)
        {
            return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
        }

        private static String FormatHelper(IFormatProvider provider, String format, ParamsArray args)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            return StringBuilderCache.GetStringAndRelease(
                StringBuilderCache
                    .Acquire(format.Length + args.Length * 8)
                    .AppendFormatHelper(provider, format, args));
        }

        public String Insert(int startIndex, String value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (startIndex < 0 || startIndex > this.Length)
                throw new ArgumentOutOfRangeException("startIndex");

            int oldLength = Length;
            int insertLength = value.Length;

            if (oldLength == 0)
                return value;
            if (insertLength == 0)
                return this;

            int newLength = oldLength + insertLength;
            if (newLength < 0)
                throw new OutOfMemoryException();
            String result = FastAllocateString(newLength);
            unsafe
            {
                fixed (char* srcThis = &_firstChar)
                {
                    fixed (char* srcInsert = &value._firstChar)
                    {
                        fixed (char* dst = &result._firstChar)
                        {
                            wstrcpy(dst, srcThis, startIndex);
                            wstrcpy(dst + startIndex, srcInsert, insertLength);
                            wstrcpy(dst + startIndex + insertLength, srcThis + startIndex, oldLength - startIndex);
                        }
                    }
                }
            }
            return result;
        }

        // Joins an array of strings together as one string with a separator between each original string.
        //
        public static String Join(String separator, params String[] value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            return Join(separator, value, 0, value.Length);
        }

        public static string Join(string separator, params object[] values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            if (values.Length == 0 || values[0] == null)
                return string.Empty;

            string firstString = values[0].ToString();

            if (values.Length == 1)
            {
                return firstString ?? string.Empty;
            }

            StringBuilder result = StringBuilderCache.Acquire();
            result.Append(firstString);

            for (int i = 1; i < values.Length; i++)
            {
                result.Append(separator);
                object value = values[i];
                if (value != null)
                {
                    result.Append(value.ToString());
                }
            }

            return StringBuilderCache.GetStringAndRelease(result);
        }

        public static String Join<T>(String separator, IEnumerable<T> values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            using (IEnumerator<T> en = values.GetEnumerator())
            {
                if (!en.MoveNext())
                    return string.Empty;

                // We called MoveNext once, so this will be the first item
                T currentValue = en.Current;

                // Call ToString before calling MoveNext again, since
                // we want to stay consistent with the below loop
                // Everything should be called in the order
                // MoveNext-Current-ToString, unless further optimizations
                // can be made, to avoid breaking changes
                string firstString = currentValue?.ToString();

                // If there's only 1 item, simply call ToString on that
                if (!en.MoveNext())
                {
                    // We have to handle the case of either currentValue
                    // or its ToString being null
                    return firstString ?? string.Empty;
                }

                StringBuilder result = StringBuilderCache.Acquire();

                result.Append(firstString);

                do
                {
                    currentValue = en.Current;

                    result.Append(separator);
                    if (currentValue != null)
                    {
                        result.Append(currentValue.ToString());
                    }
                }
                while (en.MoveNext());

                return StringBuilderCache.GetStringAndRelease(result);
            }
        }

        public static String Join(String separator, IEnumerable<String> values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            using (IEnumerator<String> en = values.GetEnumerator())
            {
                if (!en.MoveNext())
                    return String.Empty;

                String firstValue = en.Current;

                if (!en.MoveNext())
                {
                    // Only one value available
                    return firstValue ?? String.Empty;
                }

                // Null separator and values are handled by the StringBuilder
                StringBuilder result = StringBuilderCache.Acquire();
                result.Append(firstValue);

                do
                {
                    result.Append(separator);
                    result.Append(en.Current);
                } while (en.MoveNext());
                return StringBuilderCache.GetStringAndRelease(result);
            }
        }

        // Joins an array of strings together as one string with a separator between each original string.
        //
        public unsafe static String Join(String separator, String[] value, int startIndex, int count)
        {
            //Range check the array
            if (value == null)
                throw new ArgumentNullException("value");

            if (startIndex < 0)
                throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount);

            if (startIndex > value.Length - count)
                throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_IndexCountBuffer);

            //Treat null as empty string.
            if (separator == null)
            {
                separator = String.Empty;
            }

            //If count is 0, that skews a whole bunch of the calculations below, so just special case that.
            if (count == 0)
            {
                return String.Empty;
            }

            if (count == 1)
            {
                return value[startIndex] ?? String.Empty;
            }

            int endIndex = startIndex + count - 1;
            StringBuilder result = StringBuilderCache.Acquire();
            // Append the first string first and then append each following string prefixed by the separator.
            result.Append(value[startIndex]);
            for (int stringToJoinIndex = startIndex + 1; stringToJoinIndex <= endIndex; stringToJoinIndex++)
            {
                result.Append(separator);
                result.Append(value[stringToJoinIndex]);
            }

            return StringBuilderCache.GetStringAndRelease(result);
        }

        public String PadLeft(int totalWidth)
        {
            return PadLeft(totalWidth, ' ');
        }

        public String PadLeft(int totalWidth, char paddingChar)
        {
            if (totalWidth < 0)
                throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum);
            int oldLength = Length;
            int count = totalWidth - oldLength;
            if (count <= 0)
                return this;
            String result = FastAllocateString(totalWidth);
            unsafe
            {
                fixed (char* dst = &result._firstChar)
                {
                    for (int i = 0; i < count; i++)
                        dst[i] = paddingChar;
                    fixed (char* src = &_firstChar)
                    {
                        wstrcpy(dst + count, src, oldLength);
                    }
                }
            }
            return result;
        }

        public String PadRight(int totalWidth)
        {
            return PadRight(totalWidth, ' ');
        }

        public String PadRight(int totalWidth, char paddingChar)
        {
            if (totalWidth < 0)
                throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum);
            int oldLength = Length;
            int count = totalWidth - oldLength;
            if (count <= 0)
                return this;
            String result = FastAllocateString(totalWidth);
            unsafe
            {
                fixed (char* dst = &result._firstChar)
                {
                    fixed (char* src = &_firstChar)
                    {
                        wstrcpy(dst, src, oldLength);
                    }
                    for (int i = 0; i < count; i++)
                        dst[oldLength + i] = paddingChar;
                }
            }
            return result;
        }

        public String Remove(int startIndex, int count)
        {
            if (startIndex < 0)
                throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount);
            int oldLength = this.Length;
            if (count > oldLength - startIndex)
                throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_IndexCount);

            if (count == 0)
                return this;
            int newLength = oldLength - count;
            if (newLength == 0)
                return string.Empty;

            String result = FastAllocateString(newLength);
            unsafe
            {
                fixed (char* src = &_firstChar)
                {
                    fixed (char* dst = &result._firstChar)
                    {
                        wstrcpy(dst, src, startIndex);
                        wstrcpy(dst + startIndex, src + startIndex + count, newLength - startIndex);
                    }
                }
            }
            return result;
        }

        // a remove that just takes a startindex.
        public string Remove(int startIndex)
        {
            if (startIndex < 0)
            {
                throw new ArgumentOutOfRangeException("startIndex",
                        SR.ArgumentOutOfRange_StartIndex);
            }

            if (startIndex >= Length)
            {
                throw new ArgumentOutOfRangeException("startIndex",
                        SR.ArgumentOutOfRange_StartIndexLessThanLength);
            }

            return Substring(0, startIndex);
        }

        // Replaces all instances of oldChar with newChar.
        //
        public String Replace(char oldChar, char newChar)
        {
            if (oldChar == newChar)
                return this;

            unsafe
            {
                int remainingLength = Length;

                fixed (char* pChars = &_firstChar)
                {
                    char* pSrc = pChars;

                    while (remainingLength > 0)
                    {
                        if (*pSrc == oldChar)
                        {
                            break;
                        }

                        remainingLength--;
                        pSrc++;
                    }
                }

                if (remainingLength == 0)
                    return this;

                String result = FastAllocateString(Length);

                fixed (char* pChars = &_firstChar)
                {
                    fixed (char* pResult = &result._firstChar)
                    {
                        int copyLength = Length - remainingLength;

                        //Copy the characters already proven not to match.
                        if (copyLength > 0)
                        {
                            wstrcpy(pResult, pChars, copyLength);
                        }

                        //Copy the remaining characters, doing the replacement as we go.
                        char* pSrc = pChars + copyLength;
                        char* pDst = pResult + copyLength;

                        do
                        {
                            char currentChar = *pSrc;
                            if (currentChar == oldChar)
                                currentChar = newChar;
                            *pDst = currentChar;

                            remainingLength--;
                            pSrc++;
                            pDst++;
                        } while (remainingLength > 0);
                    }
                }

                return result;
            }
        }

        public String Replace(String oldValue, String newValue)
        {
            unsafe
            {
                if (oldValue == null)
                    throw new ArgumentNullException("oldValue");
                if (oldValue.Length == 0)
                    throw new ArgumentException(SR.Format(SR.Argument_StringZeroLength, "oldValue"));
                // Api behavior: if newValue is null, instances of oldValue are to be removed.
                if (newValue == null)
                    newValue = String.Empty;

                int numOccurrences = 0;
                int[] replacementIndices = new int[this.Length];
                fixed (char* pThis = &_firstChar)
                {
                    fixed (char* pOldValue = &oldValue._firstChar)
                    {
                        int idx = 0;
                        int lastPossibleMatchIdx = this.Length - oldValue.Length;
                        while (idx <= lastPossibleMatchIdx)
                        {
                            int probeIdx = idx;
                            int oldValueIdx = 0;
                            bool foundMismatch = false;
                            while (oldValueIdx < oldValue.Length)
                            {
                                Debug.Assert(probeIdx >= 0 && probeIdx < this.Length);
                                Debug.Assert(oldValueIdx >= 0 && oldValueIdx < oldValue.Length);
                                if (pThis[probeIdx] != pOldValue[oldValueIdx])
                                {
                                    foundMismatch = true;
                                    break;
                                }
                                probeIdx++;
                                oldValueIdx++;
                            }
                            if (!foundMismatch)
                            {
                                // Found a match for the string. Record the location of the match and skip over the "oldValue."
                                replacementIndices[numOccurrences++] = idx;
                                Debug.Assert(probeIdx == idx + oldValue.Length);
                                idx = probeIdx;
                            }
                            else
                            {
                                idx++;
                            }
                        }
                    }
                }

                if (numOccurrences == 0)
                    return this;

                int dstLength = checked(this.Length + (newValue.Length - oldValue.Length) * numOccurrences);
                String dst = FastAllocateString(dstLength);
                fixed (char* pThis = &_firstChar)
                {
                    fixed (char* pDst = &dst._firstChar)
                    {
                        fixed (char* pNewValue = &newValue._firstChar)
                        {
                            int dstIdx = 0;
                            int thisIdx = 0;

                            for (int r = 0; r < numOccurrences; r++)
                            {
                                int replacementIdx = replacementIndices[r];

                                // Copy over the non-matching portion of the original that precedes this occurrence of oldValue.
                                int count = replacementIdx - thisIdx;
                                Debug.Assert(count >= 0);
                                Debug.Assert(thisIdx >= 0 && thisIdx <= this.Length - count);
                                Debug.Assert(dstIdx >= 0 && dstIdx <= dst.Length - count);
                                if (count != 0)
                                {
                                    wstrcpy(&(pDst[dstIdx]), &(pThis[thisIdx]), count);
                                    dstIdx += count;
                                }
                                thisIdx = replacementIdx + oldValue.Length;

                                // Copy over newValue to replace the oldValue.
                                Debug.Assert(thisIdx >= 0 && thisIdx <= this.Length);
                                Debug.Assert(dstIdx >= 0 && dstIdx <= dst.Length - newValue.Length);
                                wstrcpy(&(pDst[dstIdx]), pNewValue, newValue.Length);
                                dstIdx += newValue.Length;
                            }

                            // Copy over the final non-matching portion at the end of the string.
                            int tailLength = this.Length - thisIdx;
                            Debug.Assert(tailLength >= 0);
                            Debug.Assert(thisIdx == this.Length - tailLength);
                            Debug.Assert(dstIdx == dst.Length - tailLength);
                            wstrcpy(&(pDst[dstIdx]), &(pThis[thisIdx]), tailLength);
                        }
                    }
                }

                return dst;
            }
        }

        // Creates an array of strings by splitting this string at each
        // occurrence of a separator.  The separator is searched for, and if found,
        // the substring preceding the occurrence is stored as the first element in
        // the array of strings.  We then continue in this manner by searching
        // the substring that follows the occurrence.  On the other hand, if the separator
        // is not found, the array of strings will contain this instance as its only element.
        // If the separator is null
        // whitespace (i.e., Character.IsWhitespace) is used as the separator.
        //
        public String[] Split(params char[] separator)
        {
            return Split(separator, Int32.MaxValue, StringSplitOptions.None);
        }

        // Creates an array of strings by splitting this string at each
        // occurrence of a separator.  The separator is searched for, and if found,
        // the substring preceding the occurrence is stored as the first element in
        // the array of strings.  We then continue in this manner by searching
        // the substring that follows the occurrence.  On the other hand, if the separator
        // is not found, the array of strings will contain this instance as its only element.
        // If the separator is the empty string (i.e., String.Empty), then
        // whitespace (i.e., Character.IsWhitespace) is used as the separator.
        // If there are more than count different strings, the last n-(count-1)
        // elements are concatenated and added as the last String.
        //
        public string[] Split(char[] separator, int count)
        {
            return Split(separator, count, StringSplitOptions.None);
        }

        public String[] Split(char[] separator, StringSplitOptions options)
        {
            return Split(separator, Int32.MaxValue, options);
        }

        public String[] Split(char[] separator, int count, StringSplitOptions options)
        {
            if (count < 0)
                throw new ArgumentOutOfRangeException("count",
                    SR.ArgumentOutOfRange_NegativeCount);

            if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, options));

            bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);

            if ((count == 0) || (omitEmptyEntries && this.Length == 0))
            {
                return Array.Empty<String>();
            }

            if (count == 1)
            {
                return new String[] { this };
            }

            int[] sepList = new int[Length];
            int numReplaces = MakeSeparatorList(separator, sepList);

            // Handle the special case of no replaces.
            if (0 == numReplaces)
            {
                return new String[] { this };
            }

            if (omitEmptyEntries)
            {
                return SplitOmitEmptyEntries(sepList, null, numReplaces, count);
            }
            else
            {
                return SplitKeepEmptyEntries(sepList, null, numReplaces, count);
            }
        }

        public String[] Split(String[] separator, StringSplitOptions options)
        {
            return Split(separator, Int32.MaxValue, options);
        }

        public String[] Split(String[] separator, Int32 count, StringSplitOptions options)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count",
                    SR.ArgumentOutOfRange_NegativeCount);
            }

            if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
            {
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options));
            }

            bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);

            if (separator == null || separator.Length == 0)
            {
                return Split((char[])null, count, options);
            }

            if ((count == 0) || (omitEmptyEntries && this.Length == 0))
            {
                return Array.Empty<String>();
            }

            if (count == 1)
            {
                return new String[] { this };
            }

            int[] sepList = new int[Length];
            int[] lengthList = new int[Length];
            int numReplaces = MakeSeparatorList(separator, sepList, lengthList);

            //Handle the special case of no replaces.
            if (0 == numReplaces)
            {
                return new String[] { this };
            }

            if (omitEmptyEntries)
            {
                return SplitOmitEmptyEntries(sepList, lengthList, numReplaces, count);
            }
            else
            {
                return SplitKeepEmptyEntries(sepList, lengthList, numReplaces, count);
            }
        }

        // Note a special case in this function:
        //     If there is no separator in the string, a string array which only contains
        //     the original string will be returned regardless of the count.
        //

        private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count)
        {
            int currIndex = 0;
            int arrIndex = 0;

            count--;
            int numActualReplaces = (numReplaces < count) ? numReplaces : count;

            //Allocate space for the new array.
            //+1 for the string from the end of the last replace to the end of the String.
            String[] splitStrings = new String[numActualReplaces + 1];

            for (int i = 0; i < numActualReplaces && currIndex < Length; i++)
            {
                splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
                currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
            }

            //Handle the last string at the end of the array if there is one.
            if (currIndex < Length && numActualReplaces >= 0)
            {
                splitStrings[arrIndex] = Substring(currIndex);
            }
            else if (arrIndex == numActualReplaces)
            {
                //We had a separator character at the end of a string.  Rather than just allowing
                //a null character, we'll replace the last element in the array with an empty string.
                splitStrings[arrIndex] = String.Empty;
            }

            return splitStrings;
        }

        // This function will not keep the Empty String
        private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count)
        {
            // Allocate array to hold items. This array may not be
            // filled completely in this function, we will create a
            // new array and copy string references to that new array.

            int maxItems = (numReplaces < count) ? (numReplaces + 1) : count;
            String[] splitStrings = new String[maxItems];

            int currIndex = 0;
            int arrIndex = 0;

            for (int i = 0; i < numReplaces && currIndex < Length; i++)
            {
                if (sepList[i] - currIndex > 0)
                {
                    splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
                }
                currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
                if (arrIndex == count - 1)
                {
                    // If all the remaining entries at the end are empty, skip them
                    while (i < numReplaces - 1 && currIndex == sepList[++i])
                    {
                        currIndex += ((lengthList == null) ? 1 : lengthList[i]);
                    }
                    break;
                }
            }

            //Handle the last string at the end of the array if there is one.
            if (currIndex < Length)
            {
                splitStrings[arrIndex++] = Substring(currIndex);
            }

            String[] stringArray = splitStrings;
            if (arrIndex != maxItems)
            {
                stringArray = new String[arrIndex];
                for (int j = 0; j < arrIndex; j++)
                {
                    stringArray[j] = splitStrings[j];
                }
            }
            return stringArray;
        }

        //--------------------------------------------------------------------
        // This function returns the number of the places within this instance where
        // characters in Separator occur.
        // Args: separator  -- A string containing all of the split characters.
        //       sepList    -- an array of ints for split char indicies.
        //--------------------------------------------------------------------
        private unsafe int MakeSeparatorList(char[] separator, int[] sepList)
        {
            int foundCount = 0;

            if (separator == null || separator.Length == 0)
            {
                fixed (char* pwzChars = &_firstChar)
                {
                    //If they passed null or an empty string, look for whitespace.
                    for (int i = 0; i < Length && foundCount < sepList.Length; i++)
                    {
                        if (Char.IsWhiteSpace(pwzChars[i]))
                        {
                            sepList[foundCount++] = i;
                        }
                    }
                }
            }
            else
            {
                int sepListCount = sepList.Length;
                int sepCount = separator.Length;
                //If they passed in a string of chars, actually look for those chars.
                fixed (char* pwzChars = &_firstChar, pSepChars = separator)
                {
                    for (int i = 0; i < Length && foundCount < sepListCount; i++)
                    {
                        char* pSep = pSepChars;
                        for (int j = 0; j < sepCount; j++, pSep++)
                        {
                            if (pwzChars[i] == *pSep)
                            {
                                sepList[foundCount++] = i;
                                break;
                            }
                        }
                    }
                }
            }
            return foundCount;
        }

        //--------------------------------------------------------------------
        // This function returns the number of the places within this instance where
        // instances of separator strings occur.
        // Args: separators -- An array containing all of the split strings.
        //       sepList    -- an array of ints for split string indicies.
        //       lengthList -- an array of ints for split string lengths.
        //--------------------------------------------------------------------
        private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList)
        {
            int foundCount = 0;
            int sepListCount = sepList.Length;
            int sepCount = separators.Length;

            fixed (char* pwzChars = &_firstChar)
            {
                for (int i = 0; i < Length && foundCount < sepListCount; i++)
                {
                    for (int j = 0; j < separators.Length; j++)
                    {
                        String separator = separators[j];
                        if (String.IsNullOrEmpty(separator))
                        {
                            continue;
                        }
                        Int32 currentSepLength = separator.Length;
                        if (pwzChars[i] == separator[0] && currentSepLength <= Length - i)
                        {
                            if (currentSepLength == 1
                                || String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0)
                            {
                                sepList[foundCount] = i;
                                lengthList[foundCount] = currentSepLength;
                                foundCount++;
                                i += currentSepLength - 1;
                                break;
                            }
                        }
                    }
                }
            }
            return foundCount;
        }

        // Returns a substring of this string.
        //
        public String Substring(int startIndex)
        {
            return this.Substring(startIndex, Length - startIndex);
        }

        // Returns a substring of this string.
        //
        public String Substring(int startIndex, int length)
        {
            //Bounds Checking.
            if (startIndex < 0)
            {
                throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
            }

            if (startIndex > Length)
            {
                throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndexLargerThanLength);
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength);
            }

            if (startIndex > Length - length)
            {
                throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_IndexLength);
            }

            if (length == 0)
            {
                return String.Empty;
            }

            if (startIndex == 0 && length == this.Length)
            {
                return this;
            }

            return InternalSubString(startIndex, length);
        }

        private unsafe string InternalSubString(int startIndex, int length)
        {
            String result = FastAllocateString(length);

            fixed (char* dest = &result._firstChar)
                fixed (char* src = &_firstChar)
            {
                wstrcpy(dest, src + startIndex, length);
            }

            return result;
        }

        // Creates a copy of this string in lower case.  The culture is set by culture.
        public String ToLower()
        {
            return FormatProvider.ToLower(this);
        }

        // Creates a copy of this string in lower case based on invariant culture.
        public String ToLowerInvariant()
        {
            return FormatProvider.ToLowerInvariant(this);
        }

        public String ToUpper()
        {
            return FormatProvider.ToUpper(this);
        }

        //Creates a copy of this string in upper case based on invariant culture.
        public String ToUpperInvariant()
        {
            return FormatProvider.ToUpperInvariant(this);
        }

        // Removes a set of characters from the end of this string.

        public String Trim(params char[] trimChars)
        {
            if (null == trimChars || trimChars.Length == 0)
            {
                return TrimHelper(TrimBoth);
            }
            return TrimHelper(trimChars, TrimBoth);
        }

        // Removes a set of characters from the beginning of this string.
        public String TrimStart(params char[] trimChars)
        {
            if (null == trimChars || trimChars.Length == 0)
            {
                return TrimHelper(TrimHead);
            }
            return TrimHelper(trimChars, TrimHead);
        }

        // Removes a set of characters from the end of this string.
        public String TrimEnd(params char[] trimChars)
        {
            if (null == trimChars || trimChars.Length == 0)
            {
                return TrimHelper(TrimTail);
            }
            return TrimHelper(trimChars, TrimTail);
        }

        // Trims the whitespace from both ends of the string.  Whitespace is defined by
        // Char.IsWhiteSpace.
        //
        public String Trim()
        {
            return TrimHelper(TrimBoth);
        }

        private String TrimHelper(int trimType)
        {
            //end will point to the first non-trimmed character on the right
            //start will point to the first non-trimmed character on the Left
            int end = this.Length - 1;
            int start = 0;

            //Trim specified characters.
            if (trimType != TrimTail)
            {
                for (start = 0; start < this.Length; start++)
                {
                    if (!Char.IsWhiteSpace(this[start])) break;
                }
            }

            if (trimType != TrimHead)
            {
                for (end = Length - 1; end >= start; end--)
                {
                    if (!Char.IsWhiteSpace(this[end])) break;
                }
            }

            return CreateTrimmedString(start, end);
        }

        private String TrimHelper(char[] trimChars, int trimType)
        {
            //end will point to the first non-trimmed character on the right
            //start will point to the first non-trimmed character on the Left
            int end = this.Length - 1;
            int start = 0;

            //Trim specified characters.
            if (trimType != TrimTail)
            {
                for (start = 0; start < this.Length; start++)
                {
                    int i = 0;
                    char ch = this[start];
                    for (i = 0; i < trimChars.Length; i++)
                    {
                        if (trimChars[i] == ch) break;
                    }
                    if (i == trimChars.Length)
                    { // the character is not white space
                        break;
                    }
                }
            }

            if (trimType != TrimHead)
            {
                for (end = Length - 1; end >= start; end--)
                {
                    int i = 0;
                    char ch = this[end];
                    for (i = 0; i < trimChars.Length; i++)
                    {
                        if (trimChars[i] == ch) break;
                    }
                    if (i == trimChars.Length)
                    { // the character is not white space
                        break;
                    }
                }
            }

            return CreateTrimmedString(start, end);
        }

        private String CreateTrimmedString(int start, int end)
        {
            int len = end - start + 1;
            if (len == this.Length)
            {
                // Don't allocate a new string as the trimmed string has not changed.
                return this;
            }
            else
            {
                if (len == 0)
                {
                    return String.Empty;
                }
                return InternalSubString(start, len);
            }
        }
    }
}