Request A
 TODO: Instead of pre-parsing and casting everything, refactor this so that only the response string gets saved, and  parse out values that are accessed.
176731
def request_a

      # 2F 3F 12 Bytes Address 30 30 21 0D 0A
      # /?00000000012300! then a CRLF
      request = "/?" + meter_number + "00!\r\n"
      read_bytes = 255
      @logger.debug "Socket write #{request}"
      response = get_remote_meter_data(request, read_bytes)

      if response.nil?
        @logger.error "No response to request_a from meter #{meter_number}"
        raise EkmOmnimeter, "No response from meter."
      end

      # Split the response string into an array and prepare a hash to store the values
      a = response.split('')
      d = {}

      # Return (255 Bytes total) :
      a.shift(1)                               # 02
      d[:meter_type] = a.shift(2)              # 2 Byte Meter Type
      d[:meter_firmware] = a.shift(1)          # 1 Byte Meter Firmware
      d[:address] = a.shift(12)                # 12 Bytes Address
      d[:total_kwh] = a.shift(8)               # 8 Bytes total Active kWh
      d[:reactive_kwh_kvarh] = a.shift(8)      # 8 Bytes Total kVARh
      d[:total_reverse_kwh] = a.shift(8)       # 8 Bytes Total Rev.kWh

      # 24 Bytes 3 phase kWh
      d[:total_kwh_l1] = a.shift(8)
      d[:total_kwh_l2] = a.shift(8)
      d[:total_kwh_l3] = a.shift(8)
      # 24 Bytes 3 phase Rev.kWh
      d[:reverse_kwh_l1] = a.shift(8)
      d[:reverse_kwh_l2] = a.shift(8)
      d[:reverse_kwh_l3] = a.shift(8)

      d[:resettable_total_kwh] = a.shift(8)    # 8 Bytes Resettable kWh
      d[:resettable_reverse_kwh] = a.shift(8)  # 8 bytes Resettable Reverse kWh
      d[:volts_l1] = a.shift(4)                # 4 Bytes Volts L1
      d[:volts_l2] = a.shift(4)                # 4 Bytes Volts L2
      d[:volts_l3] = a.shift(4)                # 4 Bytes Volts L3
      d[:amps_l1] = a.shift(5)                 # 5 Bytes Amps L1
      d[:amps_l2] = a.shift(5)                 # 5 Bytes Amps L2
      d[:amps_l3] = a.shift(5)                 # 5 Bytes Amps L3
      d[:watts_l1] = a.shift(7)                # 7 Bytes Watts L1
      d[:watts_l2] = a.shift(7)                # 7 Bytes Watts L2
      d[:watts_l3] = a.shift(7)                # 7 Bytes Watts L3
      d[:watts_total] = a.shift(7)             # 7 Bytes Watts Total
      d[:power_factor_1] = a.shift(4)          # 4 Bytes Cosϴ L1
      d[:power_factor_2] = a.shift(4)          # 4 Bytes Cosϴ L2
      d[:power_factor_3] = a.shift(4)          # 4 Bytes Cosϴ L3
      d[:reactive_power_1] = a.shift(7)        # 7 Bytes VAR L1
      d[:reactive_power_2] = a.shift(7)        # 7 Bytes VAR L2
      d[:reactive_power_3] = a.shift(7)        # 7 Bytes VAR L3
      d[:total_reactive_power] = a.shift(7)    # 7 Bytes VAR Total
      d[:frequency] = a.shift(4)               # 4 Bytes Freq
      d[:pulse_1_count] = a.shift(8)           # 8 Bytes Pulse Count 1
      d[:pulse_2_count] = a.shift(8)           # 8 Bytes Pulse Count 2
      d[:pulse_3_count] = a.shift(8)           # 8 Bytes Pulse Count 3
      d[:pulse_input_hilo] = a.shift(1)        # 1 Byte Pulse Input Hi/Lo
      d[:direction_of_current] = a.shift(1)    # 1 Bytes direction of current
      d[:outputs_onoff] = a.shift(1)           # 1 Byte Outputs On/Off
      d[:kwh_data_decimal_places] = a.shift(1) # 1 Byte kWh Data Decimal Places
      a.shift(2)                               # 2 Bytes Reserved
      meter_timestamp = a.shift(14).join('')   # 14 Bytes Current Time
      a.shift(6)                               # 30 30 21 0D 0A 03
      d[:checksum] = a.shift(2)                # 2 Bytes CRC16

      # Smash arrays into strungs
      d.each {|k,v| d[k] = v.join('')}

      # Verify that the checksum is correct
      verify_checksum(response, d[:checksum])

      # Cast types
      @values[:kwh_data_decimal_places] = d[:kwh_data_decimal_places].to_i
      d[:meter_type] = d[:meter_type].unpack('H*')[0]
      d[:meter_firmware] = d[:meter_firmware].unpack('H*')[0]
      d[:power_factor_1] = cast_power_factor(d[:power_factor_1])
      d[:power_factor_2] = cast_power_factor(d[:power_factor_2])
      d[:power_factor_3] = cast_power_factor(d[:power_factor_3])
      d[:meter_timestamp] = as_datetime(meter_timestamp)
      cast_response_to_correct_types(d)

      # Lookup mapped values
      d[:meter_type] = METER_TYPE_MAP[d[:meter_type]]
      d[:pulse_1_input], d[:pulse_2_input], d[:pulse_3_input] = PULSE_INPUT_STATE_MAP[d[:pulse_input_hilo]]
      d[:current_direction_l1], d[:current_direction_l2], d[:current_direction_l3] = DIRECTION_OF_CURRENT_MAP[d[:direction_of_current]]
      d[:output_1], d[:output_2] = OUTPUT_INDICATOR_MAP[d[:outputs_onoff]]

      # Merge to values and reset time
      @values.merge!(d)
      @last_read_timestamp = Time.now

      # Calculate totals based on wiring configuration
      @values[:volts] = calculate_measurement(volts_l1, volts_l2, volts_l3)
      @values[:amps]  = calculate_measurement(amps_l1, amps_l2, amps_l3)
      @values[:watts] = calculate_measurement(watts_l1, watts_l2, watts_l3)
      @values[:total_forward_kwh] = total_kwh - total_reverse_kwh
      @values[:net_kwh] = total_forward_kwh - total_reverse_kwh

      # Return the values returned by just this call (different than values)
      return d

    end
