jsonpipe-0.0.8/0000755000175000017500000000000011571127622013162 5ustar domibeldomibeljsonpipe-0.0.8/src/0000755000175000017500000000000011571127622013751 5ustar domibeldomibeljsonpipe-0.0.8/src/jsonpipe/0000755000175000017500000000000011571127622015600 5ustar domibeldomibeljsonpipe-0.0.8/src/jsonpipe/sh.py0000644000175000017500000000431411571127622016566 0ustar domibeldomibelimport re import calabash import simplejson import jsonpipe as jp __all__ = ['jsonpipe', 'jsonunpipe', 'select', 'search_attr'] jsonpipe = calabash.pipe(jp.jsonpipe) @calabash.pipe def jsonunpipe(stdin, *args, **kwargs): """Calabash wrapper for :func:`jsonpipe.jsonunpipe`.""" yield jp.jsonunpipe(stdin, *args, **kwargs) @calabash.pipe def select(stdin, path, pathsep='/'): r""" Select only lines beginning with the given path. This effectively selects a single JSON object and all its sub-objects. >>> obj = {'a': 1, 'b': {'c': 3, 'd': 4}} >>> list(jsonpipe(obj)) ['/\t{}', '/a\t1', '/b\t{}', '/b/c\t3', '/b/d\t4'] >>> list(jsonpipe(obj) | select('/b')) ['/b\t{}', '/b/c\t3', '/b/d\t4'] >>> list(jsonpipe(obj) | select('/b') | jsonunpipe()) [{'b': {'c': 3, 'd': 4}}] """ path = re.sub(r'%s$' % re.escape(pathsep), r'', path) return iter(stdin | calabash.common.grep(r'^%s[\t%s]' % ( re.escape(path), re.escape(pathsep)))) @calabash.pipe def search_attr(stdin, attr, value, pathsep='/'): r""" Search stdin for an exact attr/value pair. Yields paths to objects for which the given pair matches. Example: >>> obj = {'a': 1, 'b': {'a': 2, 'c': {'a': "Hello"}}} >>> list(jsonpipe(obj) | search_attr('a', 1)) ['/'] >>> list(jsonpipe(obj) | search_attr('a', 2)) ['/b'] >>> list(jsonpipe(obj) | search_attr('a', "Hello")) ['/b/c'] Multiple matches will result in multiple paths being yielded: >>> obj = {'a': 1, 'b': {'a': 1, 'c': {'a': 1}}} >>> list(jsonpipe(obj) | search_attr('a', 1)) ['/', '/b', '/b/c'] """ return iter(stdin | # '...path/attribute\tvalue' => 'path'. calabash.common.sed(r'^(.*)%s%s\t%s' % ( re.escape(pathsep), re.escape(attr), re.escape(simplejson.dumps(value))), r'\1', exclusive=True) | # Replace empty strings with the root pathsep. calabash.common.sed(r'^$', pathsep)) jsonpipe-0.0.8/src/jsonpipe/__init__.py0000644000175000017500000000461211571127622017714 0ustar domibeldomibel# -*- coding: utf-8 -*- import sys import argparse import simplejson from pipe import jsonpipe, jsonunpipe __all__ = ['jsonpipe', 'jsonunpipe'] __version__ = '0.0.8' def _get_tests(): import doctest import inspect import sys import unittest import jsonpipe.sh def _from_module(module, object): """Backported fix for http://bugs.python.org/issue1108.""" if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): return module.__dict__ is object.func_globals elif inspect.isclass(object): return module.__name__ == object.__module__ elif hasattr(object, '__module__'): return module.__name__ == object.__module__ elif isinstance(object, property): return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") finder = doctest.DocTestFinder() finder._from_module = _from_module suite = unittest.TestSuite() for name, module in sys.modules.iteritems(): if name.startswith('jsonpipe'): try: mod_suite = doctest.DocTestSuite( module, test_finder=finder, optionflags=(doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS)) except ValueError: continue suite.addTests(mod_suite) return suite PARSER = argparse.ArgumentParser() PARSER.add_argument('-s', '--separator', metavar='SEP', default='/', help="Set a custom path component separator (default: /)") PARSER.add_argument('-v', '--version', action='version', version='%%(prog)s v%s' % (__version__,)) def main(): args = PARSER.parse_args() # Load JSON from stdin, preserving the order of object keys. json_obj = simplejson.load(sys.stdin, object_pairs_hook=simplejson.OrderedDict) for line in jsonpipe(json_obj, pathsep=args.separator): print line def main_unpipe(): args = PARSER.parse_args() simplejson.dump( jsonunpipe(iter(sys.stdin), pathsep=args.separator, decoder=simplejson.JSONDecoder( object_pairs_hook=simplejson.OrderedDict)), sys.stdout) jsonpipe-0.0.8/src/jsonpipe/pipe.py0000644000175000017500000001523611571127622017116 0ustar domibeldomibelimport simplejson __all__ = ['jsonpipe', 'jsonunpipe'] def jsonpipe(obj, pathsep='/', path=()): r""" Generate a jsonpipe stream for the provided (parsed) JSON object. This generator will yield output as UTF-8-encoded bytestrings line-by-line. These lines will *not* be terminated with line ending characters. The provided object can be as complex as you like, but it must consist only of: * Dictionaries (or subclasses of `dict`) * Lists or tuples (or subclasses of the built-in types) * Unicode Strings (`unicode`, utf-8 encoded `str`) * Numbers (`int`, `long`, `float`) * Booleans (`True`, `False`) * `None` Please note that, where applicable, *all* input must use either native Unicode strings or UTF-8-encoded bytestrings, and all output will be UTF-8 encoded. The simplest case is outputting JSON values (strings, numbers, booleans and nulls): >>> def pipe(obj): # Shim for easier demonstration. ... print '\n'.join(jsonpipe(obj)) >>> pipe(u"Hello, World!") / "Hello, World!" >>> pipe(123) / 123 >>> pipe(0.25) / 0.25 >>> pipe(None) / null >>> pipe(True) / true >>> pipe(False) / false jsonpipe always uses '/' to represent the top-level object. Dictionaries are displayed as ``{}``, with each key shown as a sub-path: >>> pipe({"a": 1, "b": 2}) / {} /a 1 /b 2 Lists are treated in much the same way, only the integer indices are used as the keys, and the top-level list object is shown as ``[]``: >>> pipe([1, "foo", 2, "bar"]) / [] /0 1 /1 "foo" /2 2 /3 "bar" Finally, the practical benefit of using hierarchical paths is that the syntax supports nesting of arbitrarily complex constructs: >>> pipe([{"a": [{"b": {"c": ["foo"]}}]}]) / [] /0 {} /0/a [] /0/a/0 {} /0/a/0/b {} /0/a/0/b/c [] /0/a/0/b/c/0 "foo" Because the sole separator of path components is a ``/`` character by default, keys containing this character would result in ambiguous output. Therefore, if you try to write a dictionary with a key containing the path separator, :func:`jsonpipe` will raise a :exc:`ValueError`: >>> pipe({"a/b": 1}) Traceback (most recent call last): ... ValueError: Path separator '/' present in key 'a/b' In more complex examples, some output may be written before the exception is raised. To mitigate this problem, you can provide a custom path separator: >>> print '\n'.join(jsonpipe({"a/b": 1}, pathsep=':')) : {} :a/b 1 The path separator should be a bytestring, and you are advised to use something you are almost certain will not be present in your dictionary keys. """ def output(string): return pathsep + pathsep.join(path) + "\t" + string if is_value(obj): yield output(simplejson.dumps(obj)) raise StopIteration # Stop the generator immediately. elif isinstance(obj, dict): yield output('{}') iterator = obj.iteritems() elif hasattr(obj, '__iter__'): yield output('[]') iterator = enumerate(obj) else: raise TypeError("Unsupported type for jsonpipe output: %r" % type(obj)) for key, value in iterator: # Check the key for sanity. key = to_str(key) if pathsep in key: # In almost any case this is not what the user wants; having # the path separator in the key would create ambiguous output # so we should fail loudly and as quickly as possible. raise ValueError("Path separator %r present in key %r" % (pathsep, key)) for line in jsonpipe(value, pathsep=pathsep, path=path + (key,)): yield line def jsonunpipe(lines, pathsep='/', discard='', decoder=simplejson._default_decoder): r""" Parse a stream of jsonpipe output back into a JSON object. >>> def unpipe(s): # Shim for easier demonstration. ... print repr(jsonunpipe(s.strip().splitlines())) Works as expected for simple JSON values:: >>> unpipe('/\t"abc"') 'abc' >>> unpipe('/\t123') 123 >>> unpipe('/\t0.25') 0.25 >>> unpipe('/\tnull') None >>> unpipe('/\ttrue') True >>> unpipe('/\tfalse') False And likewise for more complex objects:: >>> unpipe(''' ... /\t{} ... /a\t1 ... /b\t2''') {'a': 1, 'b': 2} >>> unpipe(''' ... /\t[] ... /0\t{} ... /0/a\t[] ... /0/a/0\t{} ... /0/a/0/b\t{} ... /0/a/0/b/c\t[] ... /0/a/0/b/c/0\t"foo"''') [{'a': [{'b': {'c': ['foo']}}]}] Any level in the path left unspecified will be assumed to be an object:: >>> unpipe(''' ... /a/b/c\t123''') {'a': {'b': {'c': 123}}} """ def parse_line(line): path, json = line.rstrip().split('\t') return path.split(pathsep)[1:], decoder.decode(json) def getitem(obj, index): if isinstance(obj, (list, tuple)): return obj[int(index)] # All non-existent keys are assumed to be an object. if index not in obj: obj[index] = decoder.decode('{}') return obj[index] def setitem(obj, index, value): if isinstance(obj, list): index = int(index) if len(obj) == index: obj.append(value) return obj[index] = value output = decoder.decode('{}') for line in lines: path, obj = parse_line(line) if path == ['']: output = obj continue setitem(reduce(getitem, path[:-1], output), path[-1], obj) return output def to_str(obj): ur""" Coerce an object to a bytestring, utf-8-encoding if necessary. >>> to_str("Hello World") 'Hello World' >>> to_str(u"H\xe9llo") 'H\xc3\xa9llo' """ if isinstance(obj, unicode): return obj.encode('utf-8') elif hasattr(obj, '__unicode__'): return unicode(obj).encode('utf-8') return str(obj) def is_value(obj): """ Determine whether an object is a simple JSON value. The phrase 'simple JSON value' here means one of: * String (Unicode or UTF-8-encoded bytestring) * Number (integer or floating-point) * Boolean * `None` """ return isinstance(obj, (str, unicode, int, long, float, bool, type(None))) jsonpipe-0.0.8/UNLICENSE0000644000175000017500000000227311571127622014436 0ustar domibeldomibelThis is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to jsonpipe-0.0.8/.gitignore0000644000175000017500000000017411571127622015154 0ustar domibeldomibel*.egg-info *.pyc *.pyo .DS_Store build dist MANIFEST test/example/*.sqlite3 doc/.build distribute-*.egg distribute-*.tar.gz jsonpipe-0.0.8/MANIFEST.in0000644000175000017500000000003411571127622014715 0ustar domibeldomibelinclude distribute_setup.py jsonpipe-0.0.8/example.json0000644000175000017500000014305511571127622015520 0ustar domibeldomibel[ { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:53 +0000 2011", "favorited": false, "geo": null, "id": 53941178919424000, "id_str": "53941178919424000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "\u00e9 muito tarde pra voltar atras, pra te dar o que eu nao te dei...", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Fri Jan 08 22:58:29 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "Viver bem \u00e9 a melhor vingan\u00e7a!", "favourites_count": 0, "follow_request_sent": null, "followers_count": 109, "following": null, "friends_count": 103, "geo_enabled": false, "id": 103110250, "id_str": "103110250", "is_translator": false, "lang": "en", "listed_count": 3, "location": "Gravata\u00ed, RS", "name": "Milene Magnus", "notifications": null, "profile_background_color": "000000", "profile_background_image_url": "http://a2.twimg.com/profile_background_images/65470560/OgAAAOjJ_MppsYQZ5ZIFPzLf7QjT-5wgOmTemhq9qvahqFT9MRQm4559-uuhom6sKdKrrzRp-kCwdNM7xwZrzrB0OBUAm1T1UHgn-ESU4-sjIlzODnV77RH7AD4K.jpg", "profile_background_tile": true, "profile_image_url": "http://a3.twimg.com/profile_images/1284102622/OgAAAOl0wS1BtFRhzD_kOjFEXmCvi3AT66iEZDjGyDv93mMy8LsW29pEfoiwLVjd1iH1dLmNlYlXgkQRNvHQuWVCWisAm1T1UJ46Oi3Md00Fk5-wj9Qgqst-VXja_normal.jpg", "profile_link_color": "340573", "profile_sidebar_border_color": "d91a77", "profile_sidebar_fill_color": "f24389", "profile_text_color": "000000", "profile_use_background_image": false, "protected": false, "screen_name": "milenemagnus_", "show_all_inline_media": false, "statuses_count": 4478, "time_zone": "Greenland", "url": null, "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:53 +0000 2011", "favorited": false, "geo": null, "id": 53941178504192000, "id_str": "53941178504192000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "De los errores se aprende, no se lamenta.", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Wed Nov 10 05:07:00 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "T'estimo Bar\u00e7a. Viajar. Conocer el mundo, disfrutar cada segundo de la vida. English too", "favourites_count": 0, "follow_request_sent": null, "followers_count": 62, "following": null, "friends_count": 623, "geo_enabled": false, "id": 213948055, "id_str": "213948055", "is_translator": false, "lang": "en", "listed_count": 0, "location": "", "name": "Andres", "notifications": null, "profile_background_color": "022330", "profile_background_image_url": "http://a2.twimg.com/profile_background_images/197871070/andrespirate2.jpg", "profile_background_tile": false, "profile_image_url": "http://a1.twimg.com/profile_images/1164443389/andrespirate2_normal.jpg", "profile_link_color": "0084B4", "profile_sidebar_border_color": "a8c7f7", "profile_sidebar_fill_color": "C0DFEC", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "andrewsin7", "show_all_inline_media": false, "statuses_count": 513, "time_zone": "Eastern Time (US & Canada)", "url": null, "utc_offset": -18000, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:53 +0000 2011", "favorited": false, "geo": null, "id": 53941177673728000, "id_str": "53941177673728000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "a #TaianeMello ta querendo me deixar maluco, so pode !!!", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sat Oct 16 00:44:59 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "Estudante do MV1, tricolor ilustre ;p, jogador de futmesa e peladeiro do Petr\u00f4, quem me conhece, sabe exatamente como sou... ;D", "favourites_count": 0, "follow_request_sent": null, "followers_count": 37, "following": null, "friends_count": 67, "geo_enabled": false, "id": 203317177, "id_str": "203317177", "is_translator": false, "lang": "en", "listed_count": 1, "location": "Petropolis", "name": "Bernardo Kochem", "notifications": null, "profile_background_color": "1A1B1F", "profile_background_image_url": "http://a3.twimg.com/a/1300479984/images/themes/theme9/bg.gif", "profile_background_tile": false, "profile_image_url": "http://a3.twimg.com/profile_images/1279442404/S5030048_normal.JPG", "profile_link_color": "2FC2EF", "profile_sidebar_border_color": "181A1E", "profile_sidebar_fill_color": "252429", "profile_text_color": "666666", "profile_use_background_image": true, "protected": false, "screen_name": "bekochem", "show_all_inline_media": false, "statuses_count": 198, "time_zone": "Brasilia", "url": null, "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:53 +0000 2011", "favorited": false, "geo": null, "id": 53941176822272000, "id_str": "53941176822272000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "Seesmic Desktop", "text": "/@TelegraphNews: Afghanistan UN murders: the worst possible incident for the US, Nato and the UN http://tgr.ph/gy5odP", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Tue Sep 22 18:16:32 +0000 2009", "default_profile": true, "default_profile_image": false, "description": "Bringing you fast-paced, accurate news from across the country and around the world. 11 yr Air Force member.", "favourites_count": 0, "follow_request_sent": null, "followers_count": 5462, "following": null, "friends_count": 3547, "geo_enabled": false, "id": 76405315, "id_str": "76405315", "is_translator": false, "lang": "en", "listed_count": 500, "location": "Baton Rouge, LA", "name": "Chris", "notifications": null, "profile_background_color": "C0DEED", "profile_background_image_url": "http://a3.twimg.com/a/1301438647/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://a2.twimg.com/profile_images/760054127/twitterProfilePhoto_normal.jpg", "profile_link_color": "0084B4", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "TheNewsBlotter", "show_all_inline_media": false, "statuses_count": 169209, "time_zone": "Central Time (US & Canada)", "url": "http://thenewsblotter.blogspot.com/", "utc_offset": -21600, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:52 +0000 2011", "favorited": false, "geo": null, "id": 53941174725120000, "id_str": "53941174725120000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "\u00dcberSocial", "text": "Smt Even More Vex", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Thu Nov 05 05:18:49 +0000 2009", "default_profile": false, "default_profile_image": false, "description": "$$ / \u2665 / Feisty / 15 / Mixxed\r\n\r\n#HH^ & #YME ^ Its A #YUMMM Tingg ! :P", "favourites_count": 171, "follow_request_sent": null, "followers_count": 3938, "following": null, "friends_count": 3508, "geo_enabled": true, "id": 87621800, "id_str": "87621800", "is_translator": false, "lang": "en", "listed_count": 377, "location": "Bittin @OGYUMBOY_IZZY Neck :-*", "name": "\u2603RedROBBiNYUMMM", "notifications": null, "profile_background_color": "080101", "profile_background_image_url": "http://a2.twimg.com/profile_background_images/222919284/101214-203703.jpg", "profile_background_tile": true, "profile_image_url": "http://a1.twimg.com/profile_images/1269458607/Picture_002_1__phixr_normal.jpg", "profile_link_color": "000000", "profile_sidebar_border_color": "f02ba8", "profile_sidebar_fill_color": "ffffff", "profile_text_color": "f527ad", "profile_use_background_image": true, "protected": false, "screen_name": "16SinsAPRIL19th", "show_all_inline_media": true, "statuses_count": 123712, "time_zone": "Hawaii", "url": "http://plixi.com/RedRobbinYUMM", "utc_offset": -36000, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:52 +0000 2011", "favorited": false, "geo": null, "id": 53941171906560000, "id_str": "53941171906560000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "earphones in, @justinbieber on full blast, tub of ben and jerrys, block out the world. perfect", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sun Dec 19 22:10:31 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "be yourself and #dreambig .. 28/03/11 PATTIE RT ME! 23/3/11 #myworldtour @justinbieber, best night ever! family and friends mean the world\u2665.", "favourites_count": 0, "follow_request_sent": null, "followers_count": 253, "following": null, "friends_count": 396, "geo_enabled": false, "id": 228496430, "id_str": "228496430", "is_translator": false, "lang": "en", "listed_count": 1, "location": "england", "name": "ellisJB", "notifications": null, "profile_background_color": "8dcfe3", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/223151550/twitter.jpg", "profile_background_tile": true, "profile_image_url": "http://a3.twimg.com/profile_images/1290422336/JUSTIN_BIEBER2_normal.jpg", "profile_link_color": "0c00b3", "profile_sidebar_border_color": "030405", "profile_sidebar_fill_color": "14e0e0", "profile_text_color": "c918c9", "profile_use_background_image": true, "protected": false, "screen_name": "ellisbetx", "show_all_inline_media": false, "statuses_count": 537, "time_zone": null, "url": null, "utc_offset": null, "verified": false } }, { "contributors": null, "coordinates": { "coordinates": [ 3.851304, 7.341991 ], "type": "Point" }, "created_at": "Fri Apr 01 22:05:51 +0000 2011", "favorited": false, "geo": { "coordinates": [ 7.341991, 3.851304 ], "type": "Point" }, "id": 53941170006528000, "id_str": "53941170006528000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "\u00dcberSocial", "text": "E nevr kill yu..onpe RT @Adelajjj: Lwkm RT @koonley: Hehehe..e don pain am *tongue out* RT @Adelajjj: Mtscheeew...I ... http://tmi.me/8mBld", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sun May 02 11:02:11 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "Ask and yu shall know...", "favourites_count": 1, "follow_request_sent": null, "followers_count": 41, "following": null, "friends_count": 112, "geo_enabled": true, "id": 139362670, "id_str": "139362670", "is_translator": false, "lang": "en", "listed_count": 0, "location": "\u00dcT: 7.341991,3.851304", "name": "Kunle Raji", "notifications": null, "profile_background_color": "8B542B", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/125323899/051.jpg", "profile_background_tile": true, "profile_image_url": "http://a0.twimg.com/profile_images/1288807458/278767158_normal.jpg", "profile_link_color": "9D582E", "profile_sidebar_border_color": "D9B17E", "profile_sidebar_fill_color": "EADEAA", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "koonley", "show_all_inline_media": false, "statuses_count": 594, "time_zone": "Pacific Time (US & Canada)", "url": null, "utc_offset": -28800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:51 +0000 2011", "favorited": false, "geo": null, "id": 53941169373184000, "id_str": "53941169373184000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "eu sou completamente apaixonada pela voz e pelo cantor do panic at the disco *o*", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Mon Jul 27 15:33:37 +0000 2009", "default_profile": false, "default_profile_image": false, "description": "Tayna Pinheiro Bernardino , Amazonense, 14 anos aquariana, viciada em twitter,chocolate,musica,tumblr s2", "favourites_count": 371, "follow_request_sent": null, "followers_count": 2012, "following": null, "friends_count": 1714, "geo_enabled": true, "id": 60626790, "id_str": "60626790", "is_translator": false, "lang": "en", "listed_count": 231, "location": "Manaus - Am", "name": "tayna bernardino", "notifications": null, "profile_background_color": "09020f", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/223296260/000000_dream-of-love.gif", "profile_background_tile": true, "profile_image_url": "http://a3.twimg.com/profile_images/1265953164/17012011670_normal.jpg", "profile_link_color": "f0719b", "profile_sidebar_border_color": "105559", "profile_sidebar_fill_color": "f0e8ed", "profile_text_color": "28d8f7", "profile_use_background_image": true, "protected": false, "screen_name": "taynabernardino", "show_all_inline_media": false, "statuses_count": 57319, "time_zone": "Brasilia", "url": "http://taynabernardino.tumblr.com/", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:51 +0000 2011", "favorited": false, "geo": null, "id": 53941168848896000, "id_str": "53941168848896000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "today is friday", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Mon Jun 21 00:44:29 +0000 2010", "default_profile": false, "default_profile_image": true, "description": null, "favourites_count": 0, "follow_request_sent": null, "followers_count": 14, "following": null, "friends_count": 22, "geo_enabled": false, "id": 157823751, "id_str": "157823751", "is_translator": false, "lang": "en", "listed_count": 0, "location": null, "name": "Jordana", "notifications": null, "profile_background_color": "FF6699", "profile_background_image_url": "http://a3.twimg.com/a/1301071706/images/themes/theme11/bg.gif", "profile_background_tile": true, "profile_image_url": "http://a2.twimg.com/sticky/default_profile_images/default_profile_1_normal.png", "profile_link_color": "B40B43", "profile_sidebar_border_color": "CC3366", "profile_sidebar_fill_color": "E5507E", "profile_text_color": "362720", "profile_use_background_image": true, "protected": false, "screen_name": "_johlopes", "show_all_inline_media": false, "statuses_count": 173, "time_zone": null, "url": null, "utc_offset": null, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:50 +0000 2011", "favorited": false, "geo": null, "id": 53941166554624000, "id_str": "53941166554624000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "Meu quarto est\u00e1 daquele jeito...todo bagun\u00e7ado...rsrsrsrs", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sat Aug 22 01:21:12 +0000 2009", "default_profile": false, "default_profile_image": false, "description": "Menina; Mulher; Pedagoga; S\u00e3o Paulina; Pagodeira; Apaixonada; Diferente e engra\u00e7ada!", "favourites_count": 2, "follow_request_sent": null, "followers_count": 267, "following": null, "friends_count": 460, "geo_enabled": true, "id": 67776575, "id_str": "67776575", "is_translator": false, "lang": "en", "listed_count": 14, "location": "S\u00e3o Paulo", "name": "Luisa", "notifications": null, "profile_background_color": "c773d4", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/223646472/cora__o_quebrado.jpg", "profile_background_tile": true, "profile_image_url": "http://a2.twimg.com/profile_images/1289430825/047_normal.JPG", "profile_link_color": "f01de2", "profile_sidebar_border_color": "6058c9", "profile_sidebar_fill_color": "", "profile_text_color": "ff4ced", "profile_use_background_image": true, "protected": false, "screen_name": "Negah_Luhh", "show_all_inline_media": false, "statuses_count": 15080, "time_zone": "Brasilia", "url": "http://www.meadiciona.com/lulibispo", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:50 +0000 2011", "favorited": false, "geo": null, "id": 53941165178880000, "id_str": "53941165178880000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "Tinychat Connector", "text": "Hey check out this vid chat room with 40 people in it - http://tinychat.com/justanteenager [http://tinychat.com]", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sun Jun 20 18:06:05 +0000 2010", "default_profile": true, "default_profile_image": true, "description": null, "favourites_count": 0, "follow_request_sent": null, "followers_count": 2, "following": null, "friends_count": 29, "geo_enabled": false, "id": 157731697, "id_str": "157731697", "is_translator": false, "lang": "en", "listed_count": 0, "location": null, "name": "funguy", "notifications": null, "profile_background_color": "C0DEED", "profile_background_image_url": "http://a3.twimg.com/a/1301438647/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://a1.twimg.com/sticky/default_profile_images/default_profile_4_normal.png", "profile_link_color": "0084B4", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "betageta3", "show_all_inline_media": false, "statuses_count": 785, "time_zone": null, "url": null, "utc_offset": null, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:50 +0000 2011", "favorited": false, "geo": null, "id": 53941163824128000, "id_str": "53941163824128000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "Twitter for BlackBerry\u00ae", "text": "\"@ajc: Speaking of jobs ~>RT @ajcads: PCI nurses in demand @ DeKalb Medical. Unit opening soon. $4K bonus. Apply now http://bit.ly/gtlDJv\"", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Mon Nov 01 02:01:12 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "I AM what I WILL to be...Fabulous, A Legend, A Mogul!I AM a Daughter, Sister, Friend, Educator, Entrepreneur, Advocate, Motivated Mommy on the Move to the TOP! ", "favourites_count": 0, "follow_request_sent": null, "followers_count": 131, "following": null, "friends_count": 191, "geo_enabled": false, "id": 210680272, "id_str": "210680272", "is_translator": false, "lang": "en", "listed_count": 4, "location": "Atlanta...NetWORKing Globally ", "name": "Melissa Waller", "notifications": null, "profile_background_color": "A6DF40", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/168952582/xca551120f1d7a81c4e220859fe5d0f6.png", "profile_background_tile": true, "profile_image_url": "http://a1.twimg.com/profile_images/1259137345/FacebookHomescreenImage_normal.jpg", "profile_link_color": "FFFFFF", "profile_sidebar_border_color": "FF7E00", "profile_sidebar_fill_color": "51C7E6", "profile_text_color": "FA2676", "profile_use_background_image": true, "protected": false, "screen_name": "mommiepreneur", "show_all_inline_media": false, "statuses_count": 1196, "time_zone": "Quito", "url": null, "utc_offset": -18000, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:49 +0000 2011", "favorited": false, "geo": null, "id": 53941162142208000, "id_str": "53941162142208000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "s\u00f3 que o nome dele \u00e9 Phillipe KKKKKKKKKKK a\u00ed ele tava bebendo \u00e1gua, a\u00ed minha amg esqueceu e chamou ele de L\u00e9o. Ficamos rindo 53457454 horas!", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Mon Jan 31 20:42:31 +0000 2011", "default_profile": false, "default_profile_image": false, "description": "te amarei de Janeiro a Janeiro, at\u00e9 o mundo acabar, @whoiscarlos \u2665 Atualizado por: @jufact. Desde: 10/02/2011 =]", "favourites_count": 23, "follow_request_sent": null, "followers_count": 289, "following": null, "friends_count": 171, "geo_enabled": false, "id": 245495210, "id_str": "245495210", "is_translator": false, "lang": "en", "listed_count": 8, "location": "Quarto do Carlos :9 #rawr", "name": "twitf\u00e3 Carlos", "notifications": null, "profile_background_color": "e8e8e8", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/213555594/carlosx.png", "profile_background_tile": false, "profile_image_url": "http://a3.twimg.com/profile_images/1288424435/coelho_Carlos_normal.jpg", "profile_link_color": "84d7f0", "profile_sidebar_border_color": "f7f7f7", "profile_sidebar_fill_color": "", "profile_text_color": "100112", "profile_use_background_image": true, "protected": false, "screen_name": "ManiacasCarlos", "show_all_inline_media": false, "statuses_count": 6526, "time_zone": "Greenland", "url": "http://twitpic.com/photos/ManiacasCarlos", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:49 +0000 2011", "favorited": false, "geo": null, "id": 53941161617920000, "id_str": "53941161617920000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "twicca", "text": "\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Tue Oct 06 12:15:55 +0000 2009", "default_profile": false, "default_profile_image": false, "description": "\u666e\u6bb5\u306f\u4e00\u822c\u4eba\u306e\u76ae\u3092\u88ab\u308a\u3064\u3064\u3082\u4e8c\u6b21\u5143\u304c\u306a\u3044\u3068\u751f\u304d\u3089\u308c\u306a\u3044\u30c0\u30e1\u306a\u793e\u4f1a\u4eba\u3002\u57fa\u672c\u7684\u306b\u5fc3\u306e\u5e95\u304b\u3089\u30f2\u30bf\u305d\u3057\u3066\u8150\u3067\u3059\u3002GODEATER\u3068DDFF\u306b\u840c\u3048\u308b\u65e5\u3005\u3002Drrr\u3068\u304bAPH\u3082\u5927\u597d\u304d\u3067\u3059\u3002\u30aa\u30d5\u3067\u306fBASARA\u3067\u6d3b\u52d5\u4e2d\u3001\u3067\u30823\u306f\u3084\u3063\u3066\u307e\u305b\u3093\u3002\u30b5\u30a4\u30c8\u3067\u306f\u7537\u4e3b\u5922\u5c0f\u8aac\u3068\u304b\u66f8\u3044\u3066\u307e\u3059\u3088\u3002\u30d5\u30a9\u30ed\u30fb\u30ea\u30e0\u304a\u6c17\u8efd\u306b\u30c9\u30be\u30fc\u3002", "favourites_count": 10, "follow_request_sent": null, "followers_count": 54, "following": null, "friends_count": 42, "geo_enabled": false, "id": 80286573, "id_str": "80286573", "is_translator": false, "lang": "ja", "listed_count": 4, "location": "\u307f\u3084\u304e\u3051\u3093\u306e\u771f\u3093\u4e2d\u3078\u3093", "name": "\u3055\u304b\u304d", "notifications": null, "profile_background_color": "131516", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/62047302/dot_11.gif", "profile_background_tile": true, "profile_image_url": "http://a2.twimg.com/profile_images/1289192557/profile_normal.png", "profile_link_color": "009999", "profile_sidebar_border_color": "eeeeee", "profile_sidebar_fill_color": "efefef", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "sa_kaki", "show_all_inline_media": false, "statuses_count": 9636, "time_zone": "Tokyo", "url": "http://mega36.sakura.ne.jp/", "utc_offset": 32400, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:49 +0000 2011", "favorited": false, "geo": null, "id": 53941160678400000, "id_str": "53941160678400000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "nossa, quero ir pra algum lugar amanha, n\u00e3o aguento ter q ficar em casa com a minha tia e a minha v\u00f3 juntas", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Wed Jan 06 19:51:33 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "eu gosto de texugos ,guaxinins e suricatos .e voc\u00ea ? :3", "favourites_count": 2, "follow_request_sent": null, "followers_count": 199, "following": null, "friends_count": 191, "geo_enabled": true, "id": 102462023, "id_str": "102462023", "is_translator": false, "lang": "en", "listed_count": 2, "location": "", "name": "Natalia xD", "notifications": null, "profile_background_color": "000000", "profile_background_image_url": "http://a3.twimg.com/profile_background_images/190709748/knuckle.png", "profile_background_tile": true, "profile_image_url": "http://a0.twimg.com/profile_images/1241787503/Foto0376_normal.jpg", "profile_link_color": "000000", "profile_sidebar_border_color": "ffffff", "profile_sidebar_fill_color": "ffffff", "profile_text_color": "000000", "profile_use_background_image": true, "protected": false, "screen_name": "mantegavoadora", "show_all_inline_media": false, "statuses_count": 1527, "time_zone": "Greenland", "url": "http://www.formspring.me/Naahty", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:49 +0000 2011", "favorited": false, "geo": null, "id": 53941159411712000, "id_str": "53941159411712000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "Google", "text": "Des petits Ours de l'Himalaya http://goo.gl/fb/Oyjv0", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sat Jun 26 21:28:16 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "", "favourites_count": 0, "follow_request_sent": null, "followers_count": 78, "following": null, "friends_count": 210, "geo_enabled": false, "id": 159981295, "id_str": "159981295", "is_translator": false, "lang": "fr", "listed_count": 0, "location": "", "name": "hapatchan", "notifications": null, "profile_background_color": "9AE4E8", "profile_background_image_url": "http://a0.twimg.com/a/1300401069/images/themes/theme16/bg.gif", "profile_background_tile": false, "profile_image_url": "http://a1.twimg.com/profile_images/1027264665/bo3ou_normal.jpg", "profile_link_color": "0084B4", "profile_sidebar_border_color": "BDDCAD", "profile_sidebar_fill_color": "DDFFCC", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "hapatchan", "show_all_inline_media": false, "statuses_count": 603, "time_zone": "Greenland", "url": "http://www.hapatchan.blogspot.com/", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:49 +0000 2011", "favorited": false, "geo": null, "id": 53941159105536000, "id_str": "53941159105536000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "web", "text": "85 \u2013 \u00c0s vezes deixo de me aproximar de pessoas, por medo de perd\u00ea-las. (no sentido da morte), chega a ser paran\u00f3ia. #100factsaboutme", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Thu Jan 21 23:23:45 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "16 anos. Ciumento, exagerado, curioso, atrapalhado, medroso. Apaixonado por Atua\u00e7\u00e3o e Psicologia. N\u00e3o mudarei, tentando te impressionar. I Belong to Jesus! \u2665", "favourites_count": 5, "follow_request_sent": null, "followers_count": 426, "following": null, "friends_count": 96, "geo_enabled": true, "id": 107240071, "id_str": "107240071", "is_translator": false, "lang": "es", "listed_count": 124, "location": "Catanduva - S\u00e3o Paulo", "name": "Erik William Lopes", "notifications": null, "profile_background_color": "ffffff", "profile_background_image_url": "http://a1.twimg.com/profile_background_images/221771443/bg.png", "profile_background_tile": true, "profile_image_url": "http://a2.twimg.com/profile_images/1199593805/CIMG0150_normal.JPG", "profile_link_color": "78093b", "profile_sidebar_border_color": "0d0000", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "000000", "profile_use_background_image": true, "protected": false, "screen_name": "_ErikLopes", "show_all_inline_media": false, "statuses_count": 26762, "time_zone": "Greenland", "url": "http://meadiciona.com/erikwiil", "utc_offset": -10800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:48 +0000 2011", "favorited": false, "geo": null, "id": 53941158166016000, "id_str": "53941158166016000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "twitterfeed", "text": "Home Depot Tries Crowdsourced Philanthropy on Facebook http://bit.ly/i5Meip #news #socialmedia", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Sun Sep 20 05:11:03 +0000 2009", "default_profile": true, "default_profile_image": false, "description": "Your real-time source for social media jobs in San Francisco and social media news.", "favourites_count": 0, "follow_request_sent": null, "followers_count": 1211, "following": null, "friends_count": 0, "geo_enabled": false, "id": 75725191, "id_str": "75725191", "is_translator": false, "lang": "en", "listed_count": 20, "location": "San Francisco, CA", "name": "JobShoots", "notifications": null, "profile_background_color": "C0DEED", "profile_background_image_url": "http://a3.twimg.com/a/1300991299/images/themes/theme1/bg.png", "profile_background_tile": false, "profile_image_url": "http://a1.twimg.com/profile_images/425265269/10431_156500280258_156499820258_4034514_6686001_n_normal.jpg", "profile_link_color": "0084B4", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "sfsmjobshoot", "show_all_inline_media": false, "statuses_count": 52111, "time_zone": "Pacific Time (US & Canada)", "url": "http://www.jobshoots.com", "utc_offset": -28800, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:48 +0000 2011", "favorited": false, "geo": null, "id": 53941157838848000, "id_str": "53941157838848000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "jigtwi", "text": "\u306a\u3093\u304b\u6674\u308c\u3068\u308b\u3002\u3067\u3082\u5929\u6c17\u4e88\u5831\u306f\u96ea\u3063\u3066\u3069\u3046\u3044\u3046\u3053\u3068\u30fc", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Mon Jul 19 06:48:54 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "\u30c1\u30ad\u30f3\u30cf\u30fc\u30c8\u306a\u8150\u5973\u5b50\u3067\u3059\u3002\u65e5\u5e38post\u304c\u591a\u3081\u3002\u9375\u306f\u30ea\u30a2\u53cb\u5bfe\u7b56(\u7b11)\u306a\u306e\u3067\u6c17\u8efd\u306b\u30d5\u30a9\u30ed\u30fc\u3069\u3046\u305e\uff01(\u796d\u308a\u6642\u306f\u5916\u3057\u3066\u307e\u3059)\u3055\u3088\u306a\u3089\u306f\u30d6\u30ed\u30c3\u30af\u3067\u304a\u9858\u3044\u3057\u307e\u3059\u3002\r\n\r\n\u64ec\u4eba\u5316/DFF/\uff76\uff70\uff86\uff73\uff9e\uff67\uff99/APH/LD1/\u5546\u696dBL/\u6771\u65b9/\u30b3\u30b9/\u30e9\u30c6/\u304a\u7d75\u304b\u304d\u7b49", "favourites_count": 54, "follow_request_sent": null, "followers_count": 162, "following": null, "friends_count": 163, "geo_enabled": false, "id": 168402715, "id_str": "168402715", "is_translator": false, "lang": "ja", "listed_count": 3, "location": "\u5317\u306e\u56fd\u306e\u8150\u6d77\u304b\u3089", "name": "\u305f\u305d", "notifications": null, "profile_background_color": "8B542B", "profile_background_image_url": "http://a2.twimg.com/a/1301438647/images/themes/theme8/bg.gif", "profile_background_tile": false, "profile_image_url": "http://a2.twimg.com/profile_images/1287631780/_________normal.png", "profile_link_color": "9D582E", "profile_sidebar_border_color": "D9B17E", "profile_sidebar_fill_color": "EADEAA", "profile_text_color": "333333", "profile_use_background_image": true, "protected": false, "screen_name": "taso_red", "show_all_inline_media": true, "statuses_count": 19816, "time_zone": "Tokyo", "url": null, "utc_offset": 32400, "verified": false } }, { "contributors": null, "coordinates": null, "created_at": "Fri Apr 01 22:05:48 +0000 2011", "favorited": false, "geo": null, "id": 53941156375040000, "id_str": "53941156375040000", "in_reply_to_screen_name": null, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "place": null, "retweet_count": 0, "retweeted": false, "source": "Echofon", "text": "Lol RT @JesusDidIt3: I should have stayed HOME!!! I ain't got time for GIRLS!!!", "truncated": false, "user": { "contributors_enabled": false, "created_at": "Tue Jan 05 07:16:45 +0000 2010", "default_profile": false, "default_profile_image": false, "description": "whoooosssseeeyou?\u2122 \r\n", "favourites_count": 146, "follow_request_sent": null, "followers_count": 1198, "following": null, "friends_count": 564, "geo_enabled": false, "id": 101988812, "id_str": "101988812", "is_translator": false, "lang": "en", "listed_count": 78, "location": "Atlanta, GA", "name": "Ranesha Finley", "notifications": null, "profile_background_color": "50586b", "profile_background_image_url": "http://a2.twimg.com/profile_background_images/226370379/200269_10150180898970774_775445773_8467827_174615_n.jpg", "profile_background_tile": true, "profile_image_url": "http://a3.twimg.com/profile_images/1289622843/ranesha89_normal.jpg", "profile_link_color": "f2e608", "profile_sidebar_border_color": "a35b71", "profile_sidebar_fill_color": "1f1aa3", "profile_text_color": "605a7a", "profile_use_background_image": true, "protected": false, "screen_name": "ranesha89", "show_all_inline_media": false, "statuses_count": 13785, "time_zone": "Eastern Time (US & Canada)", "url": null, "utc_offset": -18000, "verified": false } } ] jsonpipe-0.0.8/README.rst0000644000175000017500000001431211571127622014652 0ustar domibeldomibel======== jsonpipe ======== Everyone I know prefers to work with JSON over XML, but sadly there is a sore lack of utilities of the quality or depth of `html-xml-utils`_ and `XMLStarlet`_ for actually processing JSON data in an automated fashion, short of writing an *ad hoc* processor in your favourite programming language. .. _html-xml-utils: http://www.w3.org/Tools/HTML-XML-utils/README .. _XMLStarlet: http://xmlstar.sourceforge.net/ **jsonpipe** is a step towards a solution: it traverses a JSON object and produces a simple, line-based textual format which can be processed by all your UNIX favourites like grep, sed, awk, cut and diff. It may also be valuable within programming languages---in fact, it was originally conceived as a way of writing simple test assertions against JSON output without coupling the tests too closely to the specific structure used. This implementation (which should be considered the reference) is written in Python. Example ======= A ``
`` is worth a thousand words. For simple JSON values::

    $ echo '"Hello, World!"' | jsonpipe
    /	"Hello, World!"
    $ echo 123 | jsonpipe
    /	123
    $ echo 0.25 | jsonpipe
    /	0.25
    $ echo null | jsonpipe
    /	null
    $ echo true | jsonpipe
    /	true
    $ echo false | jsonpipe
    /	false

The 'root' of the object tree is represented by a single ``/`` character, and
for simple values it doesn't get any more complex than the above. Note that a
single tab character separates the path on the left from the literal value on
the right.

Composite data structures use a hierarchical syntax, where individual
keys/indices are children of the path to the containing object::

    $ echo '{"a": 1, "b": 2}' | jsonpipe
    /	{}
    /a	1
    /b	2
    $ echo '["foo", "bar", "baz"]' | jsonpipe
    /	[]
    /0	"foo"
    /1	"bar"
    /2	"baz"

For an object or array, the right-hand column indicates the datatype, and will
be either ``{}`` (object) or ``[]`` (array). For objects, the order of the keys
is preserved in the output.

The path syntax allows arbitrarily complex data structures::

    $ echo '[{"a": [{"b": {"c": ["foo"]}}]}]' | jsonpipe
    /	[]
    /0	{}
    /0/a	[]
    /0/a/0	{}
    /0/a/0/b	{}
    /0/a/0/b/c	[]
    /0/a/0/b/c/0	"foo"


Caveat: Path Separators
=======================

Because the path components are separated by ``/`` characters, an object key
like ``"abc/def"`` would result in ambiguous output. jsonpipe will throw
an error if this occurs in your input, so that you can recognize and handle the
issue. To mitigate the problem, you can choose a different path separator::

    $ echo '{"abc/def": 123}' | jsonpipe -s '☃'
    ☃	{}
    ☃abc/def	123

The Unicode snowman is chosen here because it's unlikely to occur as part of
the key in most JSON objects, but any character or string (e.g. ``:``, ``::``,
``~``) will do.


jsonunpipe
==========

Another useful part of the library is ``jsonunpipe``, which turns jsonpipe
output back into JSON proper::

    $ echo '{"a": 1, "b": 2}' | jsonpipe | jsonunpipe
    {"a": 1, "b": 2}

jsonunpipe also supports incomplete information (such as you might get from
grep), and will assume all previously-undeclared parts of a path to be JSON
objects::

    $ echo "/a/b/c	123" | jsonunpipe
    {"a": {"b": {"c": 123}}}


Python API
==========

Since jsonpipe is written in Python, you can import it and use it without
having to spawn another process::

    >>> from jsonpipe import jsonpipe
    >>> for line in jsonpipe({"a": 1, "b": 2}):
    ...     print line
    /	{}
    /a	1
    /b	2

Note that the ``jsonpipe()`` generator function takes a Python object, not a
JSON string, so the order of dictionary keys may be slightly unpredictable in
the output. You can use ``simplejson.OrderedDict`` to get a fixed ordering::

    >>> from simplejson import OrderedDict
    >>> obj = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    >>> obj
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    >>> for line in jsonpipe(obj):
    ...     print line
    /	{}
    /a	1
    /b	2
    /c	3

A more general hint: if you need to parse JSON but maintain ordering for object
keys, use the ``object_pairs_hook`` option on ``simplejson.load(s)``::

    >>> import simplejson
    >>> simplejson.loads('{"a": 1, "b": 2, "c": 3}',
    ...                  object_pairs_hook=simplejson.OrderedDict)
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])

