Helper function to format data returned by AWS EC2 queries.
545941
function dataFormatter(data) {
	var instanceInfoArray = [];
	var instanceInfoObject = {};

	var reservations = data.Reservations;
	for (var reservation in reservations) {
		var instances = reservations[reservation].Instances;
		for (var instance in instances) {
			var tags = instances[instance].Tags;
			for (var tag in tags) {
				if (tags[tag].Key === 'Name') {
					instanceInfoObject = _.assign(instanceInfoObject,
					{Name: tags[tag].Value});
				}
			}
			instanceInfoObject = _.assign(instanceInfoObject,
				{State: instances[instance].State.Name},
				{id: instances[instance].InstanceId});
			instanceInfoArray.push(instanceInfoObject);
			instanceInfoObject = {};
		}
	}
	return Promise.resolve(instanceInfoArray);
}
1245650
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
                     **keywords):
        
        if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
            raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))

        # Check for duplicate keywords
        kw_lower = set(x.lower() for x in keywords)
        if (len(kw_lower) != len(keywords) or
                (date is not None and 'beginposition' in kw_lower) or
                (area is not None and 'footprint' in kw_lower)):
            raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")

        query_parts = []

        if date is not None:
            keywords['beginPosition'] = date

        for attr, value in sorted(keywords.items()):
            # Escape spaces, where appropriate
            if isinstance(value, string_types):
                value = value.strip()
                if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
                    value = re.sub(r'\s', r'\ ', value, re.M)

            # Handle date keywords
            # Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
            date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
            if attr.lower() in date_attrs:
                # Automatically format date-type attributes
                if isinstance(value, string_types) and ' TO ' in value:
                    # This is a string already formatted as a date interval,
                    # e.g. '[NOW-1DAY TO NOW]'
                    pass
                elif not isinstance(value, string_types) and len(value) == 2:
                    value = (format_query_date(value[0]), format_query_date(value[1]))
                else:
                    raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
                                     "of str or datetime objects. Received {}".format(attr, value))

            # Handle ranged values
            if isinstance(value, (list, tuple)):
                # Handle value ranges
                if len(value) == 2:
                    # Allow None to be used as a unlimited bound
                    value = ['*' if x is None else x for x in value]
                    if all(x == '*' for x in value):
                        continue
                    value = '[{} TO {}]'.format(*value)
                else:
                    raise ValueError("Invalid number of elements in list. Expected 2, received "
                                     "{}".format(len(value)))

            query_parts.append('{}:{}'.format(attr, value))

        if raw:
            query_parts.append(raw)

        if area is not None:
            query_parts.append('footprint:"{}({})"'.format(area_relation, area))

        return ' '.join(query_parts)
1148302
def _build_query_dict(self, formdata=None):
        
        if self.is_valid() and formdata is None:
            formdata = self.cleaned_data
        key = "{field}__{operator}".format(**formdata)
        if formdata['operator'] == "isnull":
            return {key: None}
        elif formdata['operator'] == "istrue":
            return {formdata['field']: True}
        elif formdata['operator'] == "isfalse":
            return {formdata['field']: False}
        return {key: formdata['value']}
803073
def format_response_data_type(self, response_data):
        
        if isinstance(response_data, list) and not isinstance(
            response_data, str
        ):
            return response_data

        int_match_str = "|".join(self.config["response_format"]["int"])
        float_match_str = "|".join(self.config["response_format"]["float"])
        for item in response_data:
            for key in item:
                try:
                    if re.search(int_match_str, key) is not None:
                        item[key] = helpers.str2num(item[key], "int")
                    elif re.search(float_match_str, key) is not None:
                        item[key] = helpers.str2num(item[key], "float")
                except ValueError:
                    continue
        return response_data
727798
def _format_json(self, ans, q):
        
        params = {}
        try: params['indent'] = int(q.get('indent')[0])
        except: pass

        return json.dumps(ans, **params)+'\n'
559921
def format_value(field_info, value, section):
    """"""
    if section == "FORMAT" and field_info.id == "FT":
        if not value:
            return "."
        elif isinstance(value, list):
            return ";".join(map(format_atomic, value))
    elif field_info.number == 1:
        if value is None:
            return "."
        else:
            return format_atomic(value)
    else:
        if not value:
            return "."
        else:
            return ",".join(map(format_atomic, value))
943962
def format_result(input):
        
        items = list(iteritems(input))
        return OrderedDict(sorted(items, key=lambda x: x[0]))
