text:
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;

namespace Google.Cloud.ArtifactRegistry.V1.Tests
{
    /// <summary>Generated unit tests.</summary>
    public sealed class GeneratedArtifactRegistryClientTest
    {
        [xunit::FactAttribute]
        public void GetRepositoryRequestObject()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository response = client.GetRepository(request);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetRepositoryRequestObjectAsync()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository responseCallSettings = await client.GetRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Repository responseCancellationToken = await client.GetRepositoryAsync(request, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public void GetRepository()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository response = client.GetRepository(request.Name);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetRepositoryAsync()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository responseCallSettings = await client.GetRepositoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Repository responseCancellationToken = await client.GetRepositoryAsync(request.Name, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public void GetRepositoryResourceNames()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository response = client.GetRepository(request.RepositoryName);
            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }

        [xunit::FactAttribute]
        public async stt::Task GetRepositoryResourceNamesAsync()
        {
            moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
            GetRepositoryRequest request = new GetRepositoryRequest
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
            };
            Repository expectedResponse = new Repository
            {
                RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
                Format = Repository.Types.Format.Yum,
                Description = "description2cf9da67",
                Labels =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                CreateTime = new wkt::Timestamp(),
                UpdateTime = new wkt::Timestamp(),
                KmsKeyName = "kms_key_name06bd122b",
            };
            mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
            Repository responseCallSettings = await client.GetRepositoryAsync(request.RepositoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
            xunit::Assert.Same(expectedResponse, responseCallSettings);
            Repository responseCancellationToken = await client.GetRepositoryAsync(request.RepositoryName, st::CancellationToken.None);
            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
    }
}


text:
/**
 * The DataSource utility provides a common configurable interface for widgets
 * to access a variety of data, from JavaScript arrays to online servers over
 * XHR.
 *
 * @namespace YAHOO.util
 * @module datasource
 * @requires yahoo, event
 * @optional connection
 * @title DataSource Utility
 * @beta
 */

/****************************************************************************/
/****************************************************************************/
/****************************************************************************/

/**
 * The DataSource class defines and manages a live set of data for widgets to
 * interact with. Examples of live databases include in-memory
 * local data such as a JavaScript array, a JavaScript function, or JSON, or
 * remote data such as data retrieved through an XHR connection.
 *
 * @class DataSource
 * @uses YAHOO.util.EventProvider
 * @constructor
 * @param oLiveData {Object} Pointer to live database.
 * @param oConfigs {Object} (optional) Object literal of configuration values.
 */
YAHOO.util.DataSource = function(oLiveData, oConfigs) {
    // Set any config params passed in to override defaults
    if(oConfigs && (oConfigs.constructor == Object)) {
        for(var sConfig in oConfigs) {
            if(sConfig) {
                this[sConfig] = oConfigs[sConfig];
            }
        }
    }

    if(!oLiveData) {
        return;
    }

    if(oLiveData.nodeType && oLiveData.nodeType == 9) {
        this.dataType = YAHOO.util.DataSource.TYPE_XML;
    }
    else if(YAHOO.lang.isArray(oLiveData)) {
        this.dataType = YAHOO.util.DataSource.TYPE_JSARRAY;
    }
    else if(YAHOO.lang.isString(oLiveData)) {
        this.dataType = YAHOO.util.DataSource.TYPE_XHR;
    }
    else if(YAHOO.lang.isFunction(oLiveData)) {
        this.dataType = YAHOO.util.DataSource.TYPE_JSFUNCTION;
    }
    else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) {
        this.dataType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
    }
    else if(YAHOO.lang.isObject(oLiveData)) {
        this.dataType = YAHOO.util.DataSource.TYPE_JSON;
    }
    else {
        this.dataType = YAHOO.util.DataSource.TYPE_UNKNOWN;
    }

    this.liveData = oLiveData;
    this._oQueue = {interval:null, conn:null, requests:[]};

    // Validate and initialize public configs
    var maxCacheEntries = this.maxCacheEntries;
    if(!YAHOO.lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
        maxCacheEntries = 0;
    }

    // Initialize local cache
    if(maxCacheEntries > 0 && !this._aCache) {
        this._aCache = [];
    }

    this._sName = "DataSource instance" + YAHOO.util.DataSource._nIndex;
    YAHOO.util.DataSource._nIndex++;

    /////////////////////////////////////////////////////////////////////////////
    //
    // Custom Events
    //
    /////////////////////////////////////////////////////////////////////////////

    /**
     * Fired when a request is made to the local cache.
     *
     * @event cacheRequestEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     */
    this.createEvent("cacheRequestEvent");

    /**
     * Fired when data is retrieved from the local cache.
     *
     * @event getCachedResponseEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.response {Object} The response object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     * @param oArgs.tId {Number} Transaction ID.
     */
    this.createEvent("cacheResponseEvent");

    /**
     * Fired when a request is sent to the live data source.
     *
     * @event requestEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     */
    this.createEvent("requestEvent");

    /**
     * Fired when live data source sends response.
     *
     * @event responseEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.response {Object} The raw response object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     */
    this.createEvent("responseEvent");

    /**
     * Fired when response is parsed.
     *
     * @event responseParseEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.response {Object} The parsed response object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     */
    this.createEvent("responseParseEvent");

    /**
     * Fired when response is cached.
     *
     * @event responseCacheEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.response {Object} The parsed response object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     */
    this.createEvent("responseCacheEvent");
    /**
     * Fired when an error is encountered with the live data source.
     *
     * @event dataErrorEvent
     * @param oArgs.request {Object} The request object.
     * @param oArgs.callback {Function} The callback function.
     * @param oArgs.caller {Object} The parent object of the callback function.
     * @param oArgs.message {String} The error message.
     */
    this.createEvent("dataErrorEvent");

    /**
     * Fired when the local cache is flushed.
     *
     * @event cacheFlushEvent
     */
    this.createEvent("cacheFlushEvent");
};

YAHOO.augment(YAHOO.util.DataSource, YAHOO.util.EventProvider);

/////////////////////////////////////////////////////////////////////////////
//
// Public constants
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Type is unknown.
 *
 * @property TYPE_UNKNOWN
 * @type Number
 * @final
 * @default -1
 */
YAHOO.util.DataSource.TYPE_UNKNOWN = -1;

/**
 * Type is a JavaScript Array.
 *
 * @property TYPE_JSARRAY
 * @type Number
 * @final
 * @default 0
 */
YAHOO.util.DataSource.TYPE_JSARRAY = 0;

/**
 * Type is a JavaScript Function.
 *
 * @property TYPE_JSFUNCTION
 * @type Number
 * @final
 * @default 1
 */
YAHOO.util.DataSource.TYPE_JSFUNCTION = 1;

/**
 * Type is hosted on a server via an XHR connection.
 *
 * @property TYPE_XHR
 * @type Number
 * @final
 * @default 2
 */
YAHOO.util.DataSource.TYPE_XHR = 2;

/**
 * Type is JSON.
 *
 * @property TYPE_JSON
 * @type Number
 * @final
 * @default 3
 */
YAHOO.util.DataSource.TYPE_JSON = 3;

/**
 * Type is XML.
 *
 * @property TYPE_XML
 * @type Number
 * @final
 * @default 4
 */
YAHOO.util.DataSource.TYPE_XML = 4;

/**
 * Type is plain text.
 *
 * @property TYPE_TEXT
 * @type Number
 * @final
 * @default 5
 */
YAHOO.util.DataSource.TYPE_TEXT = 5;

/**
 * Type is an HTML TABLE element.
 *
 * @property TYPE_HTMLTABLE
 * @type Number
 * @final
 * @default 6
 */
YAHOO.util.DataSource.TYPE_HTMLTABLE = 6;

/**
 * Error message for invalid dataresponses.
 *
 * @property ERROR_DATAINVALID
 * @type String
 * @final
 * @default "Invalid data"
 */
YAHOO.util.DataSource.ERROR_DATAINVALID = "Invalid data";

/**
 * Error message for null data responses.
 *
 * @property ERROR_DATANULL
 * @type String
 * @final
 * @default "Null data"
 */
YAHOO.util.DataSource.ERROR_DATANULL = "Null data";

/////////////////////////////////////////////////////////////////////////////
//
// Private variables
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Internal class variable to index multiple DataSource instances.
 *
 * @property DataSource._nIndex
 * @type Number
 * @private
 * @static
 */
YAHOO.util.DataSource._nIndex = 0;

/**
 * Internal class variable to assign unique transaction IDs.
 *
 * @property DataSource._nTransactionId
 * @type Number
 * @private
 * @static
 */
YAHOO.util.DataSource._nTransactionId = 0;

/**
 * Name of DataSource instance.
 *
 * @property _sName
 * @type String
 * @private
 */
YAHOO.util.DataSource.prototype._sName = null;

/**
 * Local cache of data result object literals indexed chronologically.
 *
 * @property _aCache
 * @type Object[]
 * @private
 */
YAHOO.util.DataSource.prototype._aCache = null;

/**
 * Local queue of request connections, enabled if queue needs to be managed.
 *
 * @property _oQueue
 * @type Object
 * @private
 */
YAHOO.util.DataSource.prototype._oQueue = null;

/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////
//
// Public member variables
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Max size of the local cache.  Set to 0 to turn off caching.  Caching is
 * useful to reduce the number of server connections.  Recommended only for data
 * sources that return comprehensive results for queries or when stale data is
 * not an issue.
 *
 * @property maxCacheEntries
 * @type Number
 * @default 0
 */
YAHOO.util.DataSource.prototype.maxCacheEntries = 0;

