text:
'use strict';

const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;

/**
 * Gets a deployments operation.
 *
 * @param {string} deploymentName The name of the deployment.
 *
 * @param {string} operationId The ID of the operation to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperation} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _getAtSubscriptionScope(deploymentName, operationId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') {
      throw new Error('deploymentName cannot be null or undefined and it must be of type string.');
    }
    if (deploymentName !== null && deploymentName !== undefined) {
      if (deploymentName.length > 64)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MaxLength": 64');
      }
      if (deploymentName.length < 1)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MinLength": 1');
      }
      if (deploymentName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (operationId === null || operationId === undefined || typeof operationId.valueOf() !== 'string') {
      throw new Error('operationId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}';
  requestUrl = requestUrl.replace('{deploymentName}', encodeURIComponent(deploymentName));
  requestUrl = requestUrl.replace('{operationId}', encodeURIComponent(operationId));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperation']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets all deployments operations for a deployment.
 *
 * @param {string} deploymentName The name of the deployment with the operation
 * to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {number} [options.top] The number of results to return.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperationsListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listAtSubscriptionScope(deploymentName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let top = (options && options.top !== undefined) ? options.top : undefined;
  // Validate
  try {
    if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') {
      throw new Error('deploymentName cannot be null or undefined and it must be of type string.');
    }
    if (deploymentName !== null && deploymentName !== undefined) {
      if (deploymentName.length > 64)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MaxLength": 64');
      }
      if (deploymentName.length < 1)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MinLength": 1');
      }
      if (deploymentName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations';
  requestUrl = requestUrl.replace('{deploymentName}', encodeURIComponent(deploymentName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperationsListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets a deployments operation.
 *
 * @param {string} resourceGroupName The name of the resource group. The name
 * is case insensitive.
 *
 * @param {string} deploymentName The name of the deployment.
 *
 * @param {string} operationId The ID of the operation to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperation} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _get(resourceGroupName, deploymentName, operationId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
      if (resourceGroupName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') {
      throw new Error('deploymentName cannot be null or undefined and it must be of type string.');
    }
    if (deploymentName !== null && deploymentName !== undefined) {
      if (deploymentName.length > 64)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MaxLength": 64');
      }
      if (deploymentName.length < 1)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MinLength": 1');
      }
      if (deploymentName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (operationId === null || operationId === undefined || typeof operationId.valueOf() !== 'string') {
      throw new Error('operationId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{deploymentName}', encodeURIComponent(deploymentName));
  requestUrl = requestUrl.replace('{operationId}', encodeURIComponent(operationId));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperation']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets all deployments operations for a deployment.
 *
 * @param {string} resourceGroupName The name of the resource group. The name
 * is case insensitive.
 *
 * @param {string} deploymentName The name of the deployment with the operation
 * to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {number} [options.top] The number of results to return.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperationsListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _list(resourceGroupName, deploymentName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let top = (options && options.top !== undefined) ? options.top : undefined;
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
      if (resourceGroupName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') {
      throw new Error('deploymentName cannot be null or undefined and it must be of type string.');
    }
    if (deploymentName !== null && deploymentName !== undefined) {
      if (deploymentName.length > 64)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MaxLength": 64');
      }
      if (deploymentName.length < 1)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "MinLength": 1');
      }
      if (deploymentName.match(/^[-\w\._\(\)]+$/) === null)
      {
        throw new Error('"deploymentName" should satisfy the constraint - "Pattern": /^[-\w\._\(\)]+$/');
      }
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{deploymentName}', encodeURIComponent(deploymentName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperationsListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets all deployments operations for a deployment.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperationsListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listAtSubscriptionScopeNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperationsListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets all deployments operations for a deployment.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link DeploymentOperationsListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['DeploymentOperationsListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/** Class representing a DeploymentOperations. */
class DeploymentOperations {
  /**
   * Create a DeploymentOperations.
   * @param {ResourceManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._getAtSubscriptionScope = _getAtSubscriptionScope;
    this._listAtSubscriptionScope = _listAtSubscriptionScope;
    this._get = _get;
    this._list = _list;
    this._listAtSubscriptionScopeNext = _listAtSubscriptionScopeNext;
    this._listNext = _listNext;
  }

  /**
   * Gets a deployments operation.
   *
   * @param {string} deploymentName The name of the deployment.
   *
   * @param {string} operationId The ID of the operation to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperation>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getAtSubscriptionScopeWithHttpOperationResponse(deploymentName, operationId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getAtSubscriptionScope(deploymentName, operationId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a deployments operation.
   *
   * @param {string} deploymentName The name of the deployment.
   *
   * @param {string} operationId The ID of the operation to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperation} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperation} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  getAtSubscriptionScope(deploymentName, operationId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._getAtSubscriptionScope(deploymentName, operationId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getAtSubscriptionScope(deploymentName, operationId, options, optionalCallback);
    }
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} deploymentName The name of the deployment with the operation
   * to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of results to return.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperationsListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listAtSubscriptionScopeWithHttpOperationResponse(deploymentName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listAtSubscriptionScope(deploymentName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} deploymentName The name of the deployment with the operation
   * to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of results to return.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperationsListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperationsListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listAtSubscriptionScope(deploymentName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listAtSubscriptionScope(deploymentName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listAtSubscriptionScope(deploymentName, options, optionalCallback);
    }
  }

  /**
   * Gets a deployments operation.
   *
   * @param {string} resourceGroupName The name of the resource group. The name
   * is case insensitive.
   *
   * @param {string} deploymentName The name of the deployment.
   *
   * @param {string} operationId The ID of the operation to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperation>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, deploymentName, operationId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, deploymentName, operationId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a deployments operation.
   *
   * @param {string} resourceGroupName The name of the resource group. The name
   * is case insensitive.
   *
   * @param {string} deploymentName The name of the deployment.
   *
   * @param {string} operationId The ID of the operation to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperation} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperation} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  get(resourceGroupName, deploymentName, operationId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._get(resourceGroupName, deploymentName, operationId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, deploymentName, operationId, options, optionalCallback);
    }
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} resourceGroupName The name of the resource group. The name
   * is case insensitive.
   *
   * @param {string} deploymentName The name of the deployment with the operation
   * to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of results to return.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperationsListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listWithHttpOperationResponse(resourceGroupName, deploymentName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._list(resourceGroupName, deploymentName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} resourceGroupName The name of the resource group. The name
   * is case insensitive.
   *
   * @param {string} deploymentName The name of the deployment with the operation
   * to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of results to return.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperationsListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperationsListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  list(resourceGroupName, deploymentName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._list(resourceGroupName, deploymentName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._list(resourceGroupName, deploymentName, options, optionalCallback);
    }
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperationsListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listAtSubscriptionScopeNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listAtSubscriptionScopeNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperationsListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperationsListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listAtSubscriptionScopeNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listAtSubscriptionScopeNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listAtSubscriptionScopeNext(nextPageLink, options, optionalCallback);
    }
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<DeploymentOperationsListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets all deployments operations for a deployment.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {DeploymentOperationsListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link DeploymentOperationsListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = DeploymentOperations;


text:
<?xml version="1.0" ?>
<doc>
	<str name="Patent Number">
		US7744754
	</str>
	<str name="Application Number">
		US12067121
	</str>
	<str name="Kind Code">
		B2
	</str>
	<str name="Title">
		Plant for wastewater treatment
	</str>
	<str name="Abstract">
		A plant for wastewater treatment is provided by an exemplary embodiment of the present invention. The plant for wastewater treatment includes a reactor into which wastewater and air flow into and depart from; multi-layer sludge separating portions, wherein pollutants in wastewater can be decomposed by increasing an amount of dissolved oxygen because upward moving time of intruded wastewater and air bubbles can be increased by including a reactor divided into upper and lower sides, and fluidity of wastewater may be improved by forming a residential space; and carriers located between the sludge separating portions and including a large amount of microbes, wherein wastewater treatment is performed by a biological reaction caused by contact between the carriers and wastewater.
	</str>
	<str name="Document Types">
		US | USB
	</str>
	<str name="Application Date">
		2006-09-14
	</str>
	<str name="Application Year">
		2006
	</str>
	<str name="Application(Year/Month)">
		2006-09
	</str>
	<str name="Publication Date">
		2010-06-29
	</str>
	<str name="Publication Year">
		2010
	</str>
	<str name="Publication(Year/Month)">
		2010-06
	</str>
	<str name="All IPC">
		C02F3/06
	</str>
	<str name="IPC Primary">
		C02F3/06
	</str>
	<str name="IPC Section">
		C
	</str>
	<str name="IPC Class">
		C02
	</str>
	<str name="IPC Subclass">
		C02F
	</str>
	<str name="IPC Group">
		C02F3
	</str>
	<str name="All UPC">
		210/150 | 210/188 | 210/615
	</str>
	<str name="UPC Primary">
		210/150
	</str>
	<str name="UPC Class">
		210
	</str>
	<str name="Family Member Count">
		0
	</str>
	<str name="Family Members Cited By Count">
		0
	</str>
	<str name="Other References Count">
		0
	</str>
	<str name="Cited By Count">
		0
	</str>
	<str name="Cites">
		US5718823 | US4618418 | US20080264840 | US5399266 | US4931401 | US6682653 | US5019268 | US5972212 | US6478963 | US5298164 | US7410570 | US20070289921 | US4422930 | US6808631 | US5833857 | KR020040064579 | KR019990046806 | JP1998118473
	</str>
	<str name="Cites Count">
		18
	</str>
	<str name="Priority Country">
		KR
	</str>
	<str name="Priority Number">
		1020050086725
	</str>
	<str name="Priority Date">
		2005-09-16
	</str>
	<str name="Assignee(s)">
		ECODAYS CO., LTD.
	</str>
	<str name="1st Assignee">
		ECODAYS CO., LTD.
	</str>
	<str name="Number of Assignees">
		1
	</str>
	<str name="1st Assignee Address">
		Nowon-gu, Seoul, KR
	</str>
	<str name="Assignee(s) Address">
		Nowon-gu, Seoul, KR
	</str>
	<str name="Inventor(s)">
		CHOI, HONG-BOK | LEE, JAE-KI | PARK, JU-HYUNG | CHOI, EUN-JU | KIM, JUNG-RAE
	</str>
	<str name="1st Inventor">
		CHOI, HONG-BOK
	</str>
	<str name="Number of Inventors">
		5
	</str>
	<str name="1st Inventor Address">
		Seoul, KR
	</str>
	<str name="Inventor(s) Address">
		Seoul, KR | Seoul, KR | Seoul, KR | Seoul, KR | Seoul, KR
	</str>
	<str name="Primary Examiner">
		UPTON, CHRISTOPHER
	</str>
	<str name="cited by within 3 years">
		0
	</str>
	<str name="cited by within 5 years">
		0
	</str>
</doc>

redpajama_set_name: RedPajamaGithub


text:
package external

import (
	"testing"

	uuid "github.com/gofrs/uuid"
	"github.com/stretchr/testify/require"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"

	pb "github.com/brocaar/lora-app-server/api"
	"github.com/brocaar/lora-app-server/internal/backend/networkserver"
	"github.com/brocaar/lora-app-server/internal/backend/networkserver/mock"
	"github.com/brocaar/lora-app-server/internal/storage"
	"github.com/brocaar/loraserver/api/ns"
)

func (ts *APITestSuite) TestDeviceProfile() {
	assert := require.New(ts.T())

	nsClient := mock.NewClient()
	networkserver.SetPool(mock.NewPool(nsClient))

	validator := &TestValidator{}
	api := NewDeviceProfileServiceAPI(validator)

	n := storage.NetworkServer{
		Name:   "test",
		Server: "test:1234",
	}
	assert.NoError(storage.CreateNetworkServer(context.Background(), storage.DB(), &n))

	org := storage.Organization{
		Name: "test-org",
	}
	assert.NoError(storage.CreateOrganization(context.Background(), storage.DB(), &org))

	ts.T().Run("Create", func(t *testing.T) {
		assert := require.New(t)

		createReq := pb.CreateDeviceProfileRequest{
			DeviceProfile: &pb.DeviceProfile{
				Name:                 "test-dp",
				OrganizationId:       org.ID,
				NetworkServerId:      n.ID,
				SupportsClassB:       true,
				ClassBTimeout:        10,
				PingSlotPeriod:       20,
				PingSlotDr:           5,
				PingSlotFreq:         868100000,
				SupportsClassC:       true,
				ClassCTimeout:        30,
				MacVersion:           "1.0.2",
				RegParamsRevision:    "B",
				RxDelay_1:            1,
				RxDrOffset_1:         1,
				RxDatarate_2:         6,
				RxFreq_2:             868300000,
				FactoryPresetFreqs:   []uint32{868100000, 868300000, 868500000},
				MaxEirp:              14,
				MaxDutyCycle:         10,
				SupportsJoin:         true,
				RfRegion:             "EU868",
				Supports_32BitFCnt:   true,
				PayloadCodec:         "CUSTOM_JS",
				PayloadEncoderScript: "Encode() {}",
				PayloadDecoderScript: "Decode() {}",
				GeolocBufferTtl:      60,
				GeolocMinBufferSize:  3,
			},
		}

		createResp, err := api.Create(context.Background(), &createReq)
		assert.NoError(err)

		assert.NotEqual("", createResp.Id)
		assert.NotEqual(uuid.Nil.String(), "")

		// set network-server mock
		nsCreate := <-nsClient.CreateDeviceProfileChan
		nsClient.GetDeviceProfileResponse = ns.GetDeviceProfileResponse{
			DeviceProfile: nsCreate.DeviceProfile,
		}

		t.Run("Get", func(t *testing.T) {
			assert := require.New(t)

			getResp, err := api.Get(context.Background(), &pb.GetDeviceProfileRequest{
				Id: createResp.Id,
			})
			assert.NoError(err)

			createReq.DeviceProfile.Id = createResp.Id
			assert.Equal(createReq.DeviceProfile, getResp.DeviceProfile)
		})

		t.Run("Update", func(t *testing.T) {
			assert := require.New(t)
			updateReq := pb.UpdateDeviceProfileRequest{
				DeviceProfile: &pb.DeviceProfile{
					Id:                  createResp.Id,
					OrganizationId:      org.ID,
					NetworkServerId:     n.ID,
					Name:                "updated-dp",
					SupportsClassB:      true,
					ClassBTimeout:       20,
					PingSlotPeriod:      30,
					PingSlotDr:          4,
					PingSlotFreq:        868300000,
					SupportsClassC:      true,
					ClassCTimeout:       20,
					MacVersion:          "1.1.0",
					RegParamsRevision:   "C",
					RxDelay_1:           2,
					RxDrOffset_1:        3,
					RxDatarate_2:        5,
					RxFreq_2:            868500000,
					FactoryPresetFreqs:  []uint32{868100000, 868300000, 868500000, 868700000},
					MaxEirp:             17,
					MaxDutyCycle:        1,
					SupportsJoin:        true,
					RfRegion:            "EU868",
					Supports_32BitFCnt:  true,
					GeolocBufferTtl:     120,
					GeolocMinBufferSize: 6,
				},
			}

			_, err := api.Update(context.Background(), &updateReq)
			assert.NoError(err)

			nsUpdate := <-nsClient.UpdateDeviceProfileChan
			nsClient.GetDeviceProfileResponse = ns.GetDeviceProfileResponse{
				DeviceProfile: nsUpdate.DeviceProfile,
			}

			getResp, err := api.Get(context.Background(), &pb.GetDeviceProfileRequest{
				Id: createResp.Id,
			})
			assert.NoError(err)
			assert.Equal(updateReq.DeviceProfile, getResp.DeviceProfile)
		})

		t.Run("Global admin user", func(t *testing.T) {
			validator.returnIsAdmin = true

			t.Run("List", func(t *testing.T) {
				assert := require.New(t)
				listResp, err := api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit: 10,
				})
				assert.NoError(err)
				assert.EqualValues(1, listResp.TotalCount)
				assert.Len(listResp.Result, 1)
			})

			t.Run("List with org id", func(t *testing.T) {
				assert := require.New(t)

				listResp, err := api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit:          10,
					OrganizationId: org.ID,
				})
				assert.NoError(err)
				assert.EqualValues(1, listResp.TotalCount)
				assert.Len(listResp.Result, 1)

				listResp, err = api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit:          10,
					OrganizationId: org.ID + 1,
				})
				assert.NoError(err)
				assert.EqualValues(0, listResp.TotalCount)
				assert.Len(listResp.Result, 0)
			})

			t.Run("List with app id", func(t *testing.T) {
				// we test here that only the device-profiles that are indirectly
				// linked through the application service-profile are returned

				assert := require.New(t)

				n2 := storage.NetworkServer{
					Name:   "ns-server-2",
					Server: "ns-server-2:1234",
				}
				assert.NoError(storage.CreateNetworkServer(context.Background(), storage.DB(), &n2))

				sp1 := storage.ServiceProfile{
					Name:            "test-sp",
					NetworkServerID: n.ID,
					OrganizationID:  org.ID,
				}
				assert.NoError(storage.CreateServiceProfile(context.Background(), storage.DB(), &sp1))
				sp1ID, err := uuid.FromBytes(sp1.ServiceProfile.Id)
				assert.NoError(err)

				sp2 := storage.ServiceProfile{
					Name:            "test-sp-2",
					NetworkServerID: n2.ID,
					OrganizationID:  org.ID,
				}
				assert.NoError(storage.CreateServiceProfile(context.Background(), storage.DB(), &sp2))
				sp2ID, err := uuid.FromBytes(sp2.ServiceProfile.Id)
				assert.NoError(err)

				app1 := storage.Application{
					Name:             "test-app",
					Description:      "test app",
					OrganizationID:   org.ID,
					ServiceProfileID: sp1ID,
				}
				assert.NoError(storage.CreateApplication(context.Background(), storage.DB(), &app1))

				app2 := storage.Application{
					Name:             "test-app-2",
					Description:      "test app 2",
					OrganizationID:   org.ID,
					ServiceProfileID: sp2ID,
				}
				assert.NoError(storage.CreateApplication(context.Background(), storage.DB(), &app2))

				listResp, err := api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit:         10,
					ApplicationId: app1.ID,
				})
				assert.NoError(err)
				assert.EqualValues(1, listResp.TotalCount)
				assert.Len(listResp.Result, 1)
				assert.Equal(createResp.Id, listResp.Result[0].Id)

				listResp, err = api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit:         10,
					ApplicationId: app2.ID,
				})
				assert.NoError(err)
				assert.EqualValues(0, listResp.TotalCount)
				assert.Len(listResp.Result, 0)
			})
		})

		t.Run("Organization user", func(t *testing.T) {
			assert := require.New(t)

			userID, err := storage.CreateUser(context.Background(), storage.DB(), &storage.User{
				Username: "testuser",
				IsActive: true,
				Email:    "foo@bar.com",
			}, "testpassword")
			assert.NoError(err)

			assert.NoError(storage.CreateOrganizationUser(context.Background(), storage.DB(), org.ID, userID, false, false, false))

			t.Run("List without org id returns all device-profiles for user", func(t *testing.T) {
				assert := require.New(t)

				validator.returnIsAdmin = false
				validator.returnUsername = "testuser"

				listResp, err := api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit: 10,
				})
				assert.NoError(err)
				assert.EqualValues(1, listResp.TotalCount)
				assert.Len(listResp.Result, 1)
			})

			t.Run("List with different user", func(t *testing.T) {
				assert := require.New(t)

				validator.returnIsAdmin = false
				validator.returnUsername = "differentuser"

				listResp, err := api.List(context.Background(), &pb.ListDeviceProfileRequest{
					Limit: 10,
				})
				assert.NoError(err)
				assert.EqualValues(0, listResp.TotalCount)
				assert.Len(listResp.Result, 0)
			})
		})

		t.Run("Delete", func(t *testing.T) {
			assert := require.New(t)

			_, err := api.Delete(context.Background(), &pb.DeleteDeviceProfileRequest{
				Id: createResp.Id,
			})
			assert.NoError(err)

			_, err = api.Get(context.Background(), &pb.GetDeviceProfileRequest{
				Id: createResp.Id,
			})
			assert.NotNil(err)
			assert.Equal(codes.NotFound, grpc.Code(err))
		})
	})
}


text:
import shutil
import xodb
from datetime import datetime, date

from xodb import (
    Array,
    Date,
    DateTime,
    Dict,
    Integer,
    List,
    Location,
    Schema,
    String,
    Text,
    )

class Person(object):

    def __init__(self, name, last, job,
                 hired, clocked,
                 salary, rank,
                 description, cualificaciones, kw,
                 friends, properties, location):
        self.name = name
        self.last = last
        self.job = job
        self.hired = hired
        self.clocked = clocked
        self.salary = salary
        self.rank = rank
        self.description = description
        self.cualificaciones = cualificaciones
        self.kw = kw
        self.friends = friends
        self.properties = properties
        self.location = location

class PersonSchema(Schema):

    language = String.using(default="en")

    last = String.using(prefix=False)
    name = String.using(sortable=True, facet=True, wdf_inc=2)
    job = String.using(sortable=True, boolean=True)
    department = String.using(facet=True)

    hired = Date.using(sortable=True)
    clocked = DateTime.using(sortable=True)

    salary = Integer.named('salary')
    rank = Integer.using(sortable=True)
    nothing = Integer.using(facet=True, optional=True)
    nostore = Integer.using(optional=True, store=False)

    description = Text.using(prefix=False)
    cualificaciones = Text.using(language="es")

    keywords = Array.of(String)

    @keywords.property
    def _(self, obj, element):
        return obj.kw.split()

    def j_man(self, obj, element):
        return obj.friends + ['jesus']
    friends = List.of(String).using(getter=j_man)

    properties = Dict.of(
        String.using(name='status'),
        Integer.named('shoe_size'),
        )

    location = Location.named('location')

class Department(object):

    def __init__(self, name, employees):
        self.name = name
        self.employees = employees

class DepartmentSchema(Schema):

    language = String.using(default="en")
    name = String.using(facet=True)
    employees = Array.of(String).using(facet=True)

db = None

def setup():
    global db
    db = xodb.temp()
    db.map(Person, PersonSchema)
    db.map(Department, DepartmentSchema)

    joe = Person(name=u'joe', last=u'bob', job='cake inspector',
                 salary=4500, rank=2, hired=date(1999, 9, 9),
                 clocked=datetime(2010, 10, 10, 10, 10),
                 description="I am the eggmans walking",
                 cualificaciones=u"páseador de perros",
                 kw='one two walking shoes',
                 friends=['rick', 'roll'],
                 properties=dict(status='annoying', shoe_size=3),
                 location=(7.0625, -95.677068),
                 )
    joe.nothing = None

    jane = Person(name=u'jane', last=u'bob', job='steak inspector',
                  salary=5600, rank=100, hired=date(2000, 9, 9),
                  clocked=datetime(2011, 11, 11, 11, 11),
                  description="I am the womans modernize",
                  cualificaciones="Devorador des pasteles fritos",
                  kw='three four busting rhymes',
                  friends=['alice', 'aligator'],
                  properties=dict(status='pleasant', shoe_size=99),
                  location=(51.500152, -0.126236),
                  )

    department = Department('housing',
                                 employees=[joe.name,
                                            jane.name])
    department2 = Department('joe',
                                  employees=[joe.name])

    joe.department = department2.name
    jane.department = department.name

    db.add(joe, jane, department, department2)

def teardown():
    if db.db_path:
        shutil.rmtree(db.db_path)

def assert_one(query, name, result, **kw):
    l = list(db.query(query, **kw))
    assert len(l) == 1
    assert getattr(l[0], name) == result

def test_empty_query():
    assert len(list(db.query(''))) == 4

def test_count():
    assert db.count() == len(db) == 4
    assert db.count("bob") == 2
    assert db.count("name:joe") == 2
    assert db.count("name:jane") == 1
    assert db.count("employees:joe") == 2
    assert db.count("employees:jane") == 1
    assert db.count("name:joe OR name:jane") == 3

def test_describe_query():
    assert db.describe_query('foo') == 'Xapian::Query(foo:(pos=1))'

def test_string():
    assert_one("name:jane", 'name', u'jane')
    assert db.count("bob") == 2
    assert db.count("last:jug") == 0
    assert db.count('job:"cake inspector"') == 1
    assert db.count('job:cake') == 0
    assert db.count('job:inspector') == 0
    assert db.count('job:"steak inspector"') == 1

    assert ([t.job for t in
             db.query("bob", order="job")] ==
            ['cake inspector', 'steak inspector'])

    assert ([t.job for t in
             db.query("bob", order="job", reverse=True)] ==
            ['steak inspector', 'cake inspector'])

def test_wdf():
    # this is kind of a low level test, but should hold for all future iterations of wdf algorithm
    assert db.query('name:joe')
    assert ([[(t.term, t.wdf) for t in d._xodb_document.termlist()] for d in db.query('name:joe')] ==
            [[('XCLOCKED:20101010', 1),
              ('XCUALIFICACIONES:de', 1),
              ('XCUALIFICACIONES:paseador', 1),
              ('XCUALIFICACIONES:perros', 1),
              ('XDEPARTMENT:joe', 1),
              ('XFACET:department', 1),
              ('XFACET:name', 1),
              ('XFRIENDS_0:rick', 1),
              ('XFRIENDS_1:roll', 1),
              ('XFRIENDS_2:jesus', 1),
              ('XHIRED:19990909', 1),
              ('XJOB:cake inspector', 1),
              ('XKEYWORDS:one', 1),
              ('XKEYWORDS:shoes', 1),
              ('XKEYWORDS:two', 1),
              ('XKEYWORDS:walking', 1),
              ('XLANGUAGE:en', 1),
              ('XNAME:joe', 2),
              ('XPROPERTIES_SHOE_SIZE:3', 1),
              ('XPROPERTIES_STATUS:annoying', 1),
              ('XRANK:2', 1),
              ('XSALARY:4500', 1),
              ('X_:one', 1),
              ('X_:shoes', 1),
              ('X_:two', 1),
              ('X_:walking', 1),
              ('ZXCUALIFICACIONES:paseador', 1),
              ('ZXCUALIFICACIONES:perr', 1),
              ('Zeggman', 1),
              ('Zwalk', 1),
              ('am', 1),
              ('bob', 1),
              ('eggmans', 1),
              ('i', 1),
              ('loc_watttatcttttgctacgaagt', 1),
              ('the', 1),
              ('walking', 1)],
             # this is the department
             [('XEMPLOYEES:joe', 1),
              ('XFACET:employees', 1),
              ('XFACET:name', 1),
              ('XLANGUAGE:en', 1),
              ('XNAME:joe', 1)]])

def test_integer():
    assert_one("salary:4500", 'salary', 4500)
    assert_one("salary:4500", 'name', u'joe')
    assert_one("salary:5600", 'salary', 5600)
    assert_one("salary:5600", 'name', u'jane')

    assert db.count("salary:0") == 0
    assert db.count("salary:1") == 0

    assert db.count("rank:0..1") == 0
    assert db.count("rank:1..99") == 1
    assert db.count("rank:1..101") == 2
    assert db.count("rank:99..101") == 1
    assert db.count("rank:..101") == 2
    assert db.count("rank:99..") == 1
    assert db.count("rank:102..200") == 0

    assert ([t.rank for t in
             db.query("bob", order="rank")] ==
            [2, 100])

    assert ([t.rank for t in
             db.query("bob", order="rank", reverse=True)] ==
            [100, 2])

def test_date():
    assert_one("hired:19990909", 'hired', date(1999, 9, 9))
    assert_one("hired:19990909", 'name', u'joe')
    assert_one("hired:20000909", 'hired', date(2000, 9, 9))
    assert_one("hired:20000909", 'name', u'jane')

    assert ([t.hired for t in
             db.query("bob", order="hired")] ==
            [date(1999, 9, 9), date(2000, 9, 9)])

    assert ([t.hired for t in
             db.query("bob", order="hired", reverse=True)] ==
            [date(2000, 9, 9), date(1999, 9, 9)])

def test_datetime():
    assert_one("clocked:20101010", 'clocked',
                    datetime(2010, 10, 10, 10, 10))
    assert_one("clocked:20101010", 'name', u'joe')
    assert_one("clocked:20111111", 'clocked',
                    datetime(2011, 11, 11, 11, 11))
    assert_one("clocked:20111111", 'name', u'jane')

    assert_one("clocked:20101009..20101010", 'name', u'joe')
    assert_one("clocked:20111111..20111112", 'name', u'jane')

    assert ([t.clocked for t in
             db.query("bob", order="clocked")] ==
            [datetime(2010, 10, 10, 10, 10),
             datetime(2011, 11, 11, 11, 11)])

    assert ([t.clocked for t in
             db.query("bob", order="clocked", reverse=True)] ==
            [datetime(2011, 11, 11, 11, 11),
             datetime(2010, 10, 10, 10, 10)])

def test_text():
    assert_one("eggman", 'name', u'joe', language="en")
    assert_one("woman", 'name', u'jane', language="en")
    assert_one("eggmans", 'name', u'joe', language="en")
    assert_one("womans", 'name', u'jane', language="en")
    assert_one("walk", 'name', u'joe', language="en")
    assert_one("modern", 'name', u'jane', language="en")

    assert_one("cualificaciones:paseador",
                    'name', u'joe', language="es")
    assert_one("cualificaciones:paseador",
               'cualificaciones', u'páseador de perros',
               language="es")
    assert_one("cualificaciones:devorador",
                    'name', u'jane', language="es")
    assert_one("cualificaciones:devor",
                    'name', u'jane', language="es")
    assert_one("cualificaciones:perro",
                    'name', u'joe', language="es")
    assert_one("cualificaciones:frito",
                    'name', u'jane', language="es")

def test_array():
    assert_one("keywords:one", 'name', u'joe')
    assert_one("keywords:three", 'name', u'jane')

def test_list():
    assert_one("friends_0:rick", 'name', u'joe')
    assert_one("friends_1:aligator", 'name', u'jane')
    l = [t.name for t in
         db.query("friends_2:jesus", order="rank")]
    assert l == [u'joe', u'jane']

def test_dict():
    assert_one("properties_status:annoying", 'name', u'joe')
    assert_one("properties_shoe_size:99", 'name', u'jane')
    assert_one("properties_shoe_size:99", 'properties',
                    dict(status='pleasant', shoe_size=99))

def test_location():
    assert_one("loc_watttatcttttgctacgaagt", 'name', u'joe')
    assert_one("loc_wattt*", 'name', u'joe')
    assert_one("loc_wccttcttcttacaacgagagt'", 'name', u'jane')
    assert_one("loc_wcctt**", 'name', u'jane')
    l = [t.name for t in
         db.query("loc_w*", order="rank")]
    assert l == [u'joe', u'jane']

def test_suggest():
    assert (set(db.suggest('bob')) ==
            set([u'walking', u'eggmans', u'modernize', u'womans']))

    assert (set(db.suggest('bob', prefix='name')) ==
            set([u'name:joe', u'name:jane']))

    assert (set(db.suggest('bob', prefix='department')) ==
            set([u'department:housing', u'department:joe']))

    assert (set(db.suggest('name:joe', prefix='department')) ==
            set([u'department:joe']))

    assert (set(db.suggest('name:jane', prefix='department')) ==
            set([u'department:housing']))

    assert (set(db.suggest('name:jane', prefix='department')) ==
            set([u'department:housing']))

def test_facet():
    assert (db.facet('name:housing') ==
            {u'facet:employees': 1, u'facet:name': 1})

    assert (db.facet('name:housing OR name:jane') ==
            {u'facet:employees': 1,
             u'facet:department': 1,
             u'facet:name': 2})

    assert not db.facet('name:housing AND name:jane')

    assert (db.facet('name:joe') ==
            {u'facet:employees': 1,
             u'facet:department': 1,
             u'facet:name': 2})

    assert (db.facet('name:jane') ==
            {u'facet:department': 1, u'facet:name': 1})

    assert (db.facet('name:jane OR name:joe') ==
            {u'facet:department': 2,
             u'facet:name': 3,
             u'facet:employees': 1})

    assert not db.facet('name:jane AND name:joe')

    assert not db.count('facet:nothing')

    assert (db.facet('employees:jane') ==
            {u'facet:employees': 1, u'facet:name': 1})

    assert (db.facet('employees:joe') ==
            {u'facet:employees': 2, u'facet:name': 2})

    assert (db.facet('employees:joe OR employees:jane') ==
            {u'facet:employees': 2, u'facet:name': 2})

    assert (db.facet('employees:joe AND employees:jane') ==
            {u'facet:employees': 1, u'facet:name': 1})

    assert not db.facet('employees:joe AND name:jane')

def test_metadata():
    l = list(db.query('friends_2:jesus'))
    assert len(l) == 2
    assert l[0]._xodb_document
    assert l[1]._xodb_document

    assert l[0]._xodb_percent == 100
    assert l[1]._xodb_percent == 100
    assert l[0]._xodb_rank == 0
    assert l[1]._xodb_rank == 1
    assert l[0]._xodb_weight == 0.0
    assert l[1]._xodb_weight == 0.0

    l = list(db.query('the'))
    assert len(l) == 2
    assert l[0]._xodb_percent == 100
    assert l[1]._xodb_percent == 97
    assert l[0]._xodb_rank == 0
    assert l[1]._xodb_rank == 1
    assert l[0]._xodb_weight > l[1]._xodb_weight


text:
<?php

namespace Extension;

use PHPUnit\Framework\TestCase;
use Test\Compare;

class CompareTest extends TestCase
{
    public function testLess()
    {
        $t = new Compare();

        $this->assertTrue($t->isLessInt(1, 2));
        $this->assertTrue($t->isLessDouble(1.1, 1.2));
        $this->assertFalse($t->isLessInt(20, 10));
    }

    public function testGreaterEqual()
    {
        $t = new Compare();

        $this->assertTrue($t->isGreaterEqual(3, 2));
        $this->assertTrue($t->isGreaterEqual(2, 2));
        $this->assertFalse($t->isGreaterEqual(1, 2));
    }

    public function testConst()
    {
        $t = new Compare();

        $this->assertTrue($t->isLessThenPi(3.12));
        $this->assertTrue($t->isMoreThenPi(3.15));
    }

    public function testVarWithStringEquals()
    {
        $t = new Compare();

        $this->assertSame('NOK', $t->testVarWithStringEquals('wrong testing'));
        $this->assertSame('NOK', $t->testVarWithStringEquals('another testing'));
        $this->assertSame('OK', $t->testVarWithStringEquals('testing'));
        $this->assertSame('NOK', $t->testVarWithStringEquals('testing nok'));
    }

    public function testEquals()
    {
        $t = new Compare();

        $this->assertTrue($t->testVarEqualsNull(null));
        $this->assertFalse($t->testVarEqualsNull(1));

        $this->assertTrue($t->testNullEqualsVar(null));
        $this->assertFalse($t->testNullEqualsVar(1));
    }

    public function testNotEquals()
    {
        $t = new Compare();

        $this->assertTrue($t->testNotIdenticalZeroVar());
        $this->assertTrue($t->testNotIdenticalZeroInt());
        $this->assertTrue($t->testNotIdenticalZeroLong());
    }
}