711931
def build_query_string(self, data):
        
        query_params = []
        keys_to_be_removed = []
        for key, value in data.items():
            if key not in ['version', 'restApi', 'resourcePath']:
                if key == 'addressLine':
                    query_params.append('{0}={1}'.format(key,
                                                         quote(value)))
                    keys_to_be_removed.append(key)
                else:
                    query_params.append('{0}={1}'.format(key,
                                                         value))
                    keys_to_be_removed.append(key)
        data['query'] = "&".join(query_params)
        for k in keys_to_be_removed:
            del data[k]
        return data
4648
def formatted(self):
        """"""
        return ' '.join(self.compact[i:i + 4] for i in range(0, len(self.compact), 4))
163708
def formatDateQuery(context, date_id):
    
    from_date = context.REQUEST.get('%s_fromdate' % date_id, None)
    if from_date:
        from_date = from_date + ' 00:00'
    to_date = context.REQUEST.get('%s_todate' % date_id, None)
    if to_date:
        to_date = to_date + ' 23:59'

    date_query = {}
    if from_date and to_date:
        date_query = {'query': [from_date, to_date],
                      'range': 'min:max'}
    elif from_date or to_date:
        date_query = {'query': from_date or to_date,
                      'range': from_date and 'min' or 'max'}

    return date_query
1223573
function FormatQRY(query) { 
						var R = '', Q = query; switch(true) {
							case THS.QisFunction: return CleanQRY(Q.toString());
							case THS.QisArray: return Q.join("\n").replace("\t","");
							default: return R;
						};
					}
1060870
def _format(self, method="sparql", dt_format="turtle"):
        

        try:
            return __FORMAT_OPTIONS__[method](self, dt_format=dt_format)
        except KeyError:
            raise NotImplementedError("'{}' is not a valid format method"
                                      "".format(method))
1190486
def format(self):
        """"""
        self._netrc.hosts = dedictify_machines(self.machines)
        rep = ""
        for host in self._netrc.hosts.keys():
            attrs = self._netrc.hosts[host]
            rep += "machine {host}\n\tlogin {attrs[0]}\n".format(host=host,
                                                                 attrs=attrs)
            if attrs[1]:
                rep += "\taccount {attrs[1]}\n".format(attrs=attrs)
            rep += "\tpassword {attrs[2]}\n".format(attrs=attrs)
        for macro in self._netrc.macros.keys():
            rep += "macdef {macro}\n".format(macro=macro)
            for line in self._netrc.macros[macro]:
                rep += line
            rep += "\n"
        return rep
97983
def format_data(data):
    
    if data is None:
        return None
    return u":".join([u"{:02x}".format(ord(c)) for c in data])
1372381
def _format_return_data(retcode, stdout=None, stderr=None):
    '''
    
    '''
    ret = {'retcode': retcode}
    if stdout is not None:
        ret['stdout'] = stdout
    if stderr is not None:
        ret['stderr'] = stderr
    return ret
485615
def formatted(self, include_server_time):
        
        if include_server_time:  # pylint: disable=no-else-return
            return ('{0:5d} {1:5d} '
                    '{2:7.3f} {3:7.3f} {4:7.3f} '
                    '{5:7.3f} {6:7.3f} {7:7.3f} '
                    '{8:6.0f} {9:6.0f} {10:6.0f} '
                    '{11:8.0f} {12:8.0f} {13:8.0f} {14}\n'.
                    format(self.count, self.exception_count,
                           self.avg_time, self.min_time, self.max_time,
                           self.avg_server_time, self.min_server_time,
                           self.max_server_time,
                           self.avg_request_len, self.min_request_len,
                           self.max_request_len,
                           self.avg_reply_len, self.min_reply_len,
                           self.max_reply_len,
                           self.name))
        else:
            return ('{0:5d} {1:5d} '
                    '{2:7.3f} {3:7.3f} {4:7.3f} '
                    '{5:6.0f} {6:6.0f} {7:6.0f} '
                    '{8:6.0f} {9:8.0f} {10:8.0f} {11}\n'.
                    format(self.count, self.exception_count,
                           self.avg_time, self.min_time, self.max_time,
                           self.avg_request_len, self.min_request_len,
                           self.max_request_len,
                           self.avg_reply_len, self.min_reply_len,
                           self.max_reply_len,
                           self.name))
717634
def atlasdb_format_query( query, values ):
    
    return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] )