 /**
 * Pointer to live database.
 *
 * @property liveData
 * @type Object
 */
YAHOO.util.DataSource.prototype.liveData = null;

/**
 * Where the live data is held.
 *
 * @property dataType
 * @type Number
 * @default YAHOO.util.DataSource.TYPE_UNKNOWN
 *
 */
YAHOO.util.DataSource.prototype.dataType = YAHOO.util.DataSource.TYPE_UNKNOWN;

/**
 * Format of response.
 *
 * @property responseType
 * @type Number
 * @default YAHOO.util.DataSource.TYPE_UNKNOWN
 */
YAHOO.util.DataSource.prototype.responseType = YAHOO.util.DataSource.TYPE_UNKNOWN;

/**
 * Response schema object literal takes a combination of the following properties:
 *
 *

 *
resultsList

Pointer to array of tabular data

 *
resultNode

Pointer to node name of row data (XML data only)

 *
recordDelim

Record delimiter (text data only)

 *
fieldDelim

Field delimiter (text data only)

 *
fields

Array of field names (aka keys), or array of object literals
 * such as: {key:"fieldname",parser:YAHOO.util.DataSource.parseDate}

 *

 *
 * @property responseSchema
 * @type Object
 */
YAHOO.util.DataSource.prototype.responseSchema = null;

 /**
 * Alias to YUI Connection Manager. Allows implementers to specify their own
 * subclasses of the YUI Connection Manager utility.
 *
 * @property connMgr
 * @type Object
 * @default YAHOO.util.Connect
 */
YAHOO.util.DataSource.prototype.connMgr = null;

 /**
 * If data is accessed over XHR via Connection Manager, this setting defines
 * request/response management in the following manner:
 *

 *
queueRequests

 *
If a request is already in progress, wait until response is returned
 *     before sending the next request.

 *
 *
cancelStaleRequests

 *
If a request is already in progress, cancel it before sending the next
 *     request.

 *
 *
ignoreStaleResponses

 *
Send all requests, but handle only the response for the most recently
 *     sent request.

 *
 *
allowAll

 *
Send all requests and handle all responses.

 *
 *

 *
 * @property connXhrMode
 * @type String
 * @default "allowAll"
 */
YAHOO.util.DataSource.prototype.connXhrMode = "allowAll";

 /**
 * If data is accessed over XHR via Connection Manager, true if data should be
 * sent via POST, otherwise data will be sent via GET.
 *
 * @property connMethodPost
 * @type Boolean
 * @default false
 */
YAHOO.util.DataSource.prototype.connMethodPost = false;

 /**
 * If data is accessed over XHR via Connection Manager, the connection timeout
 * defines how many  milliseconds the XHR connection will wait for a server
 * response. Any non-zero value will enable the Connection utility's
 * Auto-Abort feature.
 *
 * @property connTimeout
 * @type Number
 * @default 0
 */
YAHOO.util.DataSource.prototype.connTimeout = 0;

/////////////////////////////////////////////////////////////////////////////
//
// Public static methods
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Converts data to type String.
 *
 * @method DataSource.parseString
 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
 * The special values null and undefined will return null.
 * @return {Number} A string, or null.
 * @static
 */
YAHOO.util.DataSource.parseString = function(oData) {
    // Special case null and undefined
    if(!YAHOO.lang.isValue(oData)) {
        return null;
    }

    //Convert to string
    var string = oData + "";

    // Validate
    if(YAHOO.lang.isString(string)) {
        return string;
    }
    else {
        return null;
    }
};

/**
 * Converts data to type Number.
 *
 * @method DataSource.parseNumber
 * @param oData {String | Number | Boolean | Null} Data to convert. Beware, null
 * returns as 0.
 * @return {Number} A number, or null if NaN.
 * @static
 */
YAHOO.util.DataSource.parseNumber = function(oData) {
    //Convert to number
    var number = oData * 1;

    // Validate
    if(YAHOO.lang.isNumber(number)) {
        return number;
    }
    else {
        return null;
    }
};
// Backward compatibility
YAHOO.util.DataSource.convertNumber = function(oData) {
    return YAHOO.util.DataSource.parseNumber(oData);
};

/**
 * Converts data to type Date.
 *
 * @method DataSource.parseDate
 * @param oData {Date | String | Number} Data to convert.
 * @return {Date} A Date instance.
 * @static
 */
YAHOO.util.DataSource.parseDate = function(oData) {
    var date = null;

    //Convert to date
    if(!(oData instanceof Date)) {
        date = new Date(oData);
    }
    else {
        return oData;
    }

    // Validate
    if(date instanceof Date) {
        return date;
    }
    else {
        return null;
    }
};
// Backward compatibility
YAHOO.util.DataSource.convertDate = function(oData) {
    return YAHOO.util.DataSource.parseDate(oData);
};

/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Public accessor to the unique name of the DataSource instance.
 *
 * @method toString
 * @return {String} Unique name of the DataSource instance.
 */
YAHOO.util.DataSource.prototype.toString = function() {
    return this._sName;
};

/**
 * Overridable method passes request to cache and returns cached response if any,
 * refreshing the hit in the cache as the newest item. Returns null if there is
 * no cache hit.
 *
 * @method getCachedResponse
 * @param oRequest {Object} Request object.
 * @param oCallback {Function} Handler function to receive the response.
 * @param oCaller {Object} The Calling object that is making the request.
 * @return {Object} Cached response object or null.
 */
YAHOO.util.DataSource.prototype.getCachedResponse = function(oRequest, oCallback, oCaller) {
    var aCache = this._aCache;
    var nCacheLength = (aCache) ? aCache.length : 0;
    var oResponse = null;

    // If cache is enabled...
    if((this.maxCacheEntries > 0) && aCache && (nCacheLength > 0)) {
        this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});

        // Loop through each cached element
        for(var i = nCacheLength-1; i >= 0; i--) {
            var oCacheElem = aCache[i];

            // Defer cache hit logic to a public overridable method
            if(this.isCacheHit(oRequest,oCacheElem.request)) {
                // Grab the cached response
                oResponse = oCacheElem.response;
                // The cache returned a hit!
                // Remove element from its original location
                aCache.splice(i,1);
                // Add as newest
                this.addToCache(oRequest, oResponse);
                this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
                break;
            }
        }
    }
    return oResponse;
};

/**
 * Default overridable method matches given request to given cached request.
 * Returns true if is a hit, returns false otherwise.  Implementers should
 * override this method to customize the cache-matching algorithm.
 *
 * @method isCacheHit
 * @param oRequest {Object} Request object.
 * @param oCachedRequest {Object} Cached request object.
 * @return {Boolean} True if given request matches cached request, false otherwise.
 */
YAHOO.util.DataSource.prototype.isCacheHit = function(oRequest, oCachedRequest) {
    return (oRequest === oCachedRequest);
};

/**
 * Adds a new item to the cache. If cache is full, evicts the stalest item
 * before adding the new item.
 *
 * @method addToCache
 * @param oRequest {Object} Request object.
 * @param oResponse {Object} Response object to cache.
 */
YAHOO.util.DataSource.prototype.addToCache = function(oRequest, oResponse) {
    var aCache = this._aCache;
    if(!aCache) {
        return;
    }

    //TODO: check for duplicate entries

    // If the cache is full, make room by removing stalest element (index=0)
    while(aCache.length >= this.maxCacheEntries) {
        aCache.shift();
    }

    // Add to cache in the newest position, at the end of the array
    var oCacheElem = {request:oRequest,response:oResponse};
    aCache.push(oCacheElem);
    this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
};

/**
 * Flushes cache.
 *
 * @method flushCache
 */
YAHOO.util.DataSource.prototype.flushCache = function() {
    if(this._aCache) {
        this._aCache = [];
        this.fireEvent("cacheFlushEvent");
    }
};

/**
 * First looks for cached response, then sends request to live data.
 *
 * @method sendRequest
 * @param oRequest {Object} Request object.
 * @param oCallback {Function} Handler function to receive the response.
 * @param oCaller {Object} The Calling object that is making the request.
 * @return {Number} Transaction ID, or null if response found in cache.
 */
YAHOO.util.DataSource.prototype.sendRequest = function(oRequest, oCallback, oCaller) {
    // First look in cache
    var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
    if(oCachedResponse) {
        oCallback.call(oCaller, oRequest, oCachedResponse);
        return null;
    }

    // Not in cache, so forward request to live data
    return this.makeConnection(oRequest, oCallback, oCaller);
};

