text:
import {EventEmitter} from 'events';
import * as net from 'net';
import * as ip from 'ip';
import {SmartBuffer} from 'smart-buffer';
import {
  DEFAULT_TIMEOUT,
  SocksCommand,
  Socks4Response,
  Socks5Auth,
  Socks5HostType,
  Socks5Response,
  SocksClientOptions,
  SocksClientChainOptions,
  SocksClientState,
  SocksRemoteHost,
  SocksProxy,
  SocksClientBoundEvent,
  SocksClientEstablishedEvent,
  SocksUDPFrameDetails,
  ERRORS,
  SOCKS_INCOMING_PACKET_SIZES,
  SOCKS5_NO_ACCEPTABLE_AUTH,
} from '../common/constants';
import {
  validateSocksClientOptions,
  validateSocksClientChainOptions,
} from '../common/helpers';
import {ReceiveBuffer} from '../common/receivebuffer';
import {SocksClientError, shuffleArray} from '../common/util';
import {Duplex} from 'stream';

// Exposes SocksClient event types
declare interface SocksClient {
  on(event: 'error', listener: (err: SocksClientError) => void): this;
  on(event: 'bound', listener: (info: SocksClientBoundEvent) => void): this;
  on(
    event: 'established',
    listener: (info: SocksClientEstablishedEvent) => void,
  ): this;

  once(event: string, listener: (...args: unknown[]) => void): this;
  once(event: 'error', listener: (err: SocksClientError) => void): this;
  once(event: 'bound', listener: (info: SocksClientBoundEvent) => void): this;
  once(
    event: 'established',
    listener: (info: SocksClientEstablishedEvent) => void,
  ): this;

  emit(event: string | symbol, ...args: unknown[]): boolean;
  emit(event: 'error', err: SocksClientError): boolean;
  emit(event: 'bound', info: SocksClientBoundEvent): boolean;
  emit(event: 'established', info: SocksClientEstablishedEvent): boolean;
}

class SocksClient extends EventEmitter implements SocksClient {
  private options: SocksClientOptions;
  private socket: Duplex;
  private state: SocksClientState;
  // This is an internal ReceiveBuffer that holds all received data while we wait for enough data to process.
  private receiveBuffer: ReceiveBuffer;
  // This is the amount of data we need to receive before we can continue processing SOCKS handshake packets.
  private nextRequiredPacketBufferSize: number;
  private socks5ChosenAuthType: number;

  // Internal Socket data handlers
  private onDataReceived: (data: Buffer) => void;
  private onClose: (hadError: boolean) => void;
  private onError: (err: Error) => void;
  private onConnect: () => void;

  constructor(options: SocksClientOptions) {
    super();
    this.options = {
      ...options,
    };

    // Validate SocksClientOptions
    validateSocksClientOptions(options);

    // Default state
    this.setState(SocksClientState.Created);
  }

  /**
   * Creates a new SOCKS connection.
   *
   * Note: Supports callbacks and promises. Only supports the connect command.
   * @param options { SocksClientOptions } Options.
   * @param callback { Function } An optional callback function.
   * @returns { Promise }
   */
  static createConnection(
    options: SocksClientOptions,
    callback?: (
      error: Error | null,
      info?: SocksClientEstablishedEvent,
    ) => void,
  ): Promise<SocksClientEstablishedEvent> {
    return new Promise<SocksClientEstablishedEvent>((resolve, reject) => {
      // Validate SocksClientOptions
      try {
        validateSocksClientOptions(options, ['connect']);
      } catch (err) {
        if (typeof callback === 'function') {
          callback(err);
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          return resolve(err as any); // Resolves pending promise (prevents memory leaks).
        } else {
          return reject(err);
        }
      }

      const client = new SocksClient(options);
      client.connect(options.existing_socket);
      client.once('established', (info: SocksClientEstablishedEvent) => {
        client.removeAllListeners();
        if (typeof callback === 'function') {
          callback(null, info);
          resolve(info); // Resolves pending promise (prevents memory leaks).
        } else {
          resolve(info);
        }
      });

      // Error occurred, failed to establish connection.
      client.once('error', (err: Error) => {
        client.removeAllListeners();
        if (typeof callback === 'function') {
          callback(err);
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          resolve(err as any); // Resolves pending promise (prevents memory leaks).
        } else {
          reject(err);
        }
      });
    });
  }

  /**
   * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
   *
   * Note: Supports callbacks and promises. Only supports the connect method.
   * Note: Implemented via createConnection() factory function.
   * @param options { SocksClientChainOptions } Options
   * @param callback { Function } An optional callback function.
   * @returns { Promise }
   */
  static createConnectionChain(
    options: SocksClientChainOptions,
    callback?: (
      error: Error | null,
      socket?: SocksClientEstablishedEvent,
    ) => void,
  ): Promise<SocksClientEstablishedEvent> {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise<SocksClientEstablishedEvent>(async (resolve, reject) => {
      // Validate SocksClientChainOptions
      try {
        validateSocksClientChainOptions(options);
      } catch (err) {
        if (typeof callback === 'function') {
          callback(err);
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          return resolve(err as any); // Resolves pending promise (prevents memory leaks).
        } else {
          return reject(err);
        }
      }

      // Shuffle proxies
      if (options.randomizeChain) {
        shuffleArray(options.proxies);
      }

      try {
        let sock: net.Socket;

        for (let i = 0; i < options.proxies.length; i++) {
          const nextProxy = options.proxies[i];

          // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy.
          const nextDestination =
            i === options.proxies.length - 1
              ? options.destination
              : {
                  host:
                    options.proxies[i + 1].host ||
                    options.proxies[i + 1].ipaddress,
                  port: options.proxies[i + 1].port,
                };

          // Creates the next connection in the chain.
          const result = await SocksClient.createConnection({
            command: 'connect',
            proxy: nextProxy,
            destination: nextDestination,
            existing_socket: sock,
          });

          // If sock is undefined, assign it here.
          sock = sock || result.socket;
        }

        if (typeof callback === 'function') {
          callback(null, {socket: sock});
          resolve({socket: sock}); // Resolves pending promise (prevents memory leaks).
        } else {
          resolve({socket: sock});
        }
      } catch (err) {
        if (typeof callback === 'function') {
          callback(err);
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          resolve(err as any); // Resolves pending promise (prevents memory leaks).
        } else {
          reject(err);
        }
      }
    });
  }

  /**
   * Creates a SOCKS UDP Frame.
   * @param options
   */
  static createUDPFrame(options: SocksUDPFrameDetails): Buffer {
    const buff = new SmartBuffer();
    buff.writeUInt16BE(0);
    buff.writeUInt8(options.frameNumber || 0);

    // IPv4/IPv6/Hostname
    if (net.isIPv4(options.remoteHost.host)) {
      buff.writeUInt8(Socks5HostType.IPv4);
      buff.writeUInt32BE(ip.toLong(options.remoteHost.host));
    } else if (net.isIPv6(options.remoteHost.host)) {
      buff.writeUInt8(Socks5HostType.IPv6);
      buff.writeBuffer(ip.toBuffer(options.remoteHost.host));
    } else {
      buff.writeUInt8(Socks5HostType.Hostname);
      buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
      buff.writeString(options.remoteHost.host);
    }

    // Port
    buff.writeUInt16BE(options.remoteHost.port);

    // Data
    buff.writeBuffer(options.data);

    return buff.toBuffer();
  }

  /**
   * Parses a SOCKS UDP frame.
   * @param data
   */
  static parseUDPFrame(data: Buffer): SocksUDPFrameDetails {
    const buff = SmartBuffer.fromBuffer(data);
    buff.readOffset = 2;

    const frameNumber = buff.readUInt8();
    const hostType: Socks5HostType = buff.readUInt8();
    let remoteHost;

    if (hostType === Socks5HostType.IPv4) {
      remoteHost = ip.fromLong(buff.readUInt32BE());
    } else if (hostType === Socks5HostType.IPv6) {
      remoteHost = ip.toString(buff.readBuffer(16));
    } else {
      remoteHost = buff.readString(buff.readUInt8());
    }

    const remotePort = buff.readUInt16BE();

    return {
      frameNumber,
      remoteHost: {
        host: remoteHost,
        port: remotePort,
      },
      data: buff.readBuffer(),
    };
  }

  /**
   * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
   */
  private setState(newState: SocksClientState) {
    if (this.state !== SocksClientState.Error) {
      this.state = newState;
    }
  }

  /**
   * Starts the connection establishment to the proxy and destination.
   * @param existingSocket Connected socket to use instead of creating a new one (internal use).
   */
  public connect(existingSocket?: Duplex) {
    this.onDataReceived = (data: Buffer) => this.onDataReceivedHandler(data);
    this.onClose = () => this.onCloseHandler();
    this.onError = (err: Error) => this.onErrorHandler(err);
    this.onConnect = () => this.onConnectHandler();

    // Start timeout timer (defaults to 30 seconds)
    const timer = setTimeout(
      () => this.onEstablishedTimeout(),
      this.options.timeout || DEFAULT_TIMEOUT,
    );

    // check whether unref is available as it differs from browser to NodeJS (#33)
    if (timer.unref && typeof timer.unref === 'function') {
      timer.unref();
    }

    // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket.
    if (existingSocket) {
      this.socket = existingSocket;
    } else {
      this.socket = new net.Socket();
    }

    // Attach Socket error handlers.
    this.socket.once('close', this.onClose);
    this.socket.once('error', this.onError);
    this.socket.once('connect', this.onConnect);
    this.socket.on('data', this.onDataReceived);

    this.setState(SocksClientState.Connecting);
    this.receiveBuffer = new ReceiveBuffer();

    if (existingSocket) {
      this.socket.emit('connect');
    } else {
      (this.socket as net.Socket).connect(this.getSocketOptions());

      if (
        this.options.set_tcp_nodelay !== undefined &&
        this.options.set_tcp_nodelay !== null
      ) {
        (this.socket as net.Socket).setNoDelay(!!this.options.set_tcp_nodelay);
      }
    }

    // Listen for established event so we can re-emit any excess data received during handshakes.
    this.prependOnceListener('established', (info) => {
      setImmediate(() => {
        if (this.receiveBuffer.length > 0) {
          const excessData = this.receiveBuffer.get(this.receiveBuffer.length);

          info.socket.emit('data', excessData);
        }
        info.socket.resume();
      });
    });
  }

  // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
  private getSocketOptions(): net.SocketConnectOpts {
    return {
      ...this.options.socket_options,
      host: this.options.proxy.host || this.options.proxy.ipaddress,
      port: this.options.proxy.port,
    };
  }

  /**
   * Handles internal Socks timeout callback.
   * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
   */
  private onEstablishedTimeout() {
    if (
      this.state !== SocksClientState.Established &&
      this.state !== SocksClientState.BoundWaitingForConnection
    ) {
      this.closeSocket(ERRORS.ProxyConnectionTimedOut);
    }
  }

  /**
   * Handles Socket connect event.
   */
  private onConnectHandler() {
    this.setState(SocksClientState.Connected);

    // Send initial handshake.
    if (this.options.proxy.type === 4) {
      this.sendSocks4InitialHandshake();
    } else {
      this.sendSocks5InitialHandshake();
    }

    this.setState(SocksClientState.SentInitialHandshake);
  }