1121033
function apiResponded(apiResponse) {
      // Convert XML to JS object
      var parser = new xml2js.Parser({explicitArray:false});
      parser.parseString(apiResponse, function (err, result) {
        // If the method processes the response, give it back
        // Otherwise call the original callback

        if(typeof a.processor !== 'undefined')
          a.processor(result.response, a.callback);
        else
          a.callback(result.response);
      });


    }
754556
public GenericAnalyticsResponse parse() throws Exception {
        try {
            parser.parse();
            //discard only if EOF is not thrown
            responseContent.discardReadBytes();
            LOGGER.trace("Received last chunk and completed parsing for requestId {}", requestID);
        } catch (EOFException ex) {
            //ignore as we expect chunked responses
            LOGGER.trace("Still expecting more data for requestId {}", requestID);
        }

        //return back response only once
        if (!this.sentResponse && this.response != null) {
            this.sentResponse = true;
            return this.response;
        }

        return null;
    }
690326
function ajaxHandleResponses( s, jqXHR, responses ) {

	var contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields,
		ct,
		type,
		finalDataType,
		firstDataType;

	// Fill responseXXX fields
	for ( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}

	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}
1244259
private void checkResponseCode(String message) throws ResponseException {

        if (this.responseCode != 200 && this.responseCode != 204) {

            HashMap<Integer, String> responseCodes = new HashMap<Integer, String>() {{
                put(206, "PartialContent");
                put(400, "Bad request");
                put(401, "Unauthorized");
                put(403, "Prohibition to use the method");
                put(404, "Not found");
                put(405, "Method not allowed");
                put(413, "Request entity too large");
                put(422, "Unprocessable entity");
                put(500, "Internal server error");
                put(501, "Not implemented");
            }};

            ResponseException responseException = new ResponseException(message);
            responseException.setResponseHttpCode(this.responseCode);

            if (responseCodes.containsKey(this.responseCode)) {
                responseException.setResponseHttpDescription(responseCodes.get(this.responseCode));
            } else {
                responseException.setResponseHttpDescription("Unknown response error");
            }

            if (message != null) {
                JsonObject error = new JsonParser().parse(message).getAsJsonObject();
                for (Entry<String, JsonElement> entry : error.entrySet()) {

                    switch (entry.getKey().toLowerCase()) {
                        case "message":
                            responseException.setApiMessage(entry.getValue().getAsString());
                            break;
                        case "type":
                            responseException.setType(entry.getValue().getAsString());
                            break;
                        case "id":
                            responseException.setId(entry.getValue().getAsString());
                            break;
                        case "date":
                            responseException.setDate((int) entry.getValue().getAsDouble());
                            break;
                        case "errors":
                            if (entry.getValue() == null) break;

                            if (entry.getValue().isJsonNull()) break;

                            for (Entry<String, JsonElement> errorEntry : entry.getValue().getAsJsonObject().entrySet()) {
                                if (!responseException.getErrors().containsKey(errorEntry.getKey()))
                                    responseException.getErrors().put(errorEntry.getKey(), errorEntry.getValue().getAsString());
                                else {
                                    String description = responseException.getErrors().get(errorEntry.getKey());
                                    description = " | " + errorEntry.getValue().getAsString();

                                    responseException.getErrors().put(errorEntry.getKey(), description);
                                }
                            }
                            break;
                    }
                }
            }

            throw responseException;
        }
    }