/**
 * Overridable method provides default functionality to make a connection to
 * live data in order to send request. The response coming back is then
 * forwarded to the handleResponse function. This method should be customized
 * to achieve more complex implementations.
 *
 * @method makeConnection
 * @param oRequest {Object} Request object.
 * @param oCallback {Function} Handler function to receive the response.
 * @param oCaller {Object} The Calling object that is making the request.
 * @return {Number} Transaction ID.
 */
YAHOO.util.DataSource.prototype.makeConnection = function(oRequest, oCallback, oCaller) {
    this.fireEvent("requestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
    var oRawResponse = null;
    var tId = YAHOO.util.DataSource._nTransactionId++;

    // How to make the connection depends on the type of data
    switch(this.dataType) {
        // If the live data is a JavaScript Function
        // pass the request in as a parameter and
        // forward the return value to the handler
        case YAHOO.util.DataSource.TYPE_JSFUNCTION:
            oRawResponse = this.liveData(oRequest);
            this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
            break;
        // If the live data is over Connection Manager
        // set up the callback object and
        // pass the request in as a URL query and
        // forward the response to the handler
        case YAHOO.util.DataSource.TYPE_XHR:
            var oSelf = this;
            var oConnMgr = this.connMgr || YAHOO.util.Connect;
            var oQueue = this._oQueue;

            /**
             * Define Connection Manager success handler
             *
             * @method _xhrSuccess
             * @param oResponse {Object} HTTPXMLRequest object
             * @private
             */
            var _xhrSuccess = function(oResponse) {
                // If response ID does not match last made request ID,
                // silently fail and wait for the next response
                if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
                        (oResponse.tId != oQueue.conn.tId)) {
                    return null;
                }
                // Error if no response
                else if(!oResponse) {
                    this.fireEvent("dataErrorEvent", {request:oRequest,
                            callback:oCallback, caller:oCaller,
                            message:YAHOO.util.DataSource.ERROR_DATANULL});

                    // Send error response back to the caller with the error flag on
                    oCallback.call(oCaller, oRequest, oResponse, true);

                    return null;
                }
                // Forward to handler
                else {
                    this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
                }
            };

            /**
             * Define Connection Manager failure handler
             *
             * @method _xhrFailure
             * @param oResponse {Object} HTTPXMLRequest object
             * @private
             */
            var _xhrFailure = function(oResponse) {
                this.fireEvent("dataErrorEvent", {request:oRequest,
                        callback:oCallback, caller:oCaller,
                        message:YAHOO.util.DataSource.ERROR_DATAINVALID});

                // Backward compatibility
                if((this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
                    (oRequest.indexOf("?") !== 0)){
                }

                // Send failure response back to the caller with the error flag on
                oCallback.call(oCaller, oRequest, oResponse, true);
                return null;
            };

            /**
             * Define Connection Manager callback object
             *
             * @property _xhrCallback
             * @param oResponse {Object} HTTPXMLRequest object
             * @private
             */
             var _xhrCallback = {
                success:_xhrSuccess,
                failure:_xhrFailure,
                scope: this
            };

            // Apply Connection Manager timeout
            if(YAHOO.lang.isNumber(this.connTimeout)) {
                _xhrCallback.timeout = this.connTimeout;
            }

            // Cancel stale requests
            if(this.connXhrMode == "cancelStaleRequests") {
                    // Look in queue for stale requests
                    if(oQueue.conn) {
                        if(oConnMgr.abort) {
                            oConnMgr.abort(oQueue.conn);
                            oQueue.conn = null;
                        }
                        else {
                        }
                    }
            }

            // Get ready to send the request URL
            if(oConnMgr && oConnMgr.asyncRequest) {
                var sLiveData = this.liveData;
                var isPost = this.connMethodPost;
                var sMethod = (isPost) ? "POST" : "GET";
                var sUri = (isPost) ? sLiveData : sLiveData+oRequest;
                var sRequest = (isPost) ? oRequest : null;

                // Send the request right away
                if(this.connXhrMode != "queueRequests") {
                    oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
                }
                // Queue up then send the request
                else {
                    // Found a request already in progress
                    if(oQueue.conn) {
                        // Add request to queue
                        oQueue.requests.push({request:oRequest, callback:_xhrCallback});

                        // Interval needs to be started
                        if(!oQueue.interval) {
                            oQueue.interval = setInterval(function() {
                                // Connection is in progress
                                if(oConnMgr.isCallInProgress(oQueue.conn)) {
                                    return;
                                }
                                else {
                                    // Send next request
                                    if(oQueue.requests.length > 0) {
                                        sUri = (isPost) ? sLiveData : sLiveData+oQueue.requests[0].request;
                                        sRequest = (isPost) ? oQueue.requests[0].request : null;
                                        oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, oQueue.requests[0].callback, sRequest);

                                        // Remove request from queue
                                        oQueue.requests.shift();
                                    }
                                    // No more requests
                                    else {
                                        clearInterval(oQueue.interval);
                                        oQueue.interval = null;
                                    }
                                }
                            }, 50);
                        }
                    }
                    // Nothing is in progress
                    else {
                        oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
                    }
                }
            }
            else {
                // Send null response back to the caller with the error flag on
                oCallback.call(oCaller, oRequest, null, true);
            }

            break;
        // Simply forward the entire data object to the handler
        default:
            /* accounts for the following cases:
            YAHOO.util.DataSource.TYPE_UNKNOWN:
            YAHOO.util.DataSource.TYPE_JSARRAY:
            YAHOO.util.DataSource.TYPE_JSON:
            YAHOO.util.DataSource.TYPE_HTMLTABLE:
            YAHOO.util.DataSource.TYPE_XML:
            */
            oRawResponse = this.liveData;
            this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
            break;
    }
    return tId;
};

/**
 * Handles raw data response from live data source. Sends a parsed response object
 * to the callback function in this format:
 *
 * fnCallback(oRequest, oParsedResponse)
 *
 * where the oParsedResponse object literal with the following properties:
 *

 *
tId {Number} Unique transaction ID

 *
results {Array} Array of parsed data results

 *
error {Boolean} True if there was an error

 *

 *
 * @method handleResponse
 * @param oRequest {Object} Request object
 * @param oRawResponse {Object} The raw response from the live database.
 * @param oCallback {Function} Handler function to receive the response.
 * @param oCaller {Object} The calling object that is making the request.
 * @param tId {Number} Transaction ID.
 */
YAHOO.util.DataSource.prototype.handleResponse = function(oRequest, oRawResponse, oCallback, oCaller, tId) {
    this.fireEvent("responseEvent", {request:oRequest, response:oRawResponse,
            callback:oCallback, caller:oCaller, tId: tId});
    var xhr = (this.dataType == YAHOO.util.DataSource.TYPE_XHR) ? true : false;
    var oParsedResponse = null;
    var bError = false;

    // Access to the raw response before it gets parsed
    oRawResponse = this.doBeforeParseData(oRequest, oRawResponse);

    switch(this.responseType) {
        case YAHOO.util.DataSource.TYPE_JSARRAY:
            if(xhr && oRawResponse.responseText) {
                oRawResponse = oRawResponse.responseText;
            }
            oParsedResponse = this.parseArrayData(oRequest, oRawResponse);
            break;
        case YAHOO.util.DataSource.TYPE_JSON:
            if(xhr && oRawResponse.responseText) {
                oRawResponse = oRawResponse.responseText;
            }
            oParsedResponse = this.parseJSONData(oRequest, oRawResponse);
            break;
        case YAHOO.util.DataSource.TYPE_HTMLTABLE:
            if(xhr && oRawResponse.responseText) {
                oRawResponse = oRawResponse.responseText;
            }
            oParsedResponse = this.parseHTMLTableData(oRequest, oRawResponse);
            break;
        case YAHOO.util.DataSource.TYPE_XML:
            if(xhr && oRawResponse.responseXML) {
                oRawResponse = oRawResponse.responseXML;
            }
            oParsedResponse = this.parseXMLData(oRequest, oRawResponse);
            break;
        case YAHOO.util.DataSource.TYPE_TEXT:
            if(xhr && oRawResponse.responseText) {
                oRawResponse = oRawResponse.responseText;
            }
            oParsedResponse = this.parseTextData(oRequest, oRawResponse);
            break;
        default:
            //var contentType = oRawResponse.getResponseHeader["Content-Type"];
            break;
    }

    if(oParsedResponse) {
        // Last chance to touch the raw response or the parsed response
        oParsedResponse.tId = tId;
        oParsedResponse = this.doBeforeCallback(oRequest, oRawResponse, oParsedResponse);
        this.fireEvent("responseParseEvent", {request:oRequest,
                response:oParsedResponse, callback:oCallback, caller:oCaller});
        // Cache the response
        this.addToCache(oRequest, oParsedResponse);
    }
    else {
        this.fireEvent("dataErrorEvent", {request:oRequest, callback:oCallback,
                caller:oCaller, message:YAHOO.util.DataSource.ERROR_DATANULL});

        // Send response back to the caller with the error flag on
        oParsedResponse = {error:true};
    }

    // Send the response back to the caller
    oCallback.call(oCaller, oRequest, oParsedResponse);
};