  /**
   * Handles Socket data event.
   * @param data
   */
  private onDataReceivedHandler(data: Buffer) {
    /*
      All received data is appended to a ReceiveBuffer.
      This makes sure that all the data we need is received before we attempt to process it.
    */
    this.receiveBuffer.append(data);

    // Process data that we have.
    this.processData();
  }

  /**
   * Handles processing of the data we have received.
   */
  private processData() {
    // If we have enough data to process the next step in the SOCKS handshake, proceed.
    while (
      this.state !== SocksClientState.Established &&
      this.state !== SocksClientState.Error &&
      this.receiveBuffer.length >= this.nextRequiredPacketBufferSize
    ) {
      // Sent initial handshake, waiting for response.
      if (this.state === SocksClientState.SentInitialHandshake) {
        if (this.options.proxy.type === 4) {
          // Socks v4 only has one handshake response.
          this.handleSocks4FinalHandshakeResponse();
        } else {
          // Socks v5 has two handshakes, handle initial one here.
          this.handleInitialSocks5HandshakeResponse();
        }
        // Sent auth request for Socks v5, waiting for response.
      } else if (this.state === SocksClientState.SentAuthentication) {
        this.handleInitialSocks5AuthenticationHandshakeResponse();
        // Sent final Socks v5 handshake, waiting for final response.
      } else if (this.state === SocksClientState.SentFinalHandshake) {
        this.handleSocks5FinalHandshakeResponse();
        // Socks BIND established. Waiting for remote connection via proxy.
      } else if (this.state === SocksClientState.BoundWaitingForConnection) {
        if (this.options.proxy.type === 4) {
          this.handleSocks4IncomingConnectionResponse();
        } else {
          this.handleSocks5IncomingConnectionResponse();
        }
      } else {
        this.closeSocket(ERRORS.InternalError);
        break;
      }
    }
  }

  /**
   * Handles Socket close event.
   * @param had_error
   */
  private onCloseHandler() {
    this.closeSocket(ERRORS.SocketClosed);
  }

  /**
   * Handles Socket error event.
   * @param err
   */
  private onErrorHandler(err: Error) {
    this.closeSocket(err.message);
  }

  /**
   * Removes internal event listeners on the underlying Socket.
   */
  private removeInternalSocketHandlers() {
    // Pauses data flow of the socket (this is internally resumed after 'established' is emitted)
    this.socket.pause();
    this.socket.removeListener('data', this.onDataReceived);
    this.socket.removeListener('close', this.onClose);
    this.socket.removeListener('error', this.onError);
    this.socket.removeListener('connect', this.onConnect);
  }

  /**
   * Closes and destroys the underlying Socket. Emits an error event.
   * @param err { String } An error string to include in error event.
   */
  private closeSocket(err: string) {
    // Make sure only one 'error' event is fired for the lifetime of this SocksClient instance.
    if (this.state !== SocksClientState.Error) {
      // Set internal state to Error.
      this.setState(SocksClientState.Error);

      // Destroy Socket
      this.socket.destroy();

      // Remove internal listeners
      this.removeInternalSocketHandlers();

      // Fire 'error' event.
      this.emit('error', new SocksClientError(err, this.options));
    }
  }

  /**
   * Sends initial Socks v4 handshake request.
   */
  private sendSocks4InitialHandshake() {
    const userId = this.options.proxy.userId || '';

    const buff = new SmartBuffer();
    buff.writeUInt8(0x04);
    buff.writeUInt8(SocksCommand[this.options.command]);
    buff.writeUInt16BE(this.options.destination.port);

    // Socks 4 (IPv4)
    if (net.isIPv4(this.options.destination.host)) {
      buff.writeBuffer(ip.toBuffer(this.options.destination.host));
      buff.writeStringNT(userId);
      // Socks 4a (hostname)
    } else {
      buff.writeUInt8(0x00);
      buff.writeUInt8(0x00);
      buff.writeUInt8(0x00);
      buff.writeUInt8(0x01);
      buff.writeStringNT(userId);
      buff.writeStringNT(this.options.destination.host);
    }

    this.nextRequiredPacketBufferSize =
      SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
    this.socket.write(buff.toBuffer());
  }

  /**
   * Handles Socks v4 handshake response.
   * @param data
   */
  private handleSocks4FinalHandshakeResponse() {
    const data = this.receiveBuffer.get(8);

    if (data[1] !== Socks4Response.Granted) {
      this.closeSocket(
        `${ERRORS.Socks4ProxyRejectedConnection} - (${
          Socks4Response[data[1]]
        })`,
      );
    } else {
      // Bind response
      if (SocksCommand[this.options.command] === SocksCommand.bind) {
        const buff = SmartBuffer.fromBuffer(data);
        buff.readOffset = 2;

        const remoteHost: SocksRemoteHost = {
          port: buff.readUInt16BE(),
          host: ip.fromLong(buff.readUInt32BE()),
        };

        // If host is 0.0.0.0, set to proxy host.
        if (remoteHost.host === '0.0.0.0') {
          remoteHost.host = this.options.proxy.ipaddress;
        }
        this.setState(SocksClientState.BoundWaitingForConnection);
        this.emit('bound', {remoteHost, socket: this.socket});

        // Connect response
      } else {
        this.setState(SocksClientState.Established);
        this.removeInternalSocketHandlers();
        this.emit('established', {socket: this.socket});
      }
    }
  }

  /**
   * Handles Socks v4 incoming connection request (BIND)
   * @param data
   */
  private handleSocks4IncomingConnectionResponse() {
    const data = this.receiveBuffer.get(8);

    if (data[1] !== Socks4Response.Granted) {
      this.closeSocket(
        `${ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${
          Socks4Response[data[1]]
        })`,
      );
    } else {
      const buff = SmartBuffer.fromBuffer(data);
      buff.readOffset = 2;

      const remoteHost: SocksRemoteHost = {
        port: buff.readUInt16BE(),
        host: ip.fromLong(buff.readUInt32BE()),
      };

      this.setState(SocksClientState.Established);
      this.removeInternalSocketHandlers();
      this.emit('established', {remoteHost, socket: this.socket});
    }
  }

  /**
   * Sends initial Socks v5 handshake request.
   */
  private sendSocks5InitialHandshake() {
    const buff = new SmartBuffer();

    // By default we always support no auth.
    const supportedAuthMethods = [Socks5Auth.NoAuth];

    // We should only tell the proxy we support user/pass auth if auth info is actually provided.
    // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority.
    if (this.options.proxy.userId || this.options.proxy.password) {
      supportedAuthMethods.push(Socks5Auth.UserPass);
    }

    // Custom auth method?
    if (this.options.proxy.custom_auth_method !== undefined) {
      supportedAuthMethods.push(this.options.proxy.custom_auth_method);
    }

    // Build handshake packet
    buff.writeUInt8(0x05);
    buff.writeUInt8(supportedAuthMethods.length);
    for (const authMethod of supportedAuthMethods) {
      buff.writeUInt8(authMethod);
    }

    this.nextRequiredPacketBufferSize =
      SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
    this.socket.write(buff.toBuffer());
    this.setState(SocksClientState.SentInitialHandshake);
  }

  /**
   * Handles initial Socks v5 handshake response.
   * @param data
   */
  private handleInitialSocks5HandshakeResponse() {
    const data = this.receiveBuffer.get(2);

    if (data[0] !== 0x05) {
      this.closeSocket(ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
    } else if (data[1] === SOCKS5_NO_ACCEPTABLE_AUTH) {
      this.closeSocket(ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
    } else {
      // If selected Socks v5 auth method is no auth, send final handshake request.
      if (data[1] === Socks5Auth.NoAuth) {
        this.socks5ChosenAuthType = Socks5Auth.NoAuth;
        this.sendSocks5CommandRequest();
        // If selected Socks v5 auth method is user/password, send auth handshake.
      } else if (data[1] === Socks5Auth.UserPass) {
        this.socks5ChosenAuthType = Socks5Auth.UserPass;
        this.sendSocks5UserPassAuthentication();
        // If selected Socks v5 auth method is the custom_auth_method, send custom handshake.
      } else if (data[1] === this.options.proxy.custom_auth_method) {
        this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
        this.sendSocks5CustomAuthentication();
      } else {
        this.closeSocket(ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
      }
    }
  }

  /**
   * Sends Socks v5 user & password auth handshake.
   *
   * Note: No auth and user/pass are currently supported.
   */
  private sendSocks5UserPassAuthentication() {
    const userId = this.options.proxy.userId || '';
    const password = this.options.proxy.password || '';

    const buff = new SmartBuffer();
    buff.writeUInt8(0x01);
    buff.writeUInt8(Buffer.byteLength(userId));
    buff.writeString(userId);
    buff.writeUInt8(Buffer.byteLength(password));
    buff.writeString(password);

    this.nextRequiredPacketBufferSize =
      SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
    this.socket.write(buff.toBuffer());
    this.setState(SocksClientState.SentAuthentication);
  }

  private async sendSocks5CustomAuthentication() {
    this.nextRequiredPacketBufferSize =
      this.options.proxy.custom_auth_response_size;
    this.socket.write(await this.options.proxy.custom_auth_request_handler());
    this.setState(SocksClientState.SentAuthentication);
  }

  private async handleSocks5CustomAuthHandshakeResponse(data: Buffer) {
    return await this.options.proxy.custom_auth_response_handler(data);
  }

  private async handleSocks5AuthenticationNoAuthHandshakeResponse(
    data: Buffer,
  ): Promise<boolean> {
    return data[1] === 0x00;
  }

  private async handleSocks5AuthenticationUserPassHandshakeResponse(
    data: Buffer,
  ): Promise<boolean> {
    return data[1] === 0x00;
  }

  /**
   * Handles Socks v5 auth handshake response.
   * @param data
   */
  private async handleInitialSocks5AuthenticationHandshakeResponse() {
    this.setState(SocksClientState.ReceivedAuthenticationResponse);

    let authResult = false;

    if (this.socks5ChosenAuthType === Socks5Auth.NoAuth) {
      authResult = await this.handleSocks5AuthenticationNoAuthHandshakeResponse(
        this.receiveBuffer.get(2),
      );
    } else if (this.socks5ChosenAuthType === Socks5Auth.UserPass) {
      authResult =
        await this.handleSocks5AuthenticationUserPassHandshakeResponse(
          this.receiveBuffer.get(2),
        );
    } else if (
      this.socks5ChosenAuthType === this.options.proxy.custom_auth_method
    ) {
      authResult = await this.handleSocks5CustomAuthHandshakeResponse(
        this.receiveBuffer.get(this.options.proxy.custom_auth_response_size),
      );
    }

    if (!authResult) {
      this.closeSocket(ERRORS.Socks5AuthenticationFailed);
    } else {
      this.sendSocks5CommandRequest();
    }
  }

  /**
   * Sends Socks v5 final handshake request.
   */
  private sendSocks5CommandRequest() {
    const buff = new SmartBuffer();

    buff.writeUInt8(0x05);
    buff.writeUInt8(SocksCommand[this.options.command]);
    buff.writeUInt8(0x00);

    // ipv4, ipv6, domain?
    if (net.isIPv4(this.options.destination.host)) {
      buff.writeUInt8(Socks5HostType.IPv4);
      buff.writeBuffer(ip.toBuffer(this.options.destination.host));
    } else if (net.isIPv6(this.options.destination.host)) {
      buff.writeUInt8(Socks5HostType.IPv6);
      buff.writeBuffer(ip.toBuffer(this.options.destination.host));
    } else {
      buff.writeUInt8(Socks5HostType.Hostname);
      buff.writeUInt8(this.options.destination.host.length);
      buff.writeString(this.options.destination.host);
    }
    buff.writeUInt16BE(this.options.destination.port);

    this.nextRequiredPacketBufferSize =
      SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
    this.socket.write(buff.toBuffer());
    this.setState(SocksClientState.SentFinalHandshake);
  }

  /**
   * Handles Socks v5 final handshake response.
   * @param data
   */
  private handleSocks5FinalHandshakeResponse() {
    // Peek at available data (we need at least 5 bytes to get the hostname length)
    const header = this.receiveBuffer.peek(5);

    if (header[0] !== 0x05 || header[1] !== Socks5Response.Granted) {
      this.closeSocket(
        `${ERRORS.InvalidSocks5FinalHandshakeRejected} - ${
          Socks5Response[header[1]]
        }`,
      );
    } else {
      // Read address type
      const addressType = header[3];

      let remoteHost: SocksRemoteHost;
      let buff: SmartBuffer;

      // IPv4
      if (addressType === Socks5HostType.IPv4) {
        // Check if data is available.
        const dataNeeded = SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(4),
        );

        remoteHost = {
          host: ip.fromLong(buff.readUInt32BE()),
          port: buff.readUInt16BE(),
        };

        // If given host is 0.0.0.0, assume remote proxy ip instead.
        if (remoteHost.host === '0.0.0.0') {
          remoteHost.host = this.options.proxy.ipaddress;
        }

        // Hostname
      } else if (addressType === Socks5HostType.Hostname) {
        const hostLength = header[4];
        const dataNeeded =
          SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port

        // Check if data is available.
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(5), // Slice at 5 to skip host length
        );

        remoteHost = {
          host: buff.readString(hostLength),
          port: buff.readUInt16BE(),
        };
        // IPv6
      } else if (addressType === Socks5HostType.IPv6) {
        // Check if data is available.
        const dataNeeded = SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(4),
        );

        remoteHost = {
          host: ip.toString(buff.readBuffer(16)),
          port: buff.readUInt16BE(),
        };
      }

      // We have everything we need
      this.setState(SocksClientState.ReceivedFinalResponse);

      // If using CONNECT, the client is now in the established state.
      if (SocksCommand[this.options.command] === SocksCommand.connect) {
        this.setState(SocksClientState.Established);
        this.removeInternalSocketHandlers();
        this.emit('established', {remoteHost, socket: this.socket});
      } else if (SocksCommand[this.options.command] === SocksCommand.bind) {
        /* If using BIND, the Socks client is now in BoundWaitingForConnection state.
           This means that the remote proxy server is waiting for a remote connection to the bound port. */
        this.setState(SocksClientState.BoundWaitingForConnection);
        this.nextRequiredPacketBufferSize =
          SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
        this.emit('bound', {remoteHost, socket: this.socket});
        /*
          If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the
          given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work.
        */
      } else if (
        SocksCommand[this.options.command] === SocksCommand.associate
      ) {
        this.setState(SocksClientState.Established);
        this.removeInternalSocketHandlers();
        this.emit('established', {
          remoteHost,
          socket: this.socket,
        });
      }
    }
  }