Of course, a Python implementation of jsonunpipe also exists::

    >>> from jsonpipe import jsonunpipe
    >>> jsonunpipe(['/\t{}', '/a\t123'])
    {'a': 123}

You can pass a ``decoder`` parameter, as in the following example, where the
JSON object returned uses an ordered dictionary::

    >>> jsonunpipe(['/\t{}', '/a\t123', '/b\t456'],
    ...            decoder=simplejson.JSONDecoder(
    ...                object_pairs_hook=simplejson.OrderedDict))
    OrderedDict([('a', 123), ('b', 456)])

Installation
============

**jsonpipe** is written in Python, so is best installed using ``pip``::

    pip install jsonpipe

Note that it requires Python v2.5 or later (simplejson only supports 2.5+).


(Un)license
===========

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to 
jsonpipe-0.0.8/setup.py0000644000175000017500000000212111571127622014670 0ustar  domibeldomibel#!/usr/bin/env python
# -*- coding: utf-8 -*-

from distribute_setup import use_setuptools
use_setuptools()

import re
from setuptools import setup, find_packages
import os.path as p


def get_version():
    source = open(p.join(p.dirname(p.abspath(__file__)),
                         'src', 'jsonpipe', '__init__.py')).read()
    match = re.search(r'__version__\s*=\s*[\'"]([^\'"]+)[\'"]', source)
    if not match:
        raise RuntimeError("Couldn't find the version string in src/jsonpipe/__init__.py")
    return match.group(1)