/**
 * Overridable method gives implementers access to the original raw response
 * before the data gets parsed. Implementers should take care not to return an
 * unparsable or otherwise invalid raw response.
 *
 * @method doBeforeParseData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Raw response for parsing.
 */
YAHOO.util.DataSource.prototype.doBeforeParseData = function(oRequest, oRawResponse) {
    return oRawResponse;
};

/**
 * Overridable method gives implementers access to the original raw response and
 * the parsed response (parsed against the given schema) before the data
 * is added to the cache (if applicable) and then sent back to callback function.
 * This is your chance to access the raw response and/or populate the parsed
 * response with any custom data.
 *
 * @method doBeforeCallback
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @param oParsedResponse {Object} The parsed response to return to calling object.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.doBeforeCallback = function(oRequest, oRawResponse, oParsedResponse) {
    return oParsedResponse;
};

/**
 * Overridable method parses raw array data into a response object.
 *
 * @method parseArrayData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.parseArrayData = function(oRequest, oRawResponse) {
    if(YAHOO.lang.isArray(oRawResponse) && YAHOO.lang.isArray(this.responseSchema.fields)) {
        var oParsedResponse = {results:[]};
        var fields = this.responseSchema.fields;
        for(var i=oRawResponse.length-1; i>-1; i--) {
            var oResult = {};
            for(var j=fields.length-1; j>-1; j--) {
                var field = fields[j];
                var key = (YAHOO.lang.isValue(field.key)) ? field.key : field;
                var data = (YAHOO.lang.isValue(oRawResponse[i][j])) ? oRawResponse[i][j] : oRawResponse[i][key];
                // Backward compatibility
                if(!field.parser && field.converter) {
                    field.parser = field.converter;
                }
                if(field.parser) {
                    data = field.parser.call(this, data);
                }
                // Safety measure
                if(data === undefined) {
                    data = null;
                }
                oResult[key] = data;
            }
            oParsedResponse.results.unshift(oResult);
        }
        return oParsedResponse;
    }
    else {
        return null;
    }
};

/**
 * Overridable method parses raw plain text data into a response object.
 *
 * @method parseTextData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.parseTextData = function(oRequest, oRawResponse) {
    var oParsedResponse = {};
    if(YAHOO.lang.isString(oRawResponse) &&
            YAHOO.lang.isArray(this.responseSchema.fields) &&
            YAHOO.lang.isString(this.responseSchema.recordDelim) &&
            YAHOO.lang.isString(this.responseSchema.fieldDelim)) {
        oParsedResponse.results = [];
        var recDelim = this.responseSchema.recordDelim;
        var fieldDelim = this.responseSchema.fieldDelim;
        var fields = this.responseSchema.fields;
        if(oRawResponse.length > 0) {
            // Delete the last line delimiter at the end of the data if it exists
            var newLength = oRawResponse.length-recDelim.length;
            if(oRawResponse.substr(newLength) == recDelim) {
                oRawResponse = oRawResponse.substr(0, newLength);
            }
            // Split along record delimiter to get an array of strings
            var recordsarray = oRawResponse.split(recDelim);
            // Cycle through each record, except the first which contains header info
            for(var i = recordsarray.length-1; i>-1; i--) {
                var oResult = {};
                for(var j=fields.length-1; j>-1; j--) {
                    // Split along field delimter to get each data value
                    var fielddataarray = recordsarray[i].split(fieldDelim);

                    // Remove quotation marks from edges, if applicable
                    var data = fielddataarray[j];
                    if(data.charAt(0) == "\"") {
                        data = data.substr(1);
                    }
                    if(data.charAt(data.length-1) == "\"") {
                        data = data.substr(0,data.length-1);
                    }
                    var field = fields[j];
                    var key = (YAHOO.lang.isValue(field.key)) ? field.key : field;
                    // Backward compatibility
                    if(!field.parser && field.converter) {
                        field.parser = field.converter;
                    }
                    if(field.parser) {
                        data = field.parser.call(this, data);
                    }
                    // Safety measure
                    if(data === undefined) {
                        data = null;
                    }
                    oResult[key] = data;
                }
                oParsedResponse.results.unshift(oResult);
            }
        }
    }
    else {
        oParsedResponse.error = true;
    }
    return oParsedResponse;
};

/**
 * Overridable method parses raw XML data into a response object.
 *
 * @method parseXMLData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.parseXMLData = function(oRequest, oRawResponse) {
        var bError = false;
        var oParsedResponse = {};
        var xmlList = (this.responseSchema.resultNode) ?
                oRawResponse.getElementsByTagName(this.responseSchema.resultNode) :
                null;
        if(!xmlList || !YAHOO.lang.isArray(this.responseSchema.fields)) {
            bError = true;
        }
        // Loop through each result
        else {
            oParsedResponse.results = [];
            for(var k = xmlList.length-1; k >= 0 ; k--) {
                var result = xmlList.item(k);
                var oResult = {};
                // Loop through each data field in each result using the schema
                for(var m = this.responseSchema.fields.length-1; m >= 0 ; m--) {
                    var field = this.responseSchema.fields[m];
                    var key = (YAHOO.lang.isValue(field.key)) ? field.key : field;
                    var data = null;
                    // Values may be held in an attribute...
                    var xmlAttr = result.attributes.getNamedItem(key);
                    if(xmlAttr) {
                        data = xmlAttr.value;
                    }
                    // ...or in a node
                    else {
                        var xmlNode = result.getElementsByTagName(key);
                        if(xmlNode && xmlNode.item(0) && xmlNode.item(0).firstChild) {
                            data = xmlNode.item(0).firstChild.nodeValue;
                        }
                        else {
                               data = "";
                        }
                    }
                    // Backward compatibility
                    if(!field.parser && field.converter) {
                        field.parser = field.converter;
                    }
                    if(field.parser) {
                        data = field.parser.call(this, data);
                    }
                    // Safety measure
                    if(data === undefined) {
                        data = null;
                    }
                    oResult[key] = data;
                }
                // Capture each array of values into an array of results
                oParsedResponse.results.unshift(oResult);
            }
        }
        if(bError) {
            oParsedResponse.error = true;
        }
        else {
        }
        return oParsedResponse;
};

/**
 * Overridable method parses raw JSON data into a response object.
 *
 * @method parseJSONData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.parseJSONData = function(oRequest, oRawResponse) {
    var oParsedResponse = {};
    if(oRawResponse && YAHOO.lang.isArray(this.responseSchema.fields)) {
        var fields = this.responseSchema.fields;
        var bError = false;
        oParsedResponse.results = [];
        var jsonObj,jsonList;

        // Parse JSON object out if it's a string
        if(YAHOO.lang.isString(oRawResponse)) {
            // Check for latest JSON lib but divert KHTML clients
            var isNotMac = (navigator.userAgent.toLowerCase().indexOf('khtml')== -1);
            if(oRawResponse.parseJSON && isNotMac) {
                // Use the new JSON utility if available
                jsonObj = oRawResponse.parseJSON();
                if(!jsonObj) {
                    bError = true;
                }
            }
            // Check for older JSON lib but divert KHTML clients
            else if(window.JSON && JSON.parse && isNotMac) {
                // Use the JSON utility if available
                jsonObj = JSON.parse(oRawResponse);
                if(!jsonObj) {
                    bError = true;
                }
            }
            // No JSON lib found so parse the string
            else {
                try {
                    // Trim leading spaces
                    while (oRawResponse.length > 0 &&
                            (oRawResponse.charAt(0) != "{") &&
                            (oRawResponse.charAt(0) != "[")) {
                        oRawResponse = oRawResponse.substring(1, oRawResponse.length);
                    }

                    if(oRawResponse.length > 0) {
                        // Strip extraneous stuff at the end
                        var objEnd = Math.max(oRawResponse.lastIndexOf("]"),oRawResponse.lastIndexOf("}"));
                        oRawResponse = oRawResponse.substring(0,objEnd+1);

                        // Turn the string into an object literal...
                        // ...eval is necessary here
                        jsonObj = eval("(" + oRawResponse + ")");
                        if(!jsonObj) {
                            bError = true;
                        }

                    }
                    else {
                        jsonObj = null;
                        bError = true;
                    }
                }
                catch(e) {
                    bError = true;
               }
            }
        }
        // Response must already be a JSON object
        else if(oRawResponse.constructor == Object) {
            jsonObj = oRawResponse;
        }
        // Not a string or an object
        else {
            bError = true;
        }
        // Now that we have a JSON object, parse a jsonList out of it
        if(jsonObj && jsonObj.constructor == Object) {
            try {
                // eval is necessary here since schema can be of unknown depth
                jsonList = eval("jsonObj." + this.responseSchema.resultsList);
            }
            catch(e) {
                bError = true;
            }
        }

        if(bError || !jsonList) {
            oParsedResponse.error = true;
        }
        if(jsonList && !YAHOO.lang.isArray(jsonList)) {
            jsonList = [jsonList];
        }
        else if(!jsonList) {
            jsonList = [];
        }

        // Loop through the array of all responses...
        for(var i = jsonList.length-1; i >= 0 ; i--) {
            var oResult = {};
            var jsonResult = jsonList[i];
            // ...and loop through each data field value of each response
            for(var j = fields.length-1; j >= 0 ; j--) {
                var field = fields[j];
                var key = (YAHOO.lang.isValue(field.key)) ? field.key : field;
                // ...and capture data into an array mapped according to the schema...
                // eval is necessary here since schema can be of unknown depth
                var data = eval("jsonResult." + key);

                // Backward compatibility
                if(!field.parser && field.converter) {
                    field.parser = field.converter;
                }
                if(field.parser) {
                    data = field.parser.call(this, data);
                }
                // Safety measure
                if(data === undefined) {
                    data = null;
                }
                oResult[key] = data;
            }
            // Capture the array of data field values in an array of results
            oParsedResponse.results.unshift(oResult);
        }
    }
    else {
        oParsedResponse.error = true;
    }
    return oParsedResponse;
};

/**
 * Overridable method parses raw HTML TABLE element data into a response object.
 *
 * @method parseHTMLTableData
 * @param oRequest {Object} Request object.
 * @param oRawResponse {Object} The raw response from the live database.
 * @return {Object} Parsed response object.
 */