  /**
   * Handles Socks v5 incoming connection request (BIND).
   */
  private handleSocks5IncomingConnectionResponse() {
    // Peek at available data (we need at least 5 bytes to get the hostname length)
    const header = this.receiveBuffer.peek(5);

    if (header[0] !== 0x05 || header[1] !== Socks5Response.Granted) {
      this.closeSocket(
        `${ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${
          Socks5Response[header[1]]
        }`,
      );
    } else {
      // Read address type
      const addressType = header[3];

      let remoteHost: SocksRemoteHost;
      let buff: SmartBuffer;

      // IPv4
      if (addressType === Socks5HostType.IPv4) {
        // Check if data is available.
        const dataNeeded = SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(4),
        );

        remoteHost = {
          host: ip.fromLong(buff.readUInt32BE()),
          port: buff.readUInt16BE(),
        };

        // If given host is 0.0.0.0, assume remote proxy ip instead.
        if (remoteHost.host === '0.0.0.0') {
          remoteHost.host = this.options.proxy.ipaddress;
        }

        // Hostname
      } else if (addressType === Socks5HostType.Hostname) {
        const hostLength = header[4];
        const dataNeeded =
          SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port

        // Check if data is available.
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(5), // Slice at 5 to skip host length
        );

        remoteHost = {
          host: buff.readString(hostLength),
          port: buff.readUInt16BE(),
        };
        // IPv6
      } else if (addressType === Socks5HostType.IPv6) {
        // Check if data is available.
        const dataNeeded = SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
        if (this.receiveBuffer.length < dataNeeded) {
          this.nextRequiredPacketBufferSize = dataNeeded;
          return;
        }

        buff = SmartBuffer.fromBuffer(
          this.receiveBuffer.get(dataNeeded).slice(4),
        );

        remoteHost = {
          host: ip.toString(buff.readBuffer(16)),
          port: buff.readUInt16BE(),
        };
      }

      this.setState(SocksClientState.Established);
      this.removeInternalSocketHandlers();
      this.emit('established', {remoteHost, socket: this.socket});
    }
  }

  get socksClientOptions(): SocksClientOptions {
    return {
      ...this.options,
    };
  }
}

export {
  SocksClient,
  SocksClientOptions,
  SocksClientChainOptions,
  SocksClientError,
  SocksRemoteHost,
  SocksProxy,
  SocksUDPFrameDetails,
};


text:
The articles in this section show you how to use the SharePoint Add-in model to customize your SharePoint sites. The following table lists the articles that are included.

|**Article**|**Shows you how to use the add-in model to**|
|:-----|:-----|
|[App-Only and Elevated privileges](app-only-elevated-privileges-sharepoint-add-in.md)|Elevate privileges.|
|[Branding SharePoint Sites](branding-sharepoint-sites-sharepoint-add-in.md)|Brand SharePoint sites.|
|[Custom Actions](custom-actions-sharepoint-add-in.md)|Modify list item menus and the ribbon.|
|[Custom Field Type](custom-field-type-sharepoint-add-in.md)|Provide customized end user experiences.|
|[Delegate Controls](delegate-controls-sharepoint-add-in.md)|Implement delegate controls in your code.|
|[Document ID Provider](document-id-provider-sharepoint-add-in.md)|Set unique identifiers for documents.|
|[Event Receivers and List Event Receivers](event-receiver-and-list-event-receiver-sharepoint-add-in.md)|Handle events in SharePoint.|
|[Feature Stapling](feature-stapling-sharepoint-add-in.md)|Run code and deploy artifacts when a SharePoint site is provisioned.|
|[Information Management Policy](information-management-policy-sharepoint-add-in.md)|Apply information management policy.|
|[List Definition / List Template](list-definition-template-sharepoint-add-in.md)|Create list definitions / list templates.|
|[List Instance](list-instance-sharepoint-add-in.md)|Create list instances.|
|[Localization](localization-sharepoint-add-in.md)|Implement localization for add-ins.|
|[Master Pages](master-pages-sharepoint-add-in.md)|Implement custom master pages in SharePoint sites.|
|[MMS manipulation](mms-manipulation-sharepoint-add-in.md)|Perform Create, Read, Update, and Delete (CRUD) operations in the Managed Metadata Service (MMS).|
|[Modules](modules-sharepoint-add-in.md)|Deploy artifacts to a SharePoint environment.|
|[OneDrive for Business customization](onedrive-for-business-customization-sharepoint-add-in.md)|Customize OneDrive for Business sites.|
|[Performance Considerations](performance-considerations-sharepoint-add-in.md)|Ensure optimal performance with SharePoint.|
|[Remote Timer Jobs](remote-timer-jobs-sharepoint-add-in.md)|Implement timer jobs.|
|[Search API Usage](search-api-usage-sharepoint-add-in.md)|Execute searches with the SharePoint Search Service.|
|[Search Configuration](search-configuration-sharepoint-add-in.md)|Configure search.|
|[Site Columns and Content Types](site-columns-and-content-types-sharepoint-add-in.md)|Create site columns and content types in SharePoint sites.|
|[Site Provisioning](site-provisioning-sharepoint-add-in.md)|Provision site collections and subsites.|
|[User Controls and Web Controls](user-controls-and-web-controls-sharepoint-add-in.md)|Implement custom controls in your code.|
|[User Profile Manipulation](user profile manipulation-sharepoint-add-in.md)|Perform Create, Read, Update. and Delete (CRUD) operations in the User Profile Service (UPS).|
|[Variations](variations-sharepoint-add-in.md)|Configure variations.|
|[Web Part](web-part-sharepoint-add-in.md)|Create portable page components.|
|[Workflows, Actions (Activities), Events, and Forms](workflows-actions-events-and-forms-sharepoint-add-in.md)|Implement workflows and their associated components.|
|[Yammer Integration](yammer-integration-sharepoint-add-in.md)|Integrate Yammer with SharePoint.|

## Additional resources
<a name="bk_addresources"> </a>

- [Office 365 development patterns and practices solution guidance](Office-365-development-patterns-and-practices-solution-guidance.md)

redpajama_set_name: RedPajamaGithub


text:
namespace HolidayTest1
{
    partial class AboutForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutForm));
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.SuspendLayout();
            //
            // richTextBox1
            //
            this.richTextBox1.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.richTextBox1.Location = new System.Drawing.Point(0, 0);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ReadOnly = true;
            this.richTextBox1.Size = new System.Drawing.Size(417, 229);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.TabStop = false;
            this.richTextBox1.Text = "";
            //
            // pictureBox1
            //
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(12, 131);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(87, 86);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 1;
            this.pictureBox1.TabStop = false;
            //
            // pictureBox2
            //
            this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
            this.pictureBox2.Location = new System.Drawing.Point(318, 131);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(87, 86);
            this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox2.TabIndex = 2;
            this.pictureBox2.TabStop = false;
            //
            // AboutForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(417, 229);
            this.Controls.Add(this.pictureBox2);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.richTextBox1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MaximumSize = new System.Drawing.Size(433, 267);
            this.MinimizeBox = false;
            this.MinimumSize = new System.Drawing.Size(433, 267);
            this.Name = "AboutForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "About Holiday Tester";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.PictureBox pictureBox2;
    }
}


text:
#include "clar_libgit2.h"

#include "git2/clone.h"
#include "git2/cred_helpers.h"
#include "remote.h"
#include "fileops.h"
#include "refs.h"

#define LIVE_REPO_URL "http://github.com/libgit2/TestGitRepository"
#define LIVE_EMPTYREPO_URL "http://github.com/libgit2/TestEmptyRepository"
#define BB_REPO_URL "https://libgit3@bitbucket.org/libgit2/testgitrepository.git"
#define BB_REPO_URL_WITH_PASS "https://libgit3:libgit3@bitbucket.org/libgit2/testgitrepository.git"
#define BB_REPO_URL_WITH_WRONG_PASS "https://libgit3:wrong@bitbucket.org/libgit2/testgitrepository.git"

#define SSH_REPO_URL "ssh://github.com/libgit2/TestGitRepository"

static git_repository *g_repo;
static git_clone_options g_options;