setup(
    name='jsonpipe',
    version=get_version(),
    description="Convert JSON to a UNIX-friendly line-based format.",
    author='Zachary Voase',
    author_email='z@dvxhouse.com',
    url='http://github.com/dvxhouse/jsonpipe',
    package_dir={'': 'src'},
    packages=find_packages(where='src'),
    entry_points={'console_scripts': ['jsonpipe = jsonpipe:main',
                                      'jsonunpipe = jsonpipe:main_unpipe']},
    install_requires=['simplejson>=2.1.3', 'argparse>=1.1', 'calabash==0.0.3'],
    test_suite='jsonpipe._get_tests',
)
jsonpipe-0.0.8/EXAMPLES.rst0000644000175000017500000000374611571127622015144 0ustar  domibeldomibel========
Examples
========

This file enumerates some common patterns for working with jsonpipe output. The
examples here use the file ``example.json``, which can be found in the root of
this repo. Basic familiarity with the UNIX shell, common utilities and regular
expressions is assumed.


Simple Selection
================

In Python::

    >>> json[12]['user']['screen_name']
    u"ManiacasCarlos"

On the command-line, just grep for the specific path you're looking for::

    $ jsonpipe < example.json | grep -P '^/12/user/screen_name\t'
    /12/user/screen_name	"ManiacasCarlos"