YAHOO.util.DataSource.prototype.parseHTMLTableData = function(oRequest, oRawResponse) {
        var bError = false;
        var elTable = oRawResponse;
        var fields = this.responseSchema.fields;
        var oParsedResponse = {};
        oParsedResponse.results = [];

        // Iterate through each TBODY
        for(var i=0; i<elTable.tBodies.length; i++) {
            var elTbody = elTable.tBodies[i];

            // Iterate through each TR
            for(var j=elTbody.rows.length-1; j>-1; j--) {
                var elRow = elTbody.rows[j];
                var oResult = {};

                for(var k=fields.length-1; k>-1; k--) {
                    var field = fields[k];
                    var key = (YAHOO.lang.isValue(field.key)) ? field.key : field;
                    var data = elRow.cells[k].innerHTML;

                    // Backward compatibility
                    if(!field.parser && field.converter) {
                        field.parser = field.converter;
                    }
                    if(field.parser) {
                        data = field.parser.call(this, data);
                    }
                    // Safety measure
                    if(data === undefined) {
                        data = null;
                    }
                    oResult[key] = data;
                }
                oParsedResponse.results.unshift(oResult);
            }
        }

        if(bError) {
            oParsedResponse.error = true;
        }
        else {
        }
        return oParsedResponse;
};

YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.3.1", build: "541"});

redpajama_set_name: RedPajamaGithub


text:
1. Include jQuery:

	```html
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
	```

2. Include plugin's code:

	```html
	<script src="dist/jquery.masked-input.min.js"></script>
	```

3. Call the plugin:

	```javascript
	$("#element").maskedInput({
	});
	```

## Structure

The basic structure of the project is given in the following way:

```
├── demo/
│   └── index.html
├── dist/
│   ├── jquery.masked-input.js
│   └── jquery.masked-input.min.js
├── src/
│   └── jquery.masked-input.js
├── .editorconfig
├── .gitignore
├── .jshintrc
├── .travis.yml
├── masked-input.jquery.json
├── Gruntfile.js
└── package.json
```

#### [demo/](https://github.com/simpli-io/masked-input/tree/master/demo)

Contains a simple HTML file to demonstrate your plugin.

#### [dist/](https://github.com/simpli-io/masked-input/tree/master/dist)

This is where the generated files are stored once Grunt runs.

#### [src/](https://github.com/simpli-io/masked-input/tree/master/src)

Contains the plugin's source files.

## Contributing

Check [CONTRIBUTING.md](https://github.com/simpli-io/masked-input/blob/master/CONTRIBUTING.md) for more information.

## History

Check [Releases](https://github.com/simpli-io/simpli-io/releases) for detailed changelog.

## License

[MIT License](https://github.com/simpli-io/masked-input/blob/master/LICENSE) © simpli-io


text:
import re
import os

from ..models import Report
from ..app import log, application

class ParseError(Exception):
    """
    These are raised when there is an error in the input file
    """
    pass

class BasicParser(object):
    FIRST_REGEX = "^.*$"
    LINE_REGEX = "^.*$"

    def __init__(self):
        log.debug("COMPILING %s", self.FIRST_REGEX)
        self._first_regex = re.compile(self.FIRST_REGEX)
        log.debug("COMPILING %s", self.LINE_REGEX)
        self._line_regex = re.compile(self.LINE_REGEX)
        self._session = None
        self._con = None
        self._insert_queue = []
        self.max_pending_rows = 100

    @property
    def session(self):
        if not self._session:
            self._session = application.Session()
        return self._session

    @property
    def connection(self):
        if not self._con:
            self._con = application.engine.connect()
        return self._con

    def cleanup(self):
        self.session.commit()
        self.session.close()

    def parse(self, fqn, user, catch_errors):
        """
        Take a filepath and split process it line by line
        """

        self.filename = fqn
        self.user = user

        with open(fqn) as f:
            try:
                for number, line in enumerate(f):
                    if number==0:
                        try:
                            self.process_first(line.strip())
                        except ParseError:
                            log.error("INVALID FILE HEADER IN: %s", fqn)
                            if not catch_errors:
                                raise
                            break
                    else:
                        try:
                            log.debug("### BEGIN LINE ###")
                            self.process_line(line.strip())
                            log.debug("### END LINE ###")
                        except ParseError:
                            log.error("INVALID LINE: %s:%d", fqn, number)
                            if not catch_errors:
                                raise
            except:
                self.flush()
                self.cleanup()
                raise

        self.flush()
        self.cleanup()

    def process_first(self, line):
        """
        We need to validate the headers of each file and we also dont want to add the headers to the database
        """
        match = self._first_regex.match(line)
        log.debug("PROCESSING FIRST LINE: %s", line)

        if match:
            self.process_validated_first(line)

        else:
            raise ParseError("Invalid Header")

    def process_validated_first(self, line):
        """
        Create a report object
        """
        log.info("CREATING REPORT {} OBJECT FOR {}".format(self.TYPE, self.user))
        self.report = Report()
        self.report.filename = self.filename
        self.report.user = self.user
        self.report.type = self.TYPE
        self.report.save(self.session)

    def process_line(self, line):
        """
        We need to validate each line
        """
        match = self._line_regex.match(line)
        log.debug("PROCESSING LINE: %s", line)

        if match:
            self.process_validated_line(line, match)
        else:
            raise ParseError("Invalid Line")

    def process_validated_line(self, line, match):
        """
        Base class doesn't do anything with the parsed data
        """
        print line

    def insert_dict(self, dictionary):
        """
        Put an object into our insert list for a pending insert
        """
        log.debug("Added item to data queue")
        self._insert_queue.append(dictionary)
        if len(self._insert_queue) > self.max_pending_rows:
            self.flush()

    def flush(self):
        log.info("COMMITING DATA")
        self.connection.execute(self.DB_CLS.__table__.insert(), list(self._insert_queue))
        self._insert_queue = []


text:
/**
 * @file
 *
 *  Example top level file for SystemC-TLM integration with C++-only
 *  instantiation.
 *
 */

#include <systemc>
#include <tlm>

#include "cli_parser.hh"
#include "report_handler.hh"
#include "sc_target.hh"
#include "sim_control.hh"
#include "slave_transactor.hh"
#include "stats.hh"

int
sc_main(int argc, char **argv)
{
    CliParser parser;
    parser.parse(argc, argv);

    sc_core::sc_report_handler::set_handler(reportHandler);

    Gem5SystemC::Gem5SimControl sim_control("gem5",
                                           parser.getConfigFile(),
                                           parser.getSimulationEnd(),
                                           parser.getDebugFlags());

    unsigned long long int memorySize = 512*1024*1024ULL;

    Gem5SystemC::Gem5SlaveTransactor transactor("transactor", "transactor");
    Target memory("memory",
                  parser.getVerboseFlag(),
                  memorySize,
                  parser.getMemoryOffset());

    memory.socket.bind(transactor.socket);
    transactor.sim_control.bind(sim_control);

    SC_REPORT_INFO("sc_main", "Start of Simulation");

    sc_core::sc_start();

    SC_REPORT_INFO("sc_main", "End of Simulation");

    CxxConfig::statsDump();

    return EXIT_SUCCESS;
}


text:
package ua.angrybeavers.material.em.ui.activities;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import ua.angrybeavers.material.em.R;
import ua.angrybeavers.material.em.ui.adapters.NavigationDrawerAdapter;
import ua.angrybeavers.material.em.ui.drawer.ActionBarDrawerToggle;
import ua.angrybeavers.material.em.ui.drawer.DrawerArrowDrawable;
import ua.angrybeavers.material.em.ui.items.DrawerItemPrimary;

/**
 * @author yyunikov
 */
public abstract class BaseActivity extends Activity {

    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        overridePendingTransition(0, 0);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (item.getItemId() == R.id.action_settings) {
            return true;
        }

        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    protected void setupActionBar() {
        final ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle(R.string.app_name);
        }
    }

    protected void setupDrawer() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        setDrawerAdapter();

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                createDrawerArrow(),
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                /* empty */
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                /* empty */
            }
        };

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private DrawerArrowDrawable createDrawerArrow() {
        return new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
    }

    private void setDrawerAdapter() {
        final NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(this);

        adapter.add(new DrawerItemPrimary("Account"));
        adapter.add(new DrawerItemPrimary("Reminder"));
        adapter.add(new DrawerItemPrimary("Note"));
        adapter.add(new DrawerItemPrimary("Tools"));
        adapter.add(new DrawerItemPrimary("Pro Edition"));
        adapter.add(new DrawerItemPrimary("About"));

        mDrawerList.setAdapter(adapter);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            final Intent intent;

            switch (position) {
                case 0:
                    intent = new Intent(BaseActivity.this, AccountActivity.class).
                            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                                    | Intent.FLAG_ACTIVITY_SINGLE_TOP); break;
                case 5:
                    intent = new Intent(BaseActivity.this, AboutActivity.class).
                            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); break;
                default:
                    intent = null;
                    break;
            }

            mDrawerLayout.closeDrawer(mDrawerList);

            if (intent != null) {
                startActivity(intent);
            }
        }
    }
}