static char *_remote_url = NULL;
static char *_remote_user = NULL;
static char *_remote_pass = NULL;
static char *_remote_sslnoverify = NULL;
static char *_remote_ssh_pubkey = NULL;
static char *_remote_ssh_privkey = NULL;
static char *_remote_ssh_passphrase = NULL;
static char *_remote_ssh_fingerprint = NULL;
static char *_remote_proxy_scheme = NULL;
static char *_remote_proxy_host = NULL;
static char *_remote_proxy_user = NULL;
static char *_remote_proxy_pass = NULL;
static char *_remote_proxy_selfsigned = NULL;

static int _orig_proxies_need_reset = 0;
static char *_orig_http_proxy = NULL;
static char *_orig_https_proxy = NULL;

static int ssl_cert(git_cert *cert, int valid, const char *host, void *payload)
{
	GIT_UNUSED(cert);
	GIT_UNUSED(host);
	GIT_UNUSED(payload);

	if (_remote_sslnoverify != NULL)
		valid = 1;

	return valid ? 0 : GIT_ECERTIFICATE;
}

void test_online_clone__initialize(void)
{
	git_checkout_options dummy_opts = GIT_CHECKOUT_OPTIONS_INIT;
	git_fetch_options dummy_fetch = GIT_FETCH_OPTIONS_INIT;

	g_repo = NULL;

	memset(&g_options, 0, sizeof(git_clone_options));
	g_options.version = GIT_CLONE_OPTIONS_VERSION;
	g_options.checkout_opts = dummy_opts;
	g_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
	g_options.fetch_opts = dummy_fetch;
	g_options.fetch_opts.callbacks.certificate_check = ssl_cert;

	_remote_url = cl_getenv("GITTEST_REMOTE_URL");
	_remote_user = cl_getenv("GITTEST_REMOTE_USER");
	_remote_pass = cl_getenv("GITTEST_REMOTE_PASS");
	_remote_sslnoverify = cl_getenv("GITTEST_REMOTE_SSL_NOVERIFY");
	_remote_ssh_pubkey = cl_getenv("GITTEST_REMOTE_SSH_PUBKEY");
	_remote_ssh_privkey = cl_getenv("GITTEST_REMOTE_SSH_KEY");
	_remote_ssh_passphrase = cl_getenv("GITTEST_REMOTE_SSH_PASSPHRASE");
	_remote_ssh_fingerprint = cl_getenv("GITTEST_REMOTE_SSH_FINGERPRINT");
	_remote_proxy_scheme = cl_getenv("GITTEST_REMOTE_PROXY_SCHEME");
	_remote_proxy_host = cl_getenv("GITTEST_REMOTE_PROXY_HOST");
	_remote_proxy_user = cl_getenv("GITTEST_REMOTE_PROXY_USER");
	_remote_proxy_pass = cl_getenv("GITTEST_REMOTE_PROXY_PASS");
	_remote_proxy_selfsigned = cl_getenv("GITTEST_REMOTE_PROXY_SELFSIGNED");

	_orig_proxies_need_reset = 0;
}

void test_online_clone__cleanup(void)
{
	if (g_repo) {
		git_repository_free(g_repo);
		g_repo = NULL;
	}
	cl_fixture_cleanup("./foo");

	git__free(_remote_url);
	git__free(_remote_user);
	git__free(_remote_pass);
	git__free(_remote_sslnoverify);
	git__free(_remote_ssh_pubkey);
	git__free(_remote_ssh_privkey);
	git__free(_remote_ssh_passphrase);
	git__free(_remote_ssh_fingerprint);
	git__free(_remote_proxy_scheme);
	git__free(_remote_proxy_host);
	git__free(_remote_proxy_user);
	git__free(_remote_proxy_pass);
	git__free(_remote_proxy_selfsigned);

	if (_orig_proxies_need_reset) {
		cl_setenv("HTTP_PROXY", _orig_http_proxy);
		cl_setenv("HTTPS_PROXY", _orig_https_proxy);

		git__free(_orig_http_proxy);
		git__free(_orig_https_proxy);
	}
}

void test_online_clone__network_full(void)
{
	git_remote *origin;

	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));
	cl_assert(!git_repository_is_bare(g_repo));
	cl_git_pass(git_remote_lookup(&origin, g_repo, "origin"));

	cl_assert_equal_i(GIT_REMOTE_DOWNLOAD_TAGS_AUTO, origin->download_tags);

	git_remote_free(origin);
}

void test_online_clone__network_bare(void)
{
	git_remote *origin;

	g_options.bare = true;

	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));
	cl_assert(git_repository_is_bare(g_repo));
	cl_git_pass(git_remote_lookup(&origin, g_repo, "origin"));

	git_remote_free(origin);
}

void test_online_clone__empty_repository(void)
{
	git_reference *head;

	cl_git_pass(git_clone(&g_repo, LIVE_EMPTYREPO_URL, "./foo", &g_options));

	cl_assert_equal_i(true, git_repository_is_empty(g_repo));
	cl_assert_equal_i(true, git_repository_head_unborn(g_repo));

	cl_git_pass(git_reference_lookup(&head, g_repo, GIT_HEAD_FILE));
	cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head));
	cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head));

	git_reference_free(head);
}

static void checkout_progress(const char *path, size_t cur, size_t tot, void *payload)
{
	bool *was_called = (bool*)payload;
	GIT_UNUSED(path); GIT_UNUSED(cur); GIT_UNUSED(tot);
	(*was_called) = true;
}

static int fetch_progress(const git_transfer_progress *stats, void *payload)
{
	bool *was_called = (bool*)payload;
	GIT_UNUSED(stats);
	(*was_called) = true;
	return 0;
}

void test_online_clone__can_checkout_a_cloned_repo(void)
{
	git_buf path = GIT_BUF_INIT;
	git_reference *head;
	bool checkout_progress_cb_was_called = false,
		  fetch_progress_cb_was_called = false;

	g_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
	g_options.checkout_opts.progress_cb = &checkout_progress;
	g_options.checkout_opts.progress_payload = &checkout_progress_cb_was_called;
	g_options.fetch_opts.callbacks.transfer_progress = &fetch_progress;
	g_options.fetch_opts.callbacks.payload = &fetch_progress_cb_was_called;

	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));

	cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "master.txt"));
	cl_assert_equal_i(true, git_path_isfile(git_buf_cstr(&path)));

	cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD"));
	cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head));
	cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head));

	cl_assert_equal_i(true, checkout_progress_cb_was_called);
	cl_assert_equal_i(true, fetch_progress_cb_was_called);

	git_reference_free(head);
	git_buf_dispose(&path);
}

static int remote_mirror_cb(git_remote **out, git_repository *repo,
			    const char *name, const char *url, void *payload)
{
	int error;
	git_remote *remote;

	GIT_UNUSED(payload);

	if ((error = git_remote_create_with_fetchspec(&remote, repo, name, url, "+refs/*:refs/*")) < 0)
		return error;

	*out = remote;
	return 0;
}

void test_online_clone__clone_mirror(void)
{
	git_clone_options opts = GIT_CLONE_OPTIONS_INIT;
	git_reference *head;

	bool fetch_progress_cb_was_called = false;

	opts.fetch_opts.callbacks.transfer_progress = &fetch_progress;
	opts.fetch_opts.callbacks.payload = &fetch_progress_cb_was_called;

	opts.bare = true;
	opts.remote_cb = remote_mirror_cb;

	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo.git", &opts));

	cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD"));
	cl_assert_equal_i(GIT_REFERENCE_SYMBOLIC, git_reference_type(head));
	cl_assert_equal_s("refs/heads/master", git_reference_symbolic_target(head));

	cl_assert_equal_i(true, fetch_progress_cb_was_called);

	git_reference_free(head);
	git_repository_free(g_repo);
	g_repo = NULL;

	cl_fixture_cleanup("./foo.git");
}

static int update_tips(const char *refname, const git_oid *a, const git_oid *b, void *payload)
{
	int *callcount = (int*)payload;
	GIT_UNUSED(refname); GIT_UNUSED(a); GIT_UNUSED(b);
	*callcount = *callcount + 1;
	return 0;
}

void test_online_clone__custom_remote_callbacks(void)
{
	int callcount = 0;

	g_options.fetch_opts.callbacks.update_tips = update_tips;
	g_options.fetch_opts.callbacks.payload = &callcount;

	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));
	cl_assert(callcount > 0);
}

void test_online_clone__custom_headers(void)
{
	char *empty_header = "";
	char *unnamed_header = "this is a header about nothing";
	char *newlines = "X-Custom: almost OK\n";
	char *conflict = "Accept: defined-by-git";
	char *ok = "X-Custom: this should be ok";

	g_options.fetch_opts.custom_headers.count = 1;

	g_options.fetch_opts.custom_headers.strings = &empty_header;
	cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));

	g_options.fetch_opts.custom_headers.strings = &unnamed_header;
	cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));

	g_options.fetch_opts.custom_headers.strings = &newlines;
	cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));

	g_options.fetch_opts.custom_headers.strings = &conflict;
	cl_git_fail(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));

	/* Finally, we got it right! */
	g_options.fetch_opts.custom_headers.strings = &ok;
	cl_git_pass(git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options));
}

static int cred_failure_cb(
	git_cred **cred,
	const char *url,
	const char *username_from_url,
	unsigned int allowed_types,
	void *data)
{
	GIT_UNUSED(cred); GIT_UNUSED(url); GIT_UNUSED(username_from_url);
	GIT_UNUSED(allowed_types); GIT_UNUSED(data);
	return -172;
}

void test_online_clone__cred_callback_failure_return_code_is_tunnelled(void)
{
	git__free(_remote_url);
	git__free(_remote_user);

	_remote_url = git__strdup("https://github.com/libgit2/non-existent");
	_remote_user = git__strdup("libgit2test");

	g_options.fetch_opts.callbacks.credentials = cred_failure_cb;

	cl_git_fail_with(-172, git_clone(&g_repo, _remote_url, "./foo", &g_options));
}

static int cred_count_calls_cb(git_cred **cred, const char *url, const char *user,
			       unsigned int allowed_types, void *data)
{
	size_t *counter = (size_t *) data;

	GIT_UNUSED(url); GIT_UNUSED(user); GIT_UNUSED(allowed_types);

	if (allowed_types == GIT_CREDTYPE_USERNAME)
		return git_cred_username_new(cred, "foo");

	(*counter)++;

	if (*counter == 3)
		return GIT_EUSER;

	return git_cred_userpass_plaintext_new(cred, "foo", "bar");
}

void test_online_clone__cred_callback_called_again_on_auth_failure(void)
{
	size_t counter = 0;

	git__free(_remote_url);
	git__free(_remote_user);

	_remote_url = git__strdup("https://github.com/libgit2/non-existent");
	_remote_user = git__strdup("libgit2test");

	g_options.fetch_opts.callbacks.credentials = cred_count_calls_cb;
	g_options.fetch_opts.callbacks.payload = &counter;

	cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, _remote_url, "./foo", &g_options));
	cl_assert_equal_i(3, counter);
}

int cred_default(
	git_cred **cred,
	const char *url,
	const char *user_from_url,
	unsigned int allowed_types,
	void *payload)
{
	GIT_UNUSED(url);
	GIT_UNUSED(user_from_url);
	GIT_UNUSED(payload);

	if (!(allowed_types & GIT_CREDTYPE_DEFAULT))
		return 0;

	return git_cred_default_new(cred);
}