The pattern used here is terminated with ``\t``, because otherwise we'd get
sub-components of the ``screen_name`` path if it were an object, and we'd also
pick up any keys which started with the string ``screen_name`` (so we might get
``screen_name_123`` and ``screen_name_abc`` if those keys existed).


Extracting Entire Objects
=========================

In Python::

    >>> json[12]['user']
    {... u'screen_name': u'ManiacasCarlos', ...}

On the command-line, grep for the path again but terminate with ``/`` instead
of ``\t``::

    $ jsonpipe < example.json | grep -P '^/12/user/'
    ...
    /12/user/profile_use_background_image	true
    /12/user/protected	false
    /12/user/screen_name	"ManiacasCarlos"
    /12/user/show_all_inline_media	false
    ...

You can also filter for either a simple value *or* an entire object by
terminating the pattern with a character range::

    $ jsonpipe < example.json | grep -P '^/12/user[/\t]'
    /12/user	{}
    /12/user/contributors_enabled	false
    /12/user/created_at	"Mon Jan 31 20:42:31 +0000 2011"
    /12/user/default_profile	false
    ...


Searching Based on Equality or Patterns
=======================================

Find users with a screen name beginning with a lowercase 'm'::

    $ jsonpipe < example.json | grep -P '/user/screen_name\t"m'
    /0/user/screen_name	"milenemagnus_"
    /11/user/screen_name	"mommiepreneur"
    /14/user/screen_name	"mantegavoadora"