text:
- Prevent accidentally scrolling to the top of the viewport if you call `noScroll.on()` twice without any intervening `noScroll.off()`.

## 2.1.0

- Add `toggle` function.

## 2.0.0

- Switch methods for scroll blocking. Now we're fixing the `position` of `document.documentElement`.
- Switch methods for scrollbar compensation. Now we're using `calc()`.

## 1.1.2

- Fix IE bug.

## 1.1.0 and 1.1.1

- Expose `noScroll` globally if `module.exports` is unavailable (no CommonJS environment).

## 1.0.2

- No-op if there's no document.

## 1.0.1

- Switch inline styles from body to `documentElement`.

## 1.0.0

- Initial release.


text:
<?php
/**
 * Created by PhpStorm.
 * User: akeinhell
 * Date: 20.11.16
 * Time: 20:05
 */

namespace Telegram\Entry;

use Telegram\Base\BaseEntry;

class KeyboardButtonEntry extends BaseEntry
{
    /**
     * @param $text
     * @param bool $requestContact
     * @param bool $requestLocation
     * @return KeyboardButtonEntry
     */
    public static function create($text = '', $requestContact = false, $requestLocation = false)
    {
        return (new static())
            ->setText($text)
            ->setRequestContact($requestContact)
            ->setRequestLocation($requestLocation);
    }

    /**
     * @param $text
     * @return $this
     */
    public function setText($text)
    {
        return $this->set('text', $text);
    }

    /**
     * @param bool $requestContact
     * @return $this
     */
    public function setRequestContact($requestContact)
    {
        return $this->set('request_contact', $requestContact);
    }

    /**
     * @param bool $requestLocation
     * @return $this
     */
    public function setRequestLocation($requestLocation){
        return $this->set('request_contact', $requestLocation);
    }
}


text:
package ibis.io.jme;

class IbisIllegalAccessException extends IllegalAccessException {

    private static final long serialVersionUID = 1L;

    public IbisIllegalAccessException() {
    }

    public IbisIllegalAccessException(String message) {
        super(message);
    }
}


text:
Ext.define('KitchenSink.view.form.ContactFormWindow', {
    extend: 'Ext.window.Window',
    xtype: 'form-contact-window',

    reference: 'popupWindow',

    title: 'Contact Us',
    width: 400,
    minWidth: 300,
    minHeight: 380,
    layout: 'fit',
    resizable: true,
    modal: true,
    defaultFocus: 'firstName',
    closeAction: 'hide',

    items: [{
        xtype: 'form',
        reference: 'windowForm',
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        border: false,
        bodyPadding: 10,

        fieldDefaults: {
            msgTarget: 'side',
            labelAlign: 'top',
            labelWidth: 100,
            labelStyle: 'font-weight:bold'
        },

        items: [{
            xtype: 'fieldcontainer',
            fieldLabel: 'Your Name',
            labelStyle: 'font-weight:bold;padding:0;',
            layout: 'hbox',
            defaultType: 'textfield',

            fieldDefaults: {
                labelAlign: 'top'
            },

            items: [{
                flex: 1,
                name: 'firstName',
                itemId: 'firstName',
                afterLabelTextTpl: [
                    '*'
                ],
                fieldLabel: 'First',
                allowBlank: false
            }, {
                width: 30,
                name: 'middleInitial',
                fieldLabel: 'MI',
                margin: '0 0 0 5'
            }, {
                flex: 2,
                name: 'lastName',
                afterLabelTextTpl: [
                    '*'
                ],
                fieldLabel: 'Last',
                allowBlank: false,
                margin: '0 0 0 5'
            }]
        }, {
            xtype: 'textfield',
            fieldLabel: 'Your Email Address',
            afterLabelTextTpl: [
                '*'
            ],
            vtype: 'email',
            allowBlank: false
        }, {
            xtype: 'textfield',
            fieldLabel: 'Subject',
            afterLabelTextTpl: [
                '*'
            ],
            allowBlank: false
        }, {
            xtype: 'textareafield',
            fieldLabel: 'Message',
            labelAlign: 'top',
            flex: 1,
            margin: '0',
            afterLabelTextTpl: [
                '*'
            ],
            allowBlank: false
        }],

        buttons: [{
            text: 'Cancel',
            handler: 'onFormCancel'
        }, {
            text: 'Send',
            handler: 'onFormSubmit'
        }]
    }]
});


text:
const char *_errstr[] = {
    "no error",
    "unrecognized option",
    "cannot open input file",
    "cannot open output file",
    "invalid instruction",
    "invalid alphanumeric constant",
    "symbol already defined",
    "invalid symbol name",
    "undefined symbol",
    "undefined local symbol",
    "forward symbol used in expression",
    "division by zero",
    "parse error"
};

static int _errstr_count  = sizeof(_errstr) / sizeof(char *);

const char * errstr(int err)
{
    return (err < _errstr_count ? _errstr[err] : NULL);
}


text:
import maya.cmds as cmds # @UnresolvedImport

import oopmaya.core as oopmaya # @UnresolvedImport
reload( oopmaya )

import simulation_tool # @UnresolvedImport
reload( simulation_tool )

class Skin_Convert_Tool():
   def convert_mesh_to_joints( self, objects ):
      mesh_joints = []
      joints_dag = []

      cluster_joints = []
      cluster_data = {}

      meshes = oopmaya.get_object_type( objects, 'mesh' )
      cluster_handles = oopmaya.get_object_type( objects, 'cluster1Handle' )

      for mesh in meshes:
         cmds.select( cl = True )

         mesh_joints.append( cmds.joint( n = '{0}_jnt'.format( mesh ) ) )
         joint_dag = oopmaya.DAG_Node()
         joints_dag.append( joint_dag )

         cmds.parentConstraint( mesh, joint_dag.name() )

      for cluster_handle in cluster_handles:
         cluster_vert = oopmaya.get_cluster_verts( cluster_handle )

         if cluster_vert:
            mesh_shape = cmds.cluster( cluster_handle, geometry = True, q = True )
            mesh_transform = cmds.listRelatives( mesh_shape, parent = True )

            cluster_data[mesh_transform] = [cluster_handles, cluster_vert]

            cluster_joints.append( cmds.joint( n = '{0}_jnt'.format( cluster_handle ) ) )
            joint_dag = oopmaya.DAG_Node()
            joints_dag.append( joint_dag )

            cmds.parentConstraint( cluster_handle, joint_dag.name() )

      simulation_tool.Simulation_Tool().bake_sim( mesh_joints, cluster_joints )
      cmds.delete( objects, cn = True )

      for obj_dag, joint_dag in zip( meshes, joints_dag ):
         if obj_dag.name() in cluster_data:
            print 1

         obj_dag.parent_constraint( joint_dag )