162425
function(request){
			var response = {};
			if(Array.isArray(request) && request.length > 0){
				if(request.indexOf('all') > -1){
					response = getData('all');
				}
				else{
					for(var d = 0; d < request.length; d++){
						var prop = request[d];
						response[prop] = getData(prop);
					}
				}
			}
			else if(request){
				response = getData(request);
			}
			else{
				response = "BAD_REQUEST_EXCEPTION"
			}
			return response;
		}
324768
private String clientResponseToString(ClientResponse response) {
        if (response == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[status: ").append(response.getStatus());
        builder.append(", media type: ").append(response.getType());
        if (response.getStatus() != 404) {
            try {
                String responseBody = response.getEntity(String.class);
                if (responseBody != null) {
                    builder.append(", response body: ").append(responseBody);
                }
            } catch (RuntimeException ignore) {
                // Ignore if there is no response body, or IO error - it may have already been read in certain scenario.
            }
        }
        builder.append(", response headers: ").append(response.getHeaders());
        builder.append("]");
        return builder.toString();
    }
581890
function(res) {
    res.setEncoding('utf8');
    var data = "";
    res.on('data', function(chunk) {
      data+=chunk;
    });

    res.on('end', function() {
      // Get HTTP Statuscode and act according to situation
      var code = res.statusCode;
      try { // try to parse JSON
        var answer = JSON.parse(data);
      } catch (e) {
        var err = {};
        err.http_code = 500;
        err.message = "No valid JSON received: "+data;
        callback(err, null);
        return;
      }
      if(code >= 200 && code <= 206) { // request was successful
        callback(null, answer);
      } else if (code >= 300 && code <= 307) { // server send redirect
        // we do not follow anything the server wants us to follow right now, since this should never be the case.
        // instead let's raise an error.
        var err = new Object();
        err.http_code = 500;
        err.message = "Redirects not supported by pastyclient-node"
        callback(err, null);
      } else if (code >= 400 && code <= 418) { // client error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else if(answer.code != undefined && answer.message != undefined) { // New RestError, temporary support both 
          var err = answer;
          err.http_code = code;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Resource not found";
        }
        callback(err, null);
      } else if (code >= 500 && code <= 505) { // server error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Internal Server Error";
        }
        callback(err, null);
      } else {
        // Not existant HTTP code. Raise error.
        var err = new Object();
        err.http_code = 500;
        err.message = "HTTP Status Code "+code+" is not supported by pastyclient-node"
        callback(err, null);
      }
    });
  }
245886
def convert_response(response)
      HttpResponse.new(response.status, response.headers, response.body)
    end