jsonpipe-0.0.8/distribute_setup.py0000644000175000017500000003661511571127622017145 0ustar  domibeldomibel#!python
"""Bootstrap distribute installation

If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::

    from distribute_setup import use_setuptools
    use_setuptools()

If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.

This file can also be run as a script to install or upgrade setuptools.
"""
import os
import sys
import time
import fnmatch
import tempfile
import tarfile
from distutils import log

try:
    from site import USER_SITE
except ImportError:
    USER_SITE = None

try:
    import subprocess

    def _python_cmd(*args):
        args = (sys.executable,) + args
        return subprocess.call(args) == 0

except ImportError:
    # will be used for python 2.3
    def _python_cmd(*args):
        args = (sys.executable,) + args
        # quoting arguments if windows
        if sys.platform == 'win32':
            def quote(arg):
                if ' ' in arg:
                    return '"%s"' % arg
                return arg
            args = [quote(arg) for arg in args]
        return os.spawnl(os.P_WAIT, sys.executable, *args) == 0

DEFAULT_VERSION = "0.6.14"
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
SETUPTOOLS_FAKED_VERSION = "0.6c11"

SETUPTOOLS_PKG_INFO = """\
Metadata-Version: 1.0
Name: setuptools
Version: %s
Summary: xxxx
Home-page: xxx
Author: xxx
Author-email: xxx
License: xxx
Description: xxx
""" % SETUPTOOLS_FAKED_VERSION