void test_online_clone__credentials(void)
{
	/* Remote URL environment variable must be set.
	 * User and password are optional.
	 */
	git_cred_userpass_payload user_pass = {
		_remote_user,
		_remote_pass
	};

	if (!_remote_url)
		clar__skip();

	if (cl_is_env_set("GITTEST_REMOTE_DEFAULT")) {
		g_options.fetch_opts.callbacks.credentials = cred_default;
	} else {
		g_options.fetch_opts.callbacks.credentials = git_cred_userpass;
		g_options.fetch_opts.callbacks.payload = &user_pass;
	}

	cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options));
	git_repository_free(g_repo); g_repo = NULL;
	cl_fixture_cleanup("./foo");
}

void test_online_clone__bitbucket_style(void)
{
	git_cred_userpass_payload user_pass = {
		"libgit3", "libgit3"
	};

	g_options.fetch_opts.callbacks.credentials = git_cred_userpass;
	g_options.fetch_opts.callbacks.payload = &user_pass;

	cl_git_pass(git_clone(&g_repo, BB_REPO_URL, "./foo", &g_options));
	git_repository_free(g_repo); g_repo = NULL;
	cl_fixture_cleanup("./foo");
}

void test_online_clone__bitbucket_uses_creds_in_url(void)
{
	git_cred_userpass_payload user_pass = {
		"libgit2", "wrong"
	};

	g_options.fetch_opts.callbacks.credentials = git_cred_userpass;
	g_options.fetch_opts.callbacks.payload = &user_pass;

	/*
	 * Correct user and pass are in the URL; the (incorrect) creds in
	 * the `git_cred_userpass_payload` should be ignored.
	 */
	cl_git_pass(git_clone(&g_repo, BB_REPO_URL_WITH_PASS, "./foo", &g_options));
	git_repository_free(g_repo); g_repo = NULL;
	cl_fixture_cleanup("./foo");
}

void test_online_clone__bitbucket_falls_back_to_specified_creds(void)
{
	git_cred_userpass_payload user_pass = {
		"libgit2", "libgit2"
	};

	g_options.fetch_opts.callbacks.credentials = git_cred_userpass;
	g_options.fetch_opts.callbacks.payload = &user_pass;

	/*
	 * TODO: as of March 2018, bitbucket sporadically fails with
	 * 403s instead of replying with a 401 - but only sometimes.
	 */
	cl_skip();

	/*
	 * Incorrect user and pass are in the URL; the (correct) creds in
	 * the `git_cred_userpass_payload` should be used as a fallback.
	 */
	cl_git_pass(git_clone(&g_repo, BB_REPO_URL_WITH_WRONG_PASS, "./foo", &g_options));
	git_repository_free(g_repo); g_repo = NULL;
	cl_fixture_cleanup("./foo");
}

static int cancel_at_half(const git_transfer_progress *stats, void *payload)
{
	GIT_UNUSED(payload);

	if (stats->received_objects > (stats->total_objects/2))
		return 4321;
	return 0;
}

void test_online_clone__can_cancel(void)
{
	g_options.fetch_opts.callbacks.transfer_progress = cancel_at_half;

	cl_git_fail_with(
		git_clone(&g_repo, LIVE_REPO_URL, "./foo", &g_options), 4321);
}

static int cred_cb(git_cred **cred, const char *url, const char *user_from_url,
		   unsigned int allowed_types, void *payload)
{
	GIT_UNUSED(url); GIT_UNUSED(user_from_url); GIT_UNUSED(payload);

	if (allowed_types & GIT_CREDTYPE_USERNAME)
		return git_cred_username_new(cred, _remote_user);

	if (allowed_types & GIT_CREDTYPE_SSH_KEY)
		return git_cred_ssh_key_new(cred,
			_remote_user, _remote_ssh_pubkey,
			_remote_ssh_privkey, _remote_ssh_passphrase);

	git_error_set(GIT_ERROR_NET, "unexpected cred type");
	return -1;
}

static int check_ssh_auth_methods(git_cred **cred, const char *url, const char *username_from_url,
				  unsigned int allowed_types, void *data)
{
	int *with_user = (int *) data;
	GIT_UNUSED(cred); GIT_UNUSED(url); GIT_UNUSED(username_from_url); GIT_UNUSED(data);

	if (!*with_user)
		cl_assert_equal_i(GIT_CREDTYPE_USERNAME, allowed_types);
	else
		cl_assert(!(allowed_types & GIT_CREDTYPE_USERNAME));

	return GIT_EUSER;
}

void test_online_clone__ssh_auth_methods(void)
{
	int with_user;

#ifndef GIT_SSH
	clar__skip();
#endif
	g_options.fetch_opts.callbacks.credentials = check_ssh_auth_methods;
	g_options.fetch_opts.callbacks.payload = &with_user;
	g_options.fetch_opts.callbacks.certificate_check = NULL;

	with_user = 0;
	cl_git_fail_with(GIT_EUSER,
		git_clone(&g_repo, SSH_REPO_URL, "./foo", &g_options));

	with_user = 1;
	cl_git_fail_with(GIT_EUSER,
		git_clone(&g_repo, "ssh://git@github.com/libgit2/TestGitRepository", "./foo", &g_options));
}

static int custom_remote_ssh_with_paths(
	git_remote **out,
	git_repository *repo,
	const char *name,
	const char *url,
	void *payload)
{
	int error;

	GIT_UNUSED(payload);

	if ((error = git_remote_create(out, repo, name, url)) < 0)
		return error;

	return 0;
}

void test_online_clone__ssh_with_paths(void)
{
	char *bad_paths[] = {
		"/bin/yes",
		"/bin/false",
	};
	char *good_paths[] = {
		"/usr/bin/git-upload-pack",
		"/usr/bin/git-receive-pack",
	};
	git_strarray arr = {
		bad_paths,
		2,
	};

#ifndef GIT_SSH
	clar__skip();
#endif
	if (!_remote_url || !_remote_user || strncmp(_remote_url, "ssh://", 5) != 0)
		clar__skip();

	g_options.remote_cb = custom_remote_ssh_with_paths;
	g_options.fetch_opts.callbacks.transport = git_transport_ssh_with_paths;
	g_options.fetch_opts.callbacks.credentials = cred_cb;
	g_options.fetch_opts.callbacks.payload = &arr;
	g_options.fetch_opts.callbacks.certificate_check = NULL;

	cl_git_fail(git_clone(&g_repo, _remote_url, "./foo", &g_options));

	arr.strings = good_paths;
	cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options));
}

static int cred_foo_bar(git_cred **cred, const char *url, const char *username_from_url,
				  unsigned int allowed_types, void *data)

{
	GIT_UNUSED(url); GIT_UNUSED(username_from_url); GIT_UNUSED(allowed_types); GIT_UNUSED(data);

	return git_cred_userpass_plaintext_new(cred, "foo", "bar");
}

void test_online_clone__ssh_cannot_change_username(void)
{
#ifndef GIT_SSH
	clar__skip();
#endif
	g_options.fetch_opts.callbacks.credentials = cred_foo_bar;

	cl_git_fail(git_clone(&g_repo, "ssh://git@github.com/libgit2/TestGitRepository", "./foo", &g_options));
}

int ssh_certificate_check(git_cert *cert, int valid, const char *host, void *payload)
{
	git_cert_hostkey *key;
	git_oid expected = {{0}}, actual = {{0}};

	GIT_UNUSED(valid);
	GIT_UNUSED(payload);

	cl_assert(_remote_ssh_fingerprint);

	cl_git_pass(git_oid_fromstrp(&expected, _remote_ssh_fingerprint));
	cl_assert_equal_i(GIT_CERT_HOSTKEY_LIBSSH2, cert->cert_type);
	key = (git_cert_hostkey *) cert;

	/*
	 * We need to figure out how long our input was to check for
	 * the type. Here we abuse the fact that both hashes fit into
	 * our git_oid type.
	 */
	if (strlen(_remote_ssh_fingerprint) == 32 && key->type & GIT_CERT_SSH_MD5) {
		memcpy(&actual.id, key->hash_md5, 16);
	} else 	if (strlen(_remote_ssh_fingerprint) == 40 && key->type & GIT_CERT_SSH_SHA1) {
		memcpy(&actual, key->hash_sha1, 20);
	} else {
		cl_fail("Cannot find a usable SSH hash");
	}

	cl_assert(!memcmp(&expected, &actual, 20));

	cl_assert_equal_s("localhost", host);

	return GIT_EUSER;
}

void test_online_clone__ssh_cert(void)
{
	g_options.fetch_opts.callbacks.certificate_check = ssh_certificate_check;

	if (!_remote_ssh_fingerprint)
		cl_skip();

	cl_git_fail_with(GIT_EUSER, git_clone(&g_repo, _remote_url, "./foo", &g_options));
}

static char *read_key_file(const char *path)
{
	FILE *f;
	char *buf;
	long key_length;

	if (!path || !*path)
		return NULL;

	cl_assert((f = fopen(path, "r")) != NULL);
	cl_assert(fseek(f, 0, SEEK_END) != -1);
	cl_assert((key_length = ftell(f)) != -1);
	cl_assert(fseek(f, 0, SEEK_SET) != -1);
	cl_assert((buf = malloc(key_length)) != NULL);
	cl_assert(fread(buf, key_length, 1, f) == 1);
	fclose(f);

	return buf;
}

static int ssh_memory_cred_cb(git_cred **cred, const char *url, const char *user_from_url,
		   unsigned int allowed_types, void *payload)
{
	GIT_UNUSED(url); GIT_UNUSED(user_from_url); GIT_UNUSED(payload);

	if (allowed_types & GIT_CREDTYPE_USERNAME)
		return git_cred_username_new(cred, _remote_user);

	if (allowed_types & GIT_CREDTYPE_SSH_KEY)
	{
		char *pubkey = read_key_file(_remote_ssh_pubkey);
		char *privkey = read_key_file(_remote_ssh_privkey);

		int ret = git_cred_ssh_key_memory_new(cred, _remote_user, pubkey, privkey, _remote_ssh_passphrase);

		if (privkey)
			free(privkey);
		if (pubkey)
			free(pubkey);
		return ret;
	}

	git_error_set(GIT_ERROR_NET, "unexpected cred type");
	return -1;
}

void test_online_clone__ssh_memory_auth(void)
{
#ifndef GIT_SSH_MEMORY_CREDENTIALS
	clar__skip();
#endif
	if (!_remote_url || !_remote_user || !_remote_ssh_privkey || strncmp(_remote_url, "ssh://", 5) != 0)
		clar__skip();

	g_options.fetch_opts.callbacks.credentials = ssh_memory_cred_cb;

	cl_git_pass(git_clone(&g_repo, _remote_url, "./foo", &g_options));
}

void test_online_clone__url_with_no_path_returns_EINVALIDSPEC(void)
{
	cl_git_fail_with(git_clone(&g_repo, "http://github.com", "./foo", &g_options),
		GIT_EINVALIDSPEC);
}

static int fail_certificate_check(git_cert *cert, int valid, const char *host, void *payload)
{
	GIT_UNUSED(cert);
	GIT_UNUSED(valid);
	GIT_UNUSED(host);
	GIT_UNUSED(payload);

	return GIT_ECERTIFICATE;
}

void test_online_clone__certificate_invalid(void)
{
	g_options.fetch_opts.callbacks.certificate_check = fail_certificate_check;

	cl_git_fail_with(git_clone(&g_repo, "https://github.com/libgit2/TestGitRepository", "./foo", &g_options),
		GIT_ECERTIFICATE);

#ifdef GIT_SSH
	cl_git_fail_with(git_clone(&g_repo, "ssh://github.com/libgit2/TestGitRepository", "./foo", &g_options),
		GIT_ECERTIFICATE);
#endif
}