440196
function () {
                // Read response state from the memoized partial data.
                var _a = partialFromXhr(), headers = _a.headers, status = _a.status, statusText = _a.statusText, url = _a.url;
                // The body will be read out if present.
                var body = null;
                if (status !== 204) {
                    // Use XMLHttpRequest.response if set, responseText otherwise.
                    body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
                }
                // Normalize another potential bug (this one comes from CORS).
                if (status === 0) {
                    status = !!body ? 200 : 0;
                }
                // ok determines whether the response will be transmitted on the event or
                // error channel. Unsuccessful status codes (not 2xx) will always be errors,
                // but a successful status code can still result in an error if the user
                // asked for JSON data and the body cannot be parsed as such.
                var ok = status >= 200 && status < 300;
                // Check whether the body needs to be parsed as JSON (in many cases the browser
                // will have done that already).
                if (req.responseType === 'json' && typeof body === 'string') {
                    // Save the original body, before attempting XSSI prefix stripping.
                    var originalBody = body;
                    body = body.replace(XSSI_PREFIX, '');
                    try {
                        // Attempt the parse. If it fails, a parse error should be delivered to the user.
                        body = body !== '' ? JSON.parse(body) : null;
                    }
                    catch (error) {
                        // Since the JSON.parse failed, it's reasonable to assume this might not have been a
                        // JSON response. Restore the original body (including any XSSI prefix) to deliver
                        // a better error response.
                        body = originalBody;
                        // If this was an error request to begin with, leave it as a string, it probably
                        // just isn't JSON. Otherwise, deliver the parsing error to the user.
                        if (ok) {
                            // Even though the response status was 2xx, this is still an error.
                            ok = false;
                            // The parse error contains the text of the body that failed to parse.
                            body = { error: error, text: body };
                        }
                    }
                }
                if (ok) {
                    // A successful response is delivered on the event stream.
                    observer.next(new HttpResponse({
                        body: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                    // The full body has been received and delivered, no further events
                    // are possible. This request is complete.
                    observer.complete();
                }
                else {
                    // An unsuccessful request is delivered on the error channel.
                    observer.error(new HttpErrorResponse({
                        // The error in this case is the response body (error from the server).
                        error: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                }
            }
678639
@SuppressWarnings("unused")
    final void handleHeaderValue(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
        StringBuilder stringBuilder = state.stringBuilder;
        if (stringBuilder == null) {
            stringBuilder = new StringBuilder();
            state.parseState = 0;
        }

        int parseState = state.parseState;
        while (buffer.hasRemaining()) {
            final byte next = buffer.get();
            switch (parseState) {
                case NORMAL: {
                    if (next == '\r') {
                        parseState = BEGIN_LINE_END;
                    } else if (next == '\n') {
                        parseState = LINE_END;
                    } else if (next == ' ' || next == '\t') {
                        parseState = WHITESPACE;
                    } else {
                        stringBuilder.append((char) next);
                    }
                    break;
                }
                case WHITESPACE: {
                    if (next == '\r') {
                        parseState = BEGIN_LINE_END;
                    } else if (next == '\n') {
                        parseState = LINE_END;
                    } else if (next == ' ' || next == '\t') {
                    } else {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append(' ');
                        }
                        stringBuilder.append((char) next);
                        parseState = NORMAL;
                    }
                    break;
                }
                case LINE_END:
                case BEGIN_LINE_END: {
                    if (next == '\n' && parseState == BEGIN_LINE_END) {
                        parseState = LINE_END;
                    } else if (next == '\t' ||
                            next == ' ') {
                        //this is a continuation
                        parseState = WHITESPACE;
                    } else {
                        //we have a header
                        HttpString nextStandardHeader = state.nextHeader;
                        String headerValue = stringBuilder.toString();

                        //TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
                        builder.getResponseHeaders().add(nextStandardHeader, headerValue);

                        state.nextHeader = null;

                        state.leftOver = next;
                        state.stringBuilder.setLength(0);
                        if (next == '\r') {
                            parseState = AWAIT_DATA_END;
                        } else {
                            state.state = ResponseParseState.HEADER;
                            state.parseState = 0;
                            return;
                        }
                    }
                    break;
                }
                case AWAIT_DATA_END: {
                    state.state = ResponseParseState.PARSE_COMPLETE;
                    return;
                }
            }
        }
        //we only write to the state if we did not finish parsing
        state.parseState = parseState;
    }
10815
def _serialize(self):
        

        # Do something appropriate if the response object is unbound
        if self._defcode is None:
            raise exceptions.UnboundResponse()

        # Build the response
        resp = self.response_class(request=self.req, status=self.code,
                                   headerlist=self._headers.items())

        # Do we have a body?
        if self.result:
            resp.content_type = self.content_type
            resp.body = self.serializer(self.result)

        # Return the response
        return resp
37724
function(originalResponse, successful) {
            var response = originalResponse;

            // The passed "response" param may not be a response at all.
            // It could be a string, detailing the error, for example.
            if (!qq.isObject(originalResponse)) {
                response = {};

                if (qq.isString(originalResponse) && !successful) {
                    response.error = originalResponse;
                }
            }

            response.success = successful;

            return response;
        }
1221100
@Override
	public String asString() {
		ByteArrayOutputStream result = new ByteArrayOutputStream(getIntContentLength(this.response));
		saveTo(result);
		return result.toString();
	}
1013732
private <T, E> void parseAndCallback(
      RequestInfo<T, E> requestInfo, int statusCode, HttpResponse response)
      throws IOException {
    BatchCallback<T, E> callback = requestInfo.callback;

    HttpHeaders responseHeaders = response.getHeaders();
    HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler =
        requestInfo.request.getUnsuccessfulResponseHandler();

    if (HttpStatusCodes.isSuccess(statusCode)) {
      if (callback == null) {
        // No point in parsing if there is no callback.
        return;
      }
      T parsed = getParsedDataClass(requestInfo.dataClass, response, requestInfo);
      callback.onSuccess(parsed, responseHeaders);
    } else {
      HttpContent content = requestInfo.request.getContent();
      boolean retrySupported = retryAllowed && (content == null || content.retrySupported());
      boolean errorHandled = false;
      boolean redirectRequest = false;
      if (unsuccessfulResponseHandler != null) {
        errorHandled = unsuccessfulResponseHandler.handleResponse(
            requestInfo.request, response, retrySupported);
      }
      if (!errorHandled) {
        if (requestInfo.request.handleRedirect(response.getStatusCode(), response.getHeaders())) {
          redirectRequest = true;
        }
      }
      if (retrySupported && (errorHandled || redirectRequest)) {
        unsuccessfulRequestInfos.add(requestInfo);
      } else {
        if (callback == null) {
          // No point in parsing if there is no callback.
          return;
        }
        E parsed = getParsedDataClass(requestInfo.errorClass, response, requestInfo);
        callback.onFailure(parsed, responseHeaders);
      }
    }
  }
495886
def dump_request_and_response(self, response):
        
        if response.reason is None:
            response.reason = "<unknown>"
        return d1_client.util.normalize_request_response_dump(
            requests_toolbelt.utils.dump.dump_response(response)
        )
716196
private String _serialize(Object object, Map<Object, String> done) throws ConverterException {

	type = "OBJECT";

	String rtn;
	deep++;
	// NULL
	if (object == null) {
	    rtn = goIn() + "";
	    deep--;
	    type = "NULL";
	    return rtn;
	}
	// String
	if (object instanceof String) {
	    rtn = goIn() + XMLUtil.escapeXMLString(object.toString());
	    deep--;
	    type = "STRING";
	    return rtn;
	}
	// Number
	if (object instanceof Number) {
	    rtn = goIn() + ((Number) object).doubleValue();
	    deep--;
	    type = "NUMBER";
	    return rtn;
	}
	// Boolean
	if (object instanceof Boolean) {
	    rtn = goIn() + ((Boolean) object).booleanValue();
	    deep--;
	    type = "BOOLEAN";
	    return rtn;
	}
	// DateTime
	if (object instanceof DateTime) {
	    rtn = _serializeDateTime((DateTime) object);
	    deep--;
	    type = "DATE";
	    return rtn;
	}
	// Date
	if (object instanceof Date) {
	    rtn = _serializeDate((Date) object);
	    deep--;
	    type = "DATE";
	    return rtn;
	}

	Object raw = LazyConverter.toRaw(object);
	String strId = done.get(raw);
	if (strId != null) {
	    rtn = goIn() + "<REF id=\"" + strId + "\"\\>";
	    deep--;
	    type = "NULL";
	    return rtn;
	}
	strId = Caster.toString(++this.id);
	done.put(raw, strId);
	try {
	    // Component
	    if (object instanceof Component) {
		rtn = _serializeComponent((Component) object, done);
		deep--;
		return rtn;
	    }
	    // Struct
	    if (object instanceof Struct) {
		rtn = _serializeStruct((Struct) object, done, strId);
		deep--;
		return rtn;
	    }
	    // Map
	    if (object instanceof Map) {
		rtn = _serializeMap((Map) object, done);
		deep--;
		return rtn;
	    }
	    // Array
	    if (object instanceof Array) {
		rtn = _serializeArray((Array) object, done, strId);
		deep--;
		return rtn;
	    }
	    // List
	    if (object instanceof List) {
		rtn = _serializeList((List) object, done, strId);
		deep--;
		return rtn;
	    }
	    // Query
	    if (object instanceof Query) {
		rtn = _serializeQuery((Query) object, done, strId);
		deep--;
		return rtn;
	    }
	}
	finally {
	    done.remove(raw);
	}
	// Others
	rtn = "<STRUCT ID=\"" + strId + "\" TYPE=\"" + Caster.toTypeName(object) + "\"></STRUCT>";
	deep--;
	return rtn;
    }