def _install(tarball):
    # extracting the tarball
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        tar = tarfile.open(tarball)
        _extractall(tar)
        tar.close()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)

        # installing
        log.warn('Installing Distribute')
        if not _python_cmd('setup.py', 'install'):
            log.warn('Something went wrong during the installation.')
            log.warn('See the error message above.')
    finally:
        os.chdir(old_wd)


def _build_egg(egg, tarball, to_dir):
    # extracting the tarball
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        tar = tarfile.open(tarball)
        _extractall(tar)
        tar.close()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)

        # building an egg
        log.warn('Building a Distribute egg in %s', to_dir)
        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)

    finally:
        os.chdir(old_wd)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError('Could not build the egg.')


def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        tarball = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, tarball, to_dir)
    sys.path.insert(0, egg)
    import setuptools
    setuptools.bootstrap_install_from = egg


def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
                   to_dir=os.curdir, download_delay=15, no_fake=True):
    # making sure we use the absolute path
    to_dir = os.path.abspath(to_dir)
    was_imported = 'pkg_resources' in sys.modules or \
        'setuptools' in sys.modules
    try:
        try:
            import pkg_resources
            if not hasattr(pkg_resources, '_distribute'):
                if not no_fake:
                    _fake_setuptools()
                raise ImportError
        except ImportError:
            return _do_download(version, download_base, to_dir, download_delay)
        try:
            pkg_resources.require("distribute>="+version)
            return
        except pkg_resources.VersionConflict:
            e = sys.exc_info()[1]
            if was_imported:
                sys.stderr.write(
                "The required version of distribute (>=%s) is not available,\n"
                "and can't be installed while this script is running. Please\n"
                "install a more recent version first, using\n"
                "'easy_install -U distribute'."
                "\n\n(Currently using %r)\n" % (version, e.args[0]))
                sys.exit(2)
            else:
                del pkg_resources, sys.modules['pkg_resources']    # reload ok
                return _do_download(version, download_base, to_dir,
                                    download_delay)
        except pkg_resources.DistributionNotFound:
            return _do_download(version, download_base, to_dir,
                                download_delay)
    finally:
        if not no_fake:
            _create_fake_setuptools_pkg_info(to_dir)