static int succeed_certificate_check(git_cert *cert, int valid, const char *host, void *payload)
{
	GIT_UNUSED(cert);
	GIT_UNUSED(valid);
	GIT_UNUSED(payload);

	cl_assert_equal_s("github.com", host);

	return 0;
}

void test_online_clone__certificate_valid(void)
{
	g_options.fetch_opts.callbacks.certificate_check = succeed_certificate_check;

	cl_git_pass(git_clone(&g_repo, "https://github.com/libgit2/TestGitRepository", "./foo", &g_options));
}

void test_online_clone__start_with_http(void)
{
	g_options.fetch_opts.callbacks.certificate_check = succeed_certificate_check;

	cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options));
}

static int called_proxy_creds;
static int proxy_cred_cb(git_cred **out, const char *url, const char *username, unsigned int allowed, void *payload)
{
	GIT_UNUSED(url);
	GIT_UNUSED(username);
	GIT_UNUSED(allowed);
	GIT_UNUSED(payload);

	called_proxy_creds = 1;
	return git_cred_userpass_plaintext_new(out, _remote_proxy_user, _remote_proxy_pass);
}

static int proxy_cert_cb(git_cert *cert, int valid, const char *host, void *payload)
{
	char *colon;
	size_t host_len;

	GIT_UNUSED(cert);
	GIT_UNUSED(valid);
	GIT_UNUSED(payload);

	cl_assert(_remote_proxy_host);

	if ((colon = strchr(_remote_proxy_host, ':')) != NULL)
		host_len = (colon - _remote_proxy_host);
	else
		host_len = strlen(_remote_proxy_host);

	if (_remote_proxy_selfsigned != NULL &&
	    strlen(host) == host_len &&
	    strncmp(_remote_proxy_host, host, host_len) == 0)
		valid = 1;

	return valid ? 0 : GIT_ECERTIFICATE;
}

void test_online_clone__proxy_credentials_request(void)
{
	git_buf url = GIT_BUF_INIT;

	if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass)
		cl_skip();

	cl_git_pass(git_buf_printf(&url, "%s://%s/",
		_remote_proxy_scheme ? _remote_proxy_scheme : "http",
		_remote_proxy_host));

	g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED;
	g_options.fetch_opts.proxy_opts.url = url.ptr;
	g_options.fetch_opts.proxy_opts.credentials = proxy_cred_cb;
	g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb;
	called_proxy_creds = 0;
	cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options));
	cl_assert(called_proxy_creds);

	git_buf_dispose(&url);
}

void test_online_clone__proxy_credentials_in_url(void)
{
	git_buf url = GIT_BUF_INIT;

	if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass)
		cl_skip();

	cl_git_pass(git_buf_printf(&url, "%s://%s:%s@%s/",
		_remote_proxy_scheme ? _remote_proxy_scheme : "http",
		_remote_proxy_user, _remote_proxy_pass, _remote_proxy_host));

	g_options.fetch_opts.proxy_opts.type = GIT_PROXY_SPECIFIED;
	g_options.fetch_opts.proxy_opts.url = url.ptr;
	g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb;
	called_proxy_creds = 0;
	cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options));
	cl_assert(called_proxy_creds == 0);

	git_buf_dispose(&url);
}

void test_online_clone__proxy_credentials_in_environment(void)
{
	git_buf url = GIT_BUF_INIT;

	if (!_remote_proxy_host || !_remote_proxy_user || !_remote_proxy_pass)
		cl_skip();

	_orig_http_proxy = cl_getenv("HTTP_PROXY");
	_orig_https_proxy = cl_getenv("HTTPS_PROXY");
	_orig_proxies_need_reset = 1;

	g_options.fetch_opts.proxy_opts.type = GIT_PROXY_AUTO;
	g_options.fetch_opts.proxy_opts.certificate_check = proxy_cert_cb;

	cl_git_pass(git_buf_printf(&url, "%s://%s:%s@%s/",
		_remote_proxy_scheme ? _remote_proxy_scheme : "http",
		_remote_proxy_user, _remote_proxy_pass, _remote_proxy_host));

	cl_setenv("HTTP_PROXY", url.ptr);
	cl_setenv("HTTPS_PROXY", url.ptr);

	cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options));

	git_buf_dispose(&url);
}

void test_online_clone__proxy_auto_not_detected(void)
{
	g_options.fetch_opts.proxy_opts.type = GIT_PROXY_AUTO;

	cl_git_pass(git_clone(&g_repo, "http://github.com/libgit2/TestGitRepository", "./foo", &g_options));
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using Zifmia.FyreVM.Service;

namespace FyreVMDemo.Game
{
    public class GlulxStateService
    {
        #region Singleton Pattern

        protected static GlulxStateService _instance;

        public static GlulxStateService Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new GlulxStateService();
                }

                return _instance;
            }
        }
        #endregion

        private Dictionary<eGlulxCommands, string> _dGlulxCommands = new Dictionary<eGlulxCommands, string>();
        private EngineWrapper _fyreVmWrapper;

        private bool _bShutdown = false;

        public GlulxStateService()
        {
            _dGlulxCommands.Add(eGlulxCommands.Look, "look");
            _dGlulxCommands.Add(eGlulxCommands.Wait, "wait");
        }

        public void Initialize(object data)
        {
            if (data == null)
            {
                return;
            }

            var ulxFile = data as TextAsset;
            if(ulxFile == null)
            {
                return;
            }

            var buffer = ulxFile.bytes;

            _fyreVmWrapper = new EngineWrapper(buffer);

            _bShutdown = false;
        }

        public void Shutdown()
        {
            _bShutdown = true;
        }

        public void InitialScene()
        {
            _fyreVmWrapper.SendCommand(_dGlulxCommands[eGlulxCommands.Look]);

            ProcessLocationGlulxOutput(_fyreVmWrapper.FromHash());
        }

        public void Look()
        {
            if (_bShutdown == true)
            {
                return;
            }

            _fyreVmWrapper.SendCommand(_dGlulxCommands[eGlulxCommands.Look]);

            this.ProcessGlulxOutput(_fyreVmWrapper.FromHash());
        }

        public void GoToDirection(string sMessage)
        {
            _fyreVmWrapper.SendCommand(sMessage);

            this.ProcessLocationGlulxOutput(_fyreVmWrapper.FromHash());
        }

        public void Wait()
        {
            _fyreVmWrapper.SendCommand(_dGlulxCommands[eGlulxCommands.Wait]);

            this.ProcessGlulxOutput(_fyreVmWrapper.FromHash());
        }

        #region ParsingSpecificGlulxChannels

        private void ParseLocation(string sValue)
        {
            try
            {
                var sParsed = sValue.Split(':');

                if (sParsed.Length != 1) return;

                var sLevelID = sParsed[0].ToUpperInvariant();

                TransitionController.Instance.Transition(sLevelID);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
            }
        }

        #endregion

        private string GetOutputChannelString(Dictionary<string, string> outputChannels, eStateOutputChannels eChannel)
        {
            var sChannel = GameConstants.OutputChannelToString(eChannel);

            if (outputChannels.ContainsKey(sChannel) == false)
            {
                return String.Empty;
            }

            return outputChannels[sChannel];
        }

        private void ProcessGlulxOutput(Dictionary<string, string> outputChannels)
        {
            if (_bShutdown == true)
            {
                return;
            }

            var sChannelOutput = "";

            sChannelOutput = this.GetOutputChannelString(outputChannels, eStateOutputChannels.EndGame);

            this.ParseEndEpisode(sChannelOutput);

            sChannelOutput = this.GetOutputChannelString(outputChannels, eStateOutputChannels.Location);

            if (string.IsNullOrEmpty(sChannelOutput) == false)
            {
                this.ParseLocation(sChannelOutput);
            }
        }

        private void ParseEndEpisode(string sChannelOutput)
        {
            if (string.IsNullOrEmpty(sChannelOutput) == false)
            {
                //stateEndEpisodeSignal.Dispatch();
            }
        }

        private void ProcessLocationGlulxOutput(Dictionary<string, string> outputChannels)
        {
            if (_bShutdown == true)
            {
                return;
            }

            var sChannelOutput = this.GetOutputChannelString(outputChannels, eStateOutputChannels.Location);

            if (string.IsNullOrEmpty(sChannelOutput) == false)
            {
                this.ParseLocation(sChannelOutput);
            }
        }
    }
}


text:
import java.util.List;

public class Main {
  public static void test(List<String> list) {
    list.stream().ma<caret>p((String s) -> s.trim()).forEach(x -> System.out.println(x));
  }
}


text:
using System;

namespace DoFactory.GangOfFour.Strategy.Structural
{
  /// <summary>
  /// MainApp startup class for Structural
  /// Strategy Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      Context context;

      // Three contexts following different strategies
      context = new Context(new ConcreteStrategyA());
      context.ContextInterface();

      context = new Context(new ConcreteStrategyB());
      context.ContextInterface();

      context = new Context(new ConcreteStrategyC());
      context.ContextInterface();

      // Wait for user
      Console.ReadKey();
    }
  }

  /// <summary>
  /// The 'Strategy' abstract class
  /// </summary>
  abstract class Strategy
  {
    public abstract void AlgorithmInterface();
  }

  /// <summary>
  /// A 'ConcreteStrategy' class
  /// </summary>
  class ConcreteStrategyA : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyA.AlgorithmInterface()");
    }
  }

  /// <summary>
  /// A 'ConcreteStrategy' class
  /// </summary>
  class ConcreteStrategyB : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyB.AlgorithmInterface()");
    }
  }

  /// <summary>
  /// A 'ConcreteStrategy' class
  /// </summary>
  class ConcreteStrategyC : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyC.AlgorithmInterface()");
    }
  }

  /// <summary>
  /// The 'Context' class
  /// </summary>
  class Context
  {
    private Strategy _strategy;

    // Constructor
    public Context(Strategy strategy)
    {
      this._strategy = strategy;
    }

    public void ContextInterface()
    {
      _strategy.AlgorithmInterface();
    }
  }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Http;
using OpenMetaverse.StructuredData;
using CableBeachMessages;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;

namespace OpenSim.Grid.UserServer.Modules.RexLogin
{

    public static class LindenLoginHelper
    {
        public const int REQUEST_TIMEOUT = 1000 * 100;
        public static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        static Random rng = new Random();

        public static void SetClassifiedCategories(ref LindenLoginData response)
        {
            response.AddClassifiedCategory(1, "Shopping");
            response.AddClassifiedCategory(2, "Land Rental");
            response.AddClassifiedCategory(3, "Property Rental");
            response.AddClassifiedCategory(4, "Special Attraction");
            response.AddClassifiedCategory(5, "New Products");
            response.AddClassifiedCategory(6, "Employment");
            response.AddClassifiedCategory(7, "Wanted");
            response.AddClassifiedCategory(8, "Service");
            response.AddClassifiedCategory(9, "Personal");
        }

        public static Hashtable GetBuddyList(UUID avatarID)
        {
            // TODO: Buddy list support
            return new Hashtable(0);
        }