text:
(function($) {
  'use strict';
  let $userList = $('.user-list');
  let userData;
  $.ajax('data/users.json', {
    success: function(data) {
      data.forEach(obj => {
        let $user = $('<div>').addClass('user');
        let $name = $('<div>').addClass('name');
        let $email = $('<p>').addClass('email');
        $name.text(obj.name).appendTo($user);
        $email.text(obj.email).appendTo($user);
        $user.appendTo($userList);
      });
      setData(data);
      addListeners();
    },
    error: function(status) {
      console.log('error: ', status);
    },
    complete: function() {
      console.log('complete');
      if (userData) {
        userData
        .filter(obj => obj.address)
        .map(obj => obj.name)
        .forEach(name => {
          $(`.name:contains(${name})`).addClass('has-address');
        });
        $('.user > .name')
        .filter('.has-address')
        .parent()
        .remove()
        .prependTo($('.user-list'));
      }
    }
  });
  // setData function
  function setData(data) {
    userData = data;
  }

  // addListeners function
  function addListeners() {
    $userList.on('click', '.name', selectedHandler);
    $('.clear-btn').on('click', clearSelection);
  }

  function selectedHandler(e) {
    let $target = $(e.target);
    $('.highlight').removeClass('highlight');
    if ($target.hasClass('selected')) {
      $target.removeClass('selected');
      $target.trigger('user-deselected');
    } else {
      $('.selected').removeClass('selected');
      $target.addClass('selected');
      $target.parent().addClass('highlight');
      let user = userData.filter(obj => obj.name === $target.text());
      $target.trigger('user-selected', user);
    }
  }

  function clearSelection(e) {
    let $target = $(e.target);
    $target.trigger('user-deselected');
    $('.highlight').removeClass('highlight');
    $('.selected').removeClass('selected');
  }
})(jQuery);


text:
Admin4rails.setup do
  resource class: Post do
    icon 'fa-table'
  end

  resource class: Comment do
    belongs_to :post
  end

  resource class: Reply do
    belongs_to :comment
  end

  resource class: AdminUser do
    icon 'fa-user-md'
    member_action verb: :put, method: 'test_action'
    member_action verb: :put, method: 'test_action2'
  end

  resource class: Physician do
  end

  resource class: Patient do
  end

  language text: 'Italiano', locale: :it
  language text: 'English', locale: :en
end


text:
/**
 * A simple factory to creeate a 2D grid or matrix of numbers with an initial value stored in each cell (based on Crockford's Array.matrix)
 *
 * @author Jim Armstrong (www.algorithmist.net)
 *
 * @version 1.0
 */

 export class Matrix
 {
   constructor()
   {
     // empty
   }

  /**
   * Create a new mxn grid or matrix with a supplied default value
   *
   * @param rows: number Number of rows
   *
   * @param cols: number Number of columns
   *
   * @param initValue: number Initial value
   *
   * @return Array<Array<number>> Matrix (array of arrays) initialized with the supplied default value.  There is no error-checking on the inputs; you break it, you buy it.
   */
   static create(rows: number, cols: number, initValue: number): Array<Array<number>>
   {
     let a: Array<Array<number>> = new Array<Array<number>>();

     if (!isNaN(rows) && !isNaN(cols) && !isNaN(initValue) && rows > 0 && cols > 0)
     {
       let i: number;
       let j: number;

       for (i=0; i<rows; ++i)
       {
         let columns: Array<number> = new Array<number>();
         for (j=0; j<cols; ++j)
            columns[j] = initValue;

         a[i] = columns;
       }
     }

     return a;
   }
 }


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/wanlass-julia-sphia-phillips-1855-1916" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/wanlass-julia-sphia-phillips-1855-1916</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Wanlass, Julia Sphia Phillips 1855-1916</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/wanlass-julia-sphia-phillips-1855-1916</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/wanlass-julia-sphia-phillips-1855-1916</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
var mysql = require('mysql');

/**
 * A query builder
 *
 * @constructor
 */
var Query = function() {
	this.statement = null;
	this.values = [ ];
};

/**
 * Build a string with placeholders and the relative values
 * @param {Object<string, (string|number|boolean)>} hash
 * @param {string} values
 * @return {string}
 */
Query.prototype.hashToClause = function(hash, separator) {
    var placeholder = '';
    var first = true;
    for (var key in hash) {
        placeholder += (first ? '' : separator) + key + ' = ?';
        this.values.push(hash[key]);
        first = false;
    }
    return placeholder;
};

/**
 * Build a select query
 *
 * @param {Array.<string>|string} fields
 * @param {string} table
 * @return {Query}
 */
Query.select = function(fields, table) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	if (Array.isArray(fields))
		fields = fields.join(',');
	else
		fields = fields;
	var q = new Query();
	q.statement = 'SELECT ' + fields + ' FROM ??';
	q.values.push(table);
	return q;
};

/**
 * Build an insert query
 *
 * @param {string} table
 * @param {Object.<string, (string|number|boolean)>} fields
 * @return {Query}
 */
Query.insert = function(table, fields) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	var q = new Query();
	q.values.push(table);
	q.statement = 'INSERT INTO ?? SET ' + q.hashToClause(fields, ',');
	return q;
};

/**
 * Build an update query
 *
 * @param {string} table
 * @param {Object.<string, (string|number|boolean)>} fields
 * @return {Query}
 */
Query.update = function(table, fields) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	var q = new Query();
	q.values.push(table);
	q.statement = 'UPDATE ?? SET ' + q.hashToClause(fields, ',');
	return q;
};

/**
 * Build a select count query
 *
 * @param {string} table
 * @return {Query}
 */
Query.count = function(table) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	var q = new Query();
	q.statement = 'SELECT COUNT(*) as count FROM ??';
	q.values.push(table);
	return q;
};

/**
 * Build a delete query
 *
 * @param {string} table
 * @return {Query}
 */
Query.delete = function(table) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	var q = new Query();
	q.statement = 'DELETE FROM ??';
	q.values.push(table);
	return q;
};

/**
 * Append a WHERE IN clause using the query to this query
 *
 * @param {string} field
 * @param {Query|string}
 * @return {Query}
 */
Query.prototype.whereIn = function(field, query) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.statement += ' WHERE ' + field + ' IN (';
	if (typeof query == 'string')
		this.statement += query + ')';
	else {
		this.values = this.values.concat(query.values);
		this.statement += query.statement + ')';
	}
	return this;
};

/**
 * Append a WHERE clause to this query
 *
 * @param {Object<string, (string|number|boolean)>|string} condition
 * @return {Query}
 */
Query.prototype.where = function(condition) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.statement += ' WHERE ';
	if (typeof condition == 'string')
		this.statement += condition;
	else
		this.statement += this.hashToClause(condition, ' AND ');
	return this;
};

/**
 * Append a INNER JOIN clause to this query
 *
 * @param {string} table
 * @param {Object<string, (string|number|boolean)>|string} condition
 * @return {Query}
 */
Query.prototype.innerJoin = function(table, condition) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.values.push(table);
	this.statement += ' INNER JOIN ?? ON ';
	if (typeof condition == 'string')
		this.statement += condition;
	else
		this.statement += this.hashToClause(condition, ' AND ');
	return this;
};

Query.prototype.join = Query.prototype.innerJoin;

/**
 * Append a OUTER JOIN clause to this query (left by default)
 *
 * @param {string} table
 * @param {Object<string, (string|number|boolean)>|string} condition
 * @param {boolean=} right
 * @return {Query}
 */
Query.prototype.outerJoin = function(table, condition, right) {
	if (arguments.length < 2)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.values.push(table);
	this.statement += (right ? ' RIGHT ' : ' LEFT ') + 'JOIN ?? ON ';
	if (typeof condition == 'string')
		this.statement += condition;
	else
		this.statement += this.hashToClause(condition, ' AND ');
	return this;
};

/**
 * Append an ORDER BY clause to this query
 *
 * @param {string} by
 * @param {boolean=} desc
 * @return {Query}
 */
Query.prototype.orderby = function(by, desc) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.statement += ' ORDER BY ' + by + (desc ? ' DESC' : ' ASC');
	return this;
};

/**
 * Append an LIMIT clause to this query
 *
 * @param {number=} offset
 * @param {number} lines
 * @return {Query}
 */
Query.prototype.limit = function(offset, lines) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	if (this.statement == null)
		throw new Error('Missing statement');
	this.statement += ' LIMIT ' + offset;
	if (arguments.length != 1)
		this.statement += ',' + lines;
	return this;
};

/**
 * Append a statement to this query statement
 *
 * @param {string} statement
 * @param {Array.<(string|number|boolean)>=} desc
 * @return {Query}
 */
Query.prototype.append = function(statement, values) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	this.statement += ' ' + statement;
	if (values)
		this.values.push(values);
	return this;
};

/**
 * Return the formatted final query
 *
 * @return {string}
 */
Query.prototype.toString = function() {
	return mysql.format(this.statement, this.values);
};

/**
 * Execute the query, and call cb
 *
 * @param {mysql.Connection} connection
 * @param {Function=} cb
 */
Query.prototype.exec = function(connection, cb) {
	if (arguments.length < 1)
		throw new Error('Missing arguments');
	connection.query(this.statement, this.values, cb);
};

module.exports = Query;


text:
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import Blog from './containers/Blog'
import AboutPage from './containers/AboutPage'
import PostsPage from './containers/PostsPage'
import PostPage from './containers/PostPage'