def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
                        to_dir=os.curdir, delay=15):
    """Download distribute from a specified location and return its filename

    `version` should be a valid distribute version number that is available
    as an egg for download under the `download_base` URL (which should end
    with a '/'). `to_dir` is the directory where the egg will be downloaded.
    `delay` is the number of seconds to pause before an actual download
    attempt.
    """
    # making sure we use the absolute path
    to_dir = os.path.abspath(to_dir)
    try:
        from urllib.request import urlopen
    except ImportError:
        from urllib2 import urlopen
    tgz_name = "distribute-%s.tar.gz" % version
    url = download_base + tgz_name
    saveto = os.path.join(to_dir, tgz_name)
    src = dst = None
    if not os.path.exists(saveto):  # Avoid repeated downloads
        try:
            log.warn("Downloading %s", url)
            src = urlopen(url)
            # Read/write all in one block, so we don't create a corrupt file
            # if the download is interrupted.
            data = src.read()
            dst = open(saveto, "wb")
            dst.write(data)
        finally:
            if src:
                src.close()
            if dst:
                dst.close()
    return os.path.realpath(saveto)

def _no_sandbox(function):
    def __no_sandbox(*args, **kw):
        try:
            from setuptools.sandbox import DirectorySandbox
            if not hasattr(DirectorySandbox, '_old'):
                def violation(*args):
                    pass
                DirectorySandbox._old = DirectorySandbox._violation
                DirectorySandbox._violation = violation
                patched = True
            else:
                patched = False
        except ImportError:
            patched = False

        try:
            return function(*args, **kw)
        finally:
            if patched:
                DirectorySandbox._violation = DirectorySandbox._old
                del DirectorySandbox._old

    return __no_sandbox