        public static bool TryPrepareLogin(OpenSim.Grid.UserServer.Modules.RexLogin.Avatar avatar,
            CableBeachMessages.RegionInfo startRegion,
            Vector3 startPosition,
            string clientVersion,
            System.Net.IPAddress clientIP,
            ref OpenSim.Grid.UserServer.Modules.RexLogin.LindenLoginData response,
            X509Certificate2 httpCertificate )
        {
            EnableClientMessage message = new EnableClientMessage();
            message.Identity = avatar.Identity;
            message.AgentID = avatar.ID;
            message.Attributes = avatar.Attributes;
            message.CallbackUri = null;
            message.ChildAgent = false;
            message.CircuitCode = CreateCircuitCode();
            message.ClientVersion = clientVersion;
            message.IP = clientIP;
            message.RegionHandle = startRegion.Handle;
            message.SecureSessionID = response.SecureSessionID;
            message.Services = avatar.Services.ToMessageDictionary();
            Dictionary<Uri, Uri> avStrgDict = new Dictionary<Uri, Uri>();
            avStrgDict.Add(
                OpenSim.Grid.UserServer.Modules.RexLogin.RexAvatarAttributes.AVATAR_STORAGE_URL,
                avatar.Attributes[OpenSim.Grid.UserServer.Modules.RexLogin.RexAvatarAttributes.AVATAR_STORAGE_URL].AsUri());
            message.Services.Add(OpenSim.Grid.UserServer.Modules.RexLogin.RexAvatarAttributes.AVATAR_STORAGE_URL, avStrgDict);
            message.SessionID = response.SessionID;

            Uri enableClientCap;
            if (startRegion.Capabilities.TryGetValue(new Uri(CableBeachServices.SIMULATOR_ENABLE_CLIENT), out enableClientCap))
            {
                CapsClient request = (httpCertificate != null) ?
                new CapsClient(enableClientCap, httpCertificate) :
                new CapsClient(enableClientCap);

                OSDMap responseMap = request.GetResponse(message.Serialize(), OSDFormat.Json, REQUEST_TIMEOUT) as OSDMap;

                if (responseMap != null)
                {
                    EnableClientReplyMessage reply = new EnableClientReplyMessage();
                    reply.Deserialize(responseMap);

                    if (reply.SeedCapability != null)
                    {
                        m_log.Info("enable_client succeeded, sent circuit code " + message.CircuitCode + " and received seed capability " +
                            reply.SeedCapability + " from " + enableClientCap);

                        response.CircuitCode = message.CircuitCode;
                        response.SeedCapability = reply.SeedCapability.ToString();
                        return true;
                    }
                    else
                    {
                        m_log.Error("[LindenLoginHelper] enable_client call to region " + startRegion.Name + " for login from " + avatar.Identity +
                            " failed, did not return a seed capability");
                    }
                }
                else
                {
                    m_log.Error("[LindenLoginHelper] enable_client call to region " + startRegion.Name + " for login from " + avatar.Identity +
                        " failed, could not contact or invalid response");
                }
            }
            else
            {
                m_log.Error("[LindenLoginHelper] enable_client call failed, region " + startRegion.Name +
                    " does not have an enable_client capability");
            }

            return false;
        }

        public static int CreateCircuitCode()
        {
            // TODO: Track these so we don't generate duplicate circuit codes
            return rng.Next(0, Int32.MaxValue);
        }

        #region Login XML responses

        public static XmlRpcResponse CreateFailureResponse(string reason, string message, bool loginSuccess)
        {
            Hashtable responseData = new Hashtable(3);
            responseData["reason"] = reason;
            responseData["message"] = message;
            responseData["login"] = loginSuccess.ToString().ToLower();

            XmlRpcResponse response = new XmlRpcResponse();
            response.Value = responseData;
            return response;
        }

        public static XmlRpcResponse CreateLoginFailedResponse()
        {
            return CreateFailureResponse(
                "key",
                "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
                false);
        }

        public static XmlRpcResponse CreateLoginGridErrorResponse()
        {
            return CreateFailureResponse(
                "key",
                "Error connecting to grid. Could not perceive credentials from login XML.",
                false);
        }

        public static XmlRpcResponse CreateLoginBlockedResponse()
        {
            return CreateFailureResponse(
                "presence",
                "Logins are currently restricted. Please try again later",
                false);
        }

        public static XmlRpcResponse CreateLoginInternalErrorResponse()
        {
            return CreateFailureResponse(
                "key",
                "The login server failed to complete the login process. Please try again later",
                false);
        }

        public static XmlRpcResponse CreateLoginServicesErrorResponse()
        {
            return CreateFailureResponse(
                "key",
                "The login server failed to locate a required grid service. Please try again later",
                false);
        }

        public static XmlRpcResponse CreateLoginNoRegionResponse()
        {
            return CreateFailureResponse(
                "key",
                "The login server could not find an available region to login to. Please try again later",
                false);
        }

        #endregion Login XML responses
    }
}


text:
<?php

namespace UthandoNewsletter\View\Renderer;

use UthandoNewsletter\Model\MessageModel;
use UthandoNewsletter\Model\TemplateModel;
use Zend\Config\Reader\Ini;
use Zend\View\Helper\Url;

/**
 * Class NewsletterEngine
 *
 * @package UthandoNewsletter\View\Renderer
 */
class NewsletterEngine
{
    /**
     * @var array
     */
    protected $variables;

    /**
     * @var bool
     */
    protected $parseImages = false;

    /**
     * @var Url
     */
    protected $urlHelper;

    /**
     * @return Url
     */
    public function getUrlHelper()
    {
        return $this->urlHelper;
    }

    /**
     * @param Url $urlHelper
     * @return $this
     */
    public function setUrlHelper($urlHelper)
    {
        $this->urlHelper = $urlHelper;
        return $this;
    }

    /**
     * @return boolean
     */
    public function isParseImages()
    {
        return $this->parseImages;
    }

    /**
     * @param boolean $parseImages
     * @return $this
     */
    public function setParseImages($parseImages)
    {
        $this->parseImages = $parseImages;
        return $this;
    }

    /**
     * @return array
     */
    public function getVariables()
    {
        return $this->variables;
    }

    /**
     * @param $name
     * @return null|mixed
     */
    public function getVariable($name)
    {
        if (isset($this->variables[$name])) {
            $var = $this->variables[$name];
        } elseif (isset($this->variables[strtoupper($name)])) {
            $var = $this->variables[strtoupper($name)];
        } else {
            $var = null;
        }

        return $var;
    }

    /**
     * @param array $variables
     * @return $this
     */
    public function setVariables($variables)
    {
        $this->variables = $variables;
        return $this;
    }

    /**
     * @param $name
     * @param $value
     * @return $this
     */
    public function setVariable($name, $value)
    {
        $this->variables[$name] = $value;
        return $this;
    }

    /**
     * @param $html
     * @return string
     */
    public function parseVariables($html)
    {
        $unsubscribeLink = $this->getVariable('unsubscribe');

        if (!$unsubscribeLink) {
            $this->setUnsubscribeLink();
        }

        foreach ($this->getVariables() as $key => $variable) {
            $html = str_replace('{' . strtoupper($key) . '}', $variable, $html);
        }

        return $html;
    }

    /**
     * Renders images into inline image using base64 encoding
     *
     */
    public function renderImages()
    {
        foreach ($this->getVariables() as $key => $variable) {
            if (is_file($variable)) {
                $type = pathinfo($variable, PATHINFO_EXTENSION);
                $data = file_get_contents($variable);
                $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                $this->setVariable($key, $base64);
            }
        }
    }

    /**
     * @param TemplateModel|MessageModel $model
     * @return string
     */
    public function parseParams($model)
    {
        $iniReader = new Ini();
        $params = $iniReader->fromString($model->getParams());

        if ($model instanceof MessageModel) {
            $params = array_merge(parse_ini_string($model->getTemplate()->getParams()), $params);
        }

        $this->setVariables($params);
    }

    /**
     * Set the unsubscribe link
     */
    public function setUnsubscribeLink()
    {
        $urlHelper  = $this->getUrlHelper();
        $url        = $this->getVariable('server_url') . $urlHelper('newsletter');

        $this->setVariable('unsubscribe', $url);
    }

    /**
     * @param TemplateModel|MessageModel $model
     * @return string
     */
    public function render($model)
    {
        $this->parseParams($model);

        if ($model instanceof TemplateModel) {
            $body = $model->getBody();
        } else {
            $this->setVariable('content', $model->getMessage());
            $body = $model->getTemplate()->getBody();
        }

        if ($this->isParseImages()) {
            $this->renderImages();
        }

        return $this->parseVariables($body);
    }
}


text:
package com.bmge.framework.implementation;

import java.util.List;

import android.view.View.OnTouchListener;

import com.bmge.framework.Input.TouchEvent;

public interface TouchHandler extends OnTouchListener {
    public boolean isTouchDown(int pointer);

    public int getTouchX(int pointer);

    public int getTouchY(int pointer);

    public List<TouchEvent> getTouchEvents();
}


text:
#include "tensorflow/core/grappler/optimizers/data/map_parallelization.h"

#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/optimizers/data/graph_test_utils.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace grappler {
namespace {

Status OptimizeWithMapParallelization(const GrapplerItem& item,
                                      GraphDef* output, bool autotune) {
  MapParallelization optimizer;
  RewriterConfig_CustomGraphOptimizer config;
  if (autotune) {
    (*config.mutable_parameter_map())["autotune"].set_s("true");
  } else {
    (*config.mutable_parameter_map())["autotune"].set_s("false");
  }
  TF_RETURN_IF_ERROR(optimizer.Init(&config));
  return optimizer.Optimize(nullptr, item, output);
}

using graph_tests_utils::MakeMapNode;
const char stateless_fun_name[] = "XTimesTwo";
const char stateful_fun_name[] = "RandomUniform";

class AutotuneSetting : public ::testing::TestWithParam<bool> {};

TEST_P(AutotuneSetting, MapParallelizationTest) {
  const bool autotune = GetParam();

  using test::function::NDef;
  GrapplerItem item;
  item.graph = test::function::GDef(
      {NDef("start", "Const", {}, {{"value", 0}, {"dtype", DT_INT32}}),
       NDef("stop", "Const", {}, {{"value", 10}, {"dtype", DT_INT32}}),
       NDef("step", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
       NDef("range", "RangeDataset", {"start", "stop", "step"}, {}),
       MakeMapNode("map", "range", stateless_fun_name),
       NDef("Sink", "Identity", {"map"}, {})},
      // FunctionLib
      {
          test::function::XTimesTwo(),
      });

  item.fetch.push_back("Sink");

  GraphDef output;
  TF_ASSERT_OK(OptimizeWithMapParallelization(item, &output, autotune));
  EXPECT_EQ(graph_utils::ContainsNodeWithOp("ParallelMapDatasetV2", output),
            autotune);
  EXPECT_EQ(graph_utils::ContainsGraphNodeWithName("map", output), !autotune);
}

INSTANTIATE_TEST_SUITE_P(Test, AutotuneSetting, ::testing::Values(false, true));

class FromFunctionDef : public ::testing::TestWithParam<string> {};

TEST_P(FromFunctionDef, MapParallelizationTest) {
  const string op = GetParam();
  bool from_function_def = (op == "_Retval");

  using test::function::NDef;
  GrapplerItem item;
  item.graph = test::function::GDef(
      {NDef("start", "Const", {}, {{"value", 0}, {"dtype", DT_INT32}}),
       NDef("stop", "Const", {}, {{"value", 10}, {"dtype", DT_INT32}}),
       NDef("step", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
       NDef("range", "RangeDataset", {"start", "stop", "step"}, {}),
       MakeMapNode("map", "range", stateless_fun_name),
       NDef("Sink", op, {"map"}, {})},
      // FunctionLib
      {
          test::function::XTimesTwo(),
      });

  item.fetch.push_back("Sink");

  GraphDef output;
  TF_ASSERT_OK(OptimizeWithMapParallelization(item, &output, true));
  EXPECT_EQ(graph_utils::ContainsNodeWithOp("ParallelMapDatasetV2", output),
            !from_function_def);
  EXPECT_EQ(graph_utils::ContainsGraphNodeWithName("map", output),
            from_function_def);
}

INSTANTIATE_TEST_SUITE_P(Test, FromFunctionDef,
                         ::testing::Values("Identity", "_Retval"));

TEST(ParallelizeAssert, MapParallelizationTest) {
  using test::function::NDef;
  GrapplerItem item;
  item.graph = test::function::GDef(
      {NDef("start", "Const", {}, {{"value", 0}, {"dtype", DT_INT32}}),
       NDef("stop", "Const", {}, {{"value", 10}, {"dtype", DT_INT32}}),
       NDef("step", "Const", {}, {{"value", 1}, {"dtype", DT_INT32}}),
       NDef("filename", "Const", {}, {{"value", ""}, {"dtype", DT_STRING}}),
       NDef("range", "RangeDataset", {"start", "stop", "step"}, {}),
       MakeMapNode("map1", "range", stateful_fun_name),
       MakeMapNode("map2", "map1", stateless_fun_name),
       NDef("cache", "CacheDataset", {"map2", "filename"}, {}),
       NDef("Sink", "Identity", {"cache"}, {})},
      // FunctionLib
      {
          test::function::XTimesTwo(),
          test::function::RandomUniform(),
      });

  item.fetch.push_back("Sink");

  GraphDef output;
  TF_ASSERT_OK(OptimizeWithMapParallelization(item, &output, true));
  EXPECT_TRUE(graph_utils::ContainsNodeWithOp("ParallelMapDatasetV2", output));
  EXPECT_TRUE(graph_utils::ContainsGraphNodeWithName("map1", output));
  EXPECT_FALSE(graph_utils::ContainsGraphNodeWithName("map2", output));
}

}  // namespace
}  // namespace grappler
}  // namespace tensorflow