export default <Route path='/' component={Blog}>
  <IndexRoute component={AboutPage} />
  <Route path='/blog' component={PostsPage} />
  <Route path='/portfolio' component={PostsPage} />
  <Route path='/posts/:post' component={PostPage} />
</Route>


text:
tq is command line utility  that performs an HTML element selection on HTML content passed to the stdin. Using css selectors that everybody knows.

Since input comes from stdin and output is sent to stdout, it can easily be used inside traditional UNIX pipelines to extract content from webpages and html files.

tq provides extra formating options such as json-encoding or newlines squashing, so it can play nicely with everyones favourite command line tooling.

## Installation

	sudo pip3 install https://github.com/plainas/tq/zipball/stable

## Example usage

Get headlines from hacker news

	curl https://news.ycombinator.com/news | tq -tj ".title a"

Get the title of an html document stored in a file

	cat mydocument.html | tq -t title

Get all the images from a webpage

	curl -s 'http://example.com/' | tq  "img" -a src | wget -i -

Notice that tq doesn't provide a way to make http requests or read files. You can use your favorite HTTP client, or provide the html source from any source you want.

For a modern, user friendly http client, check httpie. Or you can just use curl, wget, netcat, etc.

## Command options

  * `SELECTOR`
    A css selector

  * `-a ATTRIBUTE --attr=ATTRIBUTE`
    Outputs only the contents of the html ATTRIBUTE.

  * `-t, --text`
    Outputs only the inner text of the selected elements.

  * `-p, --parent`
    Select the parent elements instead.

  * `-q, --squash`
    Squash lines.

  * `-s, --squash-space`
    Squash spaces.

  * `-j, --json-lines`
    JSON encode each match.

  * `-J, --json`
    Output as json array of strings.

  * `-v, --version`
    Prints tq version


text:
layout: page
title: "Rodger Kram"
comments: true
description: "blanks"
keywords: "Rodger Kram,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: IPHY 3410, IPHY 4540, IPHY 4660, IPHY 5100, IPHY 6020, IPHY 6660

#### IPHY 3410: Introduction to Human Anatomy

**Terms taught**: Spring 2014, Spring 2015

**Instructor rating**: 5.26

**Standard deviation in instructor rating**: 0.12

**Average grade** (4.0 scale): 2.55

**Standard deviation in grades** (4.0 scale): 0.01

**Average workload** (raw): 2.82

**Standard deviation in workload** (raw): 0.13

#### IPHY 4540: Biomechanics

**Terms taught**: Fall 2006, Fall 2007, Fall 2009, Fall 2010, Fall 2011, Spring 2012, Fall 2012, Spring 2016

**Instructor rating**: 5.26

**Standard deviation in instructor rating**: 0.54

**Average grade** (4.0 scale): 3.16

**Standard deviation in grades** (4.0 scale): 0.12

**Average workload** (raw): 3.47

**Standard deviation in workload** (raw): 0.15

#### IPHY 4660: CT-MYTHBUST/PHYSI/BIOMEC

**Terms taught**: Spring 2007, Fall 2007

**Instructor rating**: 5.43

**Standard deviation in instructor rating**: 0.13

**Average grade** (4.0 scale): 3.44

**Standard deviation in grades** (4.0 scale): 0.17

**Average workload** (raw): 2.79

**Standard deviation in workload** (raw): 0.09

#### IPHY 5100: Colloquium in Integrative Physiology

**Terms taught**: Fall 2010, Fall 2014

**Instructor rating**: 5.7

**Standard deviation in instructor rating**: 0.02

**Average grade** (4.0 scale): 3.97

**Standard deviation in grades** (4.0 scale): 0.02

**Average workload** (raw): 1.39

**Standard deviation in workload** (raw): 0.18

#### IPHY 6020: SEMINAR

**Terms taught**: Spring 2010

**Instructor rating**: 5.38

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.77

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.57

**Standard deviation in workload** (raw): 0.0

#### IPHY 6660: Locomotion Energetics and Biomechanics

**Terms taught**: Fall 2014

**Instructor rating**: 5.82

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 4.0

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.11

**Standard deviation in workload** (raw): 0.0


text:
layout: page
title: Talks
permalink: /t/
---

Update: for an update list of talks, vist my [LinkedIn](https://www.linkedin.com/in/emadehsan/).

List of most of my talks at various Tech Community events and conferences. Since following is more a log of the talks than a written version of them, that's why I've written the name of conferences in title.
* [Cloud DevFest 19 - Kuala Lumpur](/t/kuala-lumpur-1)
* [DevFest Tashkent 2019](/t/tashkent-1)
* [DSC Summit Pakistan - Islamabad](/t/islamabad-2)
* [Facebook Developers Circle Lahore](/t/lahore-4)
* [e-Rozgaar Headquarters - Lahore](/t/lahore-3)
* [Punjab University - e-Rozgaar Center](/t/lahore-2)
* [Lahore College for Women University e-Rozgaar Center](/t/lahore-1)
* [Cloud Next Extended 19 - Islamabad](/t/islamabad-1)


text:
module SyntheticWeb.Client.ByteCountedConnection
    ( openByteCountedConnection
    , withByteCountedConnection
    ) where

import Control.Exception (bracket)
import Network.Http.Client ( Connection
                           , Hostname
                           , Port
                           , closeConnection
                           , connectSocket
                           , makeConnection
                           , modifyHostname )
import Network.Socket (close)
import SyntheticWeb.Counter.ByteCounter (ByteCounter (..))
import qualified System.IO.Streams as Streams
import GHC.Int (Int64)

type ByteCountedConnection = (Connection, IO Int64, IO Int64)

-- | Open a byte counted connection. Before the connection is closed
-- the number of bytes for download and upload can be read from the IO
-- actions.
openByteCountedConnection :: Hostname -> Port -> IO ByteCountedConnection
openByteCountedConnection host port = do
  sock         <- connectSocket host port return
  streams      <- Streams.socketToStreams sock
  (ins, inc)   <- Streams.countInput (fst streams)
  (outs, outc) <- Streams.countOutput (snd streams)
  conn         <- makeConnection (modifyHostname host port) (close sock)
                                 outs ins
  return (conn, inc, outc)

-- | Execute an action using the byte counted connection. Return the
-- result from the action and a byte counter with the count.
withByteCountedConnection :: IO ByteCountedConnection
                          -> (Connection -> IO a)
                          -> IO (a, ByteCounter)
withByteCountedConnection mkConnection action =
    bracket mkConnection
            (\(conn, _, _) -> closeConnection conn)
            (\(conn, inc, outc) -> do
               res <- action conn
               cnt <- ByteCounter <$> inc <*> outc
               return (res, cnt))


text:
Documentation to integrate a game using eole-api and eole-angular.

## Install Eole locally

You'll need

- git
- docker
- docker-compose

Clone both eole-api and eole-angular repositories.

``` bash
git clone git@github.com:eole-io/eole-api.git
git clone git@github.com:eole-io/eole-angular.git
```

Then, run `make` in each of them.

``` bash
cd eole-api/
make
cd ../

cd eole-angular/
make
cd ../
```

> **Note**:
> You'll probably need to run in `eole-api/`:
>
> `chown -R GROUP:USER .` and/or `chown -R 777 var/cache var/logs var/oauth-tokens`

The install is done.

## Default urls

Using default docker configuration, you'll have access to each of them urls:

What                               | url
---------------------------------- | -----------------------------
Eole front application             | [http://0.0.0.0:8580](http://0.0.0.0:8580)
Eole Api                           | [http://0.0.0.0:8480/api-docker.php/api/games](http://0.0.0.0:8480/api-docker.php/api/games)
Api Symfony profiler               | [http://0.0.0.0:8480/api-docker.php/_profiler/](http://0.0.0.0:8480/api-docker.php/_profiler/)
PHPMyAdmin (`root` / `root`)       | [http://0.0.0.0:8481](http://0.0.0.0:8481)
Websocket server                   | ws://0.0.0.0:8482

## Cookbook

1. [Initialize my game](initialize)

### Back

1. [Create a RestApi endpoint](create-rest-api-endpoint)
1. [Allow more players to join](allow-more-players-to-join)

### Front

1. [Calling Eole Api](calling-eole-api)


text:
#nullable enable

namespace Snittlistan.Queue;

public record MessageQueueProcessorSettings(
    string ReadQueue,
    string ErrorQueue,
    int WorkerThreadCount,
    bool AutoCreateQueues,
    bool DropFailedMessages);


text:
## Examples:

### Heat Map
![Heat Map](https://github.com/Sufflavus/D3Examples/blob/master/5_HeatMap/results/1.png)

### Heat Map with tooltip
![Heat Map with tooltip](https://github.com/Sufflavus/D3Examples/blob/master/5_HeatMap/results/2.png)


text:
Select a Category:

<button ng-repeat="category in categories track by $index" ng-click="categorySelected(category)" class="main-button">
	{{category.categoryname}}
</button>