def _patch_file(path, content):
    """Will backup the file then patch it"""
    existing_content = open(path).read()
    if existing_content == content:
        # already patched
        log.warn('Already patched.')
        return False
    log.warn('Patching...')
    _rename_path(path)
    f = open(path, 'w')
    try:
        f.write(content)
    finally:
        f.close()
    return True

_patch_file = _no_sandbox(_patch_file)

def _same_content(path, content):
    return open(path).read() == content

def _rename_path(path):
    new_name = path + '.OLD.%s' % time.time()
    log.warn('Renaming %s into %s', path, new_name)
    os.rename(path, new_name)
    return new_name

def _remove_flat_installation(placeholder):
    if not os.path.isdir(placeholder):
        log.warn('Unkown installation at %s', placeholder)
        return False
    found = False
    for file in os.listdir(placeholder):
        if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
            found = True
            break
    if not found:
        log.warn('Could not locate setuptools*.egg-info')
        return

    log.warn('Removing elements out of the way...')
    pkg_info = os.path.join(placeholder, file)
    if os.path.isdir(pkg_info):
        patched = _patch_egg_dir(pkg_info)
    else:
        patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)

    if not patched:
        log.warn('%s already patched.', pkg_info)
        return False
    # now let's move the files out of the way
    for element in ('setuptools', 'pkg_resources.py', 'site.py'):
        element = os.path.join(placeholder, element)
        if os.path.exists(element):
            _rename_path(element)
        else:
            log.warn('Could not find the %s element of the '
                     'Setuptools distribution', element)
    return True

_remove_flat_installation = _no_sandbox(_remove_flat_installation)

def _after_install(dist):
    log.warn('After install bootstrap.')
    placeholder = dist.get_command_obj('install').install_purelib
    _create_fake_setuptools_pkg_info(placeholder)

def _create_fake_setuptools_pkg_info(placeholder):
    if not placeholder or not os.path.exists(placeholder):
        log.warn('Could not find the install location')
        return
    pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
    setuptools_file = 'setuptools-%s-py%s.egg-info' % \
            (SETUPTOOLS_FAKED_VERSION, pyver)
    pkg_info = os.path.join(placeholder, setuptools_file)
    if os.path.exists(pkg_info):
        log.warn('%s already exists', pkg_info)
        return

    log.warn('Creating %s', pkg_info)
    f = open(pkg_info, 'w')
    try:
        f.write(SETUPTOOLS_PKG_INFO)
    finally:
        f.close()

    pth_file = os.path.join(placeholder, 'setuptools.pth')
    log.warn('Creating %s', pth_file)
    f = open(pth_file, 'w')
    try:
        f.write(os.path.join(os.curdir, setuptools_file))
    finally:
        f.close()

_create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info)

def _patch_egg_dir(path):
    # let's check if it's already patched
    pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
    if os.path.exists(pkg_info):
        if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
            log.warn('%s already patched.', pkg_info)
            return False
    _rename_path(path)
    os.mkdir(path)
    os.mkdir(os.path.join(path, 'EGG-INFO'))
    pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
    f = open(pkg_info, 'w')
    try:
        f.write(SETUPTOOLS_PKG_INFO)
    finally:
        f.close()
    return True

_patch_egg_dir = _no_sandbox(_patch_egg_dir)

def _before_install():
    log.warn('Before install bootstrap.')
    _fake_setuptools()


def _under_prefix(location):
    if 'install' not in sys.argv:
        return True
    args = sys.argv[sys.argv.index('install')+1:]
    for index, arg in enumerate(args):
        for option in ('--root', '--prefix'):
            if arg.startswith('%s=' % option):
                top_dir = arg.split('root=')[-1]
                return location.startswith(top_dir)
            elif arg == option:
                if len(args) > index:
                    top_dir = args[index+1]
                    return location.startswith(top_dir)
        if arg == '--user' and USER_SITE is not None:
            return location.startswith(USER_SITE)
    return True


def _fake_setuptools():
    log.warn('Scanning installed packages')
    try:
        import pkg_resources
    except ImportError:
        # we're cool
        log.warn('Setuptools or Distribute does not seem to be installed.')
        return
    ws = pkg_resources.working_set
    try:
        setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
                                  replacement=False))
    except TypeError:
        # old distribute API
        setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))

    if setuptools_dist is None:
        log.warn('No setuptools distribution found')
        return
    # detecting if it was already faked
    setuptools_location = setuptools_dist.location
    log.warn('Setuptools installation detected at %s', setuptools_location)

    # if --root or --preix was provided, and if
    # setuptools is not located in them, we don't patch it
    if not _under_prefix(setuptools_location):
        log.warn('Not patching, --root or --prefix is installing Distribute'
                 ' in another location')
        return

    # let's see if its an egg
    if not setuptools_location.endswith('.egg'):
        log.warn('Non-egg installation')
        res = _remove_flat_installation(setuptools_location)
        if not res:
            return
    else:
        log.warn('Egg installation')
        pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
        if (os.path.exists(pkg_info) and
            _same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
            log.warn('Already patched.')
            return
        log.warn('Patching...')
        # let's create a fake egg replacing setuptools one
        res = _patch_egg_dir(setuptools_location)
        if not res:
            return
    log.warn('Patched done.')
    _relaunch()


def _relaunch():
    log.warn('Relaunching...')
    # we have to relaunch the process
    # pip marker to avoid a relaunch bug
    if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']:
        sys.argv[0] = 'setup.py'
    args = [sys.executable] + sys.argv
    sys.exit(subprocess.call(args))


def _extractall(self, path=".", members=None):
    """Extract all members from the archive to the current working
       directory and set owner, modification time and permissions on
       directories afterwards. `path' specifies a different directory
       to extract to. `members' is optional and must be a subset of the
       list returned by getmembers().
    """
    import copy
    import operator
    from tarfile import ExtractError
    directories = []

    if members is None:
        members = self

    for tarinfo in members:
        if tarinfo.isdir():
            # Extract directories with a safe mode.
            directories.append(tarinfo)
            tarinfo = copy.copy(tarinfo)
            tarinfo.mode = 448 # decimal for oct 0700
        self.extract(tarinfo, path)

    # Reverse sort directories.
    if sys.version_info < (2, 4):
        def sorter(dir1, dir2):
            return cmp(dir1.name, dir2.name)
        directories.sort(sorter)
        directories.reverse()
    else:
        directories.sort(key=operator.attrgetter('name'), reverse=True)

    # Set correct owner, mtime and filemode on directories.
    for tarinfo in directories:
        dirpath = os.path.join(path, tarinfo.name)
        try:
            self.chown(tarinfo, dirpath)
            self.utime(tarinfo, dirpath)
            self.chmod(tarinfo, dirpath)
        except ExtractError:
            e = sys.exc_info()[1]
            if self.errorlevel > 1:
                raise
            else:
                self._dbg(1, "tarfile: %s" % e)


def main(argv, version=DEFAULT_VERSION):
    """Install or upgrade setuptools and EasyInstall"""
    tarball = download_setuptools()
    _install(tarball)


if __name__ == '__main__':
    main(sys.argv[1:])