text:
package org.apache.shardingsphere.sql.parser.sql.segment.ddl.constraint;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.shardingsphere.sql.parser.sql.segment.ddl.AlterDefinitionSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.ddl.CreateDefinitionSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.sql.parser.sql.segment.generic.table.SimpleTableSegment;

import java.util.Collection;
import java.util.LinkedList;
import java.util.Optional;

/**
 * Constraint definition segment.
 */
@RequiredArgsConstructor
@Getter
@Setter
public final class ConstraintDefinitionSegment implements CreateDefinitionSegment, AlterDefinitionSegment {

    private final int startIndex;

    private final int stopIndex;

    private final Collection<ColumnSegment> primaryKeyColumns = new LinkedList<>();

    private SimpleTableSegment referencedTable;

    /**
     * Get referenced table.
     *
     * @return referenced table
     */
    public Optional<SimpleTableSegment> getReferencedTable() {
        return Optional.ofNullable(referencedTable);
    }
}


text:
__all__  = ["ThreadLocal", "Registry", "WeakValuedRegistry", "SyncDict", "encoded_path", "verify_directory"]

try:
    import thread as _thread
    import threading as _threading
except ImportError:
    import dummy_thread as _thread
    import dummy_threading as _threading

from datetime import datetime, timedelta
import os
import sha
import string
import types
import weakref

try:
    Set = set
except NameError:
    from sets import Set

from beaker.converters import asbool

try:
    from base64 import b64encode, b64decode
except ImportError:
    import binascii

    _translation = [chr(_x) for _x in range(256)]

    # From Python 2.5 base64.py
    def _translate(s, altchars):
        translation = _translation[:]
        for k, v in altchars.items():
            translation[ord(k)] = v
        return s.translate(''.join(translation))

    def b64encode(s, altchars=None):
        """Encode a string using Base64.

        s is the string to encode.  Optional altchars must be a string of at least
        length 2 (additional characters are ignored) which specifies an
        alternative alphabet for the '+' and '/' characters.  This allows an
        application to e.g. generate url or filesystem safe Base64 strings.

        The encoded string is returned.
        """
        # Strip off the trailing newline
        encoded = binascii.b2a_base64(s)[:-1]
        if altchars is not None:
            return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
        return encoded

    def b64decode(s, altchars=None):
        """Decode a Base64 encoded string.

        s is the string to decode.  Optional altchars must be a string of at least
        length 2 (additional characters are ignored) which specifies the
        alternative alphabet used instead of the '+' and '/' characters.

        The decoded string is returned.  A TypeError is raised if s were
        incorrectly padded or if there are non-alphabet characters present in the
        string.
        """
        if altchars is not None:
            s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
        try:
            return binascii.a2b_base64(s)
        except binascii.Error, msg:
            # Transform this exception for consistency
            raise TypeError(msg)

def verify_directory(dir):
    """verifies and creates a directory.  tries to
    ignore collisions with other threads and processes."""

    tries = 0
    while not os.access(dir, os.F_OK):
        try:
            tries += 1
            os.makedirs(dir, 0750)
        except:
            if tries > 5:
                raise

class ThreadLocal(object):
    """stores a value on a per-thread basis"""
    def __init__(self, value = None, default = None, creator = None):
        self.dict = {}
        self.default = default
        self.creator = creator
        if value:
            self.put(value)

    def __call__(self, *arg):
        if len(arg):
            self.put(arg[0])
        else:
            return self.get()

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

    def assign(self, value):
        self.dict[_thread.get_ident()] = value

    def put(self, value):
        self.assign(value)

    def exists(self):
        return self.dict.has_key(_thread.get_ident())

    def get(self, *args, **params):
        if not self.dict.has_key(_thread.get_ident()):
            if self.default is not None:
                self.put(self.default)
            elif self.creator is not None:
                self.put(self.creator(*args, **params))

        return self.dict[_thread.get_ident()]

    def remove(self):
        del self.dict[_thread.get_ident()]

class SyncDict(object):
    """
    an efficient/threadsafe singleton map algorithm, a.k.a.
    "get a value based on this key, and create if not found or not valid" paradigm:

        exists && isvalid ? get : create

    works with weakref dictionaries and the LRUCache to handle items asynchronously
    disappearing from the dictionary.

    use python 2.3.3 or greater !  a major bug was just fixed in Nov. 2003 that
    was driving me nuts with garbage collection/weakrefs in this section.
    """

    def __init__(self, mutex, dictionary):
        self.mutex = mutex
        self.dict = dictionary

    def clear(self):
        self.dict.clear()

    def get(self, key, createfunc, isvalidfunc = None):
        """regular get method.  returns the object asynchronously, if present
        and also passes the optional isvalidfunc,
        else defers to the synchronous get method which will create it."""
        try:
            if self.has_key(key):
                return self._get_obj(key, createfunc, isvalidfunc)
            else:
                return self.sync_get(key, createfunc, isvalidfunc)
        except KeyError:
            return self.sync_get(key, createfunc, isvalidfunc)

    def sync_get(self, key, createfunc, isvalidfunc = None):
        self.mutex.acquire()
        try:
            try:
                if self.has_key(key):
                    return self._get_obj(key, createfunc, isvalidfunc, create = True)
                else:
                    return self._create(key, createfunc)
            except KeyError:
                return self._create(key, createfunc)
        finally:
            self.mutex.release()

    def _get_obj(self, key, createfunc, isvalidfunc, create = False):
        obj = self[key]
        if isvalidfunc is not None and not isvalidfunc(obj):
            if create:
                return self._create(key, createfunc)
            else:
                return self.sync_get(key, createfunc, isvalidfunc)
        else:
            return obj

    def _create(self, key, createfunc):
        obj = createfunc()
        self[key] = obj
        return obj

    def has_key(self, key):
        return self.dict.has_key(key)
    def __contains__(self, key):
        return self.dict.__contains__(key)
    def __getitem__(self, key):
        return self.dict.__getitem__(key)
    def __setitem__(self, key, value):
        self.dict.__setitem__(key, value)
    def __delitem__(self, key):
        return self.dict.__delitem__(key)

class Registry(SyncDict):
    """a registry object."""
    def __init__(self):
        SyncDict.__init__(self, _threading.Lock(), {})

class WeakValuedRegistry(SyncDict):
    """a registry that stores objects only as long as someone has a reference to them."""
    def __init__(self):
        # weakrefs apparently can trigger the __del__ method of other
        # unreferenced objects, when you create a new reference.  this can occur
        # when you place new items into the WeakValueDictionary.  if that __del__
        # method happens to want to access this same registry, well, then you need
        # the RLock instead of a regular lock, since at the point of dictionary
        # insertion, we are already inside the lock.
        SyncDict.__init__(self, _threading.RLock(), weakref.WeakValueDictionary())

def encoded_path(root, identifiers, extension = ".enc", depth = 3, digest = True):
    """generate a unique file-accessible path from the given list of identifiers
    starting at the given root directory."""
    ident = string.join(identifiers, "_")

    if digest:
        ident = sha.new(ident).hexdigest()

    ident = os.path.basename(ident)

    tokens = []
    for d in range(1, depth):
        tokens.append(ident[0:d])

    dir = os.path.join(root, *tokens)
    verify_directory(dir)

    return os.path.join(dir, ident + extension)

def verify_options(opt, types, error):
    if not isinstance(opt, types):
        if not isinstance(types, tuple):
            types = (types,)
        coerced = False
        for typ in types:
            try:
                if typ == bool:
                    typ = asbool
                opt = typ(opt)
                coerced = True
            except:
                pass
            if coerced:
                break
        if not coerced:
            raise Exception(error)
    return opt

def verify_rules(params, ruleset):
    for key, types, message in ruleset:
        if key in params:
            params[key] = verify_options(params[key], types, message)
    return params

def coerce_session_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string referring to a directory."),
        ('lock_dir', (str,), "lock_dir must be a string referring to a directory."),
        ('type', (str, types.NoneType), "Session type must be a string."),
        ('cookie_expires', (bool, datetime, timedelta), "Cookie expires was not a boolean, datetime, or timedelta instance."),
        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a string."),
        ('id', (str,), "Session id must be a string."),
        ('key', (str,), "Session key must be a string."),
        ('secret', (str, types.NoneType), "Session secret must be a string."),
        ('validate_key', (str, types.NoneType), "Session encrypt_key must be a string."),
        ('encrypt_key', (str, types.NoneType), "Session validate_key must be a string."),
        ('secure', (bool, types.NoneType), "Session secure must be a boolean."),
        ('timeout', (int, types.NoneType), "Session timeout must be an integer."),
    ]
    return verify_rules(params, rules)

def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string referring to a directory."),
        ('lock_dir', (str,), "lock_dir must be a string referring to a directory."),
        ('type', (str,), "Session type must be a string."),
    ]
    return verify_rules(params, rules)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="ru" flag="ru" title="Russian">
	 <string_upd name="_bx_cnv_form_entry_input_recipients_err"><![CDATA[Обязательное поле. Пожалуйста, укажите хотя бы одного получателя, которому Вы можете писать.]]></string_upd>
</resources>