code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
[ [ 8, 0, 0.1619, 0.0476, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.2, 0.0095, 0, 0.66, 0.0909, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2286, 0.0095, 0, 0.66, ...
[ "\"\"\"Utilities for reading OAuth 2.0 client secret files.\n\nA client_secrets.json file contains all the information needed to interact with\nan OAuth 2.0 protected service.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "from anyjson import simplejson", "TYPE_WEB = 'web'", "TYPE_INSTALL...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import os import stat import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask) def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._create_file_if_needed() f = open(self._filename, 'wb') f.write(credentials.to_json()) f.close() def locked_delete(self): """Delete Credentials file. Args: credentials: Credentials, the credentials to store. """ os.unlink(self._filename)
[ [ 8, 0, 0.1604, 0.0472, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1981, 0.0094, 0, 0.66, 0.125, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.217, 0.0094, 0, 0.66, ...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 2.0\ncredentials.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import os", "import stat", "import threading", "from anyjson import simplejson", "from client import Storage as BaseStorage", "from clien...
__version__ = "1.0c2"
[ [ 14, 0, 1, 1, 0, 0.66, 0, 162, 1, 0, 0, 0, 0, 3, 0 ] ]
[ "__version__ = \"1.0c2\"" ]
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save() def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query).delete()
[ [ 8, 0, 0.1371, 0.0403, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1694, 0.0081, 0, 0.66, 0.1111, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1855, 0.0081, 0, 0.66,...
[ "\"\"\"OAuth 2.0 utilities for Django.\n\nUtilities for using OAuth 2.0 in conjunction with\nthe Django datastore.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import oauth2client", "import base64", "import pickle", "from django.db import models", "from oauth2client.client import St...
# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
[ [ 8, 0, 0.0814, 0.1105, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1453, 0.0058, 0, 0.66, 0.0833, 162, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1512, 0.0058, 0, 0.66...
[ "\"\"\"MIME-Type Parser\n\nThis module provides basic functions for handling mime-types. It can handle\nmatching mime-types against a list of media-ranges. See section 14.1 of the\nHTTP specification [RFC 2616] for a complete explanation.\n\n http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1", "__v...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from oauth2client.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] def _prettyPrintSchema(self, schema, seen=None, dent=0): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" def __init__(self, schema, seen, dent=0): """Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % str(value), schema.get('description', '')) elif stype == 'integer': value = schema.get('default', '42') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'number': value = schema.get('default', '3.14') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema)
[ [ 8, 0, 0.1205, 0.1452, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.2046, 0.0033, 0, 0.66, 0.2, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2112, 0.0033, 0, 0.66, ...
[ "\"\"\"Schema processing for discovery based APIs\n\nSchemas holds an APIs discovery schemas. It can return those schema as\ndeserialized JSON objects, or pretty print them as prototype objects that\nconform to the schema.\n\nFor example, given the schema:", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", ...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson
[ [ 8, 0, 0.5312, 0.1562, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.6562, 0.0312, 0, 0.66, 0.5, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 7, 0, 0.875, 0.2812, 0, 0.66, ...
[ "\"\"\"Utility module to import a JSON module\n\nHides all the messy details of exactly where\nwe get a simplejson module from.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "try: # pragma: no cover\n import simplejson\nexcept ImportError: # pragma: no cover\n try:\n # Try to import from...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy import httplib2 import logging import oauth2 as oauth import urllib import urlparse from anyjson import simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Error occurred during request.""" pass class MissingParameter(Error): pass class CredentialsInvalidError(Error): pass def _abstract(): raise NotImplementedError('You need to override this function') def _oauth_uri(name, discovery, params): """Look up the OAuth URI from the discovery document and add query parameters based on params. name - The name of the OAuth URI to lookup, one of 'request', 'access', or 'authorize'. discovery - Portion of discovery document the describes the OAuth endpoints. params - Dictionary that is used to form the query parameters for the specified URI. """ if name not in ['request', 'access', 'authorize']: raise KeyError(name) keys = discovery[name]['parameters'].keys() query = {} for key in keys: if key in params: query[key] = params[key] return discovery[name]['url'] + '?' + urllib.urlencode(query) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. """ def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. """ def get(self): """Retrieve credential. Returns: apiclient.oauth.Credentials """ _abstract() def put(self, credentials): """Write a credential. Args: credentials: Credentials, the credentials to store. """ _abstract() class OAuthCredentials(Credentials): """Credentials object for OAuth 1.0a """ def __init__(self, consumer, token, user_agent): """ consumer - An instance of oauth.Consumer. token - An instance of oauth.Token constructed with the access token and secret. user_agent - The HTTP User-Agent to provide for this application. """ self.consumer = consumer self.token = token self.user_agent = user_agent self.store = None # True if the credentials have been revoked self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, "_invalid", False) def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: req = oauth.Request.from_consumer_and_token( self.consumer, self.token, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, self.token) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] # Update the stored credential if it becomes invalid. if response_code == 401: logging.info('Access token no longer valid: %s' % content) self._invalid = True if self.store is not None: self.store(self) raise CredentialsInvalidError("Credentials are no longer valid.") return resp, content http.request = new_request return http class TwoLeggedOAuthCredentials(Credentials): """Two Legged Credentials object for OAuth 1.0a. The Two Legged object is created directly, not from a flow. Once you authorize and httplib2.Http instance you can change the requestor and that change will propogate to the authorized httplib2.Http instance. For example: http = httplib2.Http() http = credentials.authorize(http) credentials.requestor = 'foo@example.info' http.request(...) credentials.requestor = 'bar@example.info' http.request(...) """ def __init__(self, consumer_key, consumer_secret, user_agent): """ Args: consumer_key: string, An OAuth 1.0 consumer key consumer_secret: string, An OAuth 1.0 consumer secret user_agent: string, The HTTP User-Agent to provide for this application. """ self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.user_agent = user_agent self.store = None # email address of the user to act on the behalf of. self._requestor = None @property def invalid(self): """True if the credentials are invalid, such as being revoked. Always returns False for Two Legged Credentials. """ return False def getrequestor(self): return self._requestor def setrequestor(self, email): self._requestor = email requestor = property(getrequestor, setrequestor, None, 'The email address of the user to act on behalf of') def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: # add in xoauth_requestor_id=self._requestor to the uri if self._requestor is None: raise MissingParameter( 'Requestor must be set before using TwoLeggedOAuthCredentials') parsed = list(urlparse.urlparse(uri)) q = parse_qsl(parsed[4]) q.append(('xoauth_requestor_id', self._requestor)) parsed[4] = urllib.urlencode(q) uri = urlparse.urlunparse(parsed) req = oauth.Request.from_consumer_and_token( self.consumer, None, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, None) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] if response_code == 401: logging.info('Access token no longer valid: %s' % content) # Do not store the invalid state of the Credentials because # being 2LO they could be reinstated in the future. raise CredentialsInvalidError("Credentials are invalid.") return resp, content http.request = new_request return http class FlowThreeLegged(Flow): """Does the Three Legged Dance for OAuth 1.0a. """ def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs): """ discovery - Section of the API discovery document that describes the OAuth endpoints. consumer_key - OAuth consumer key consumer_secret - OAuth consumer secret user_agent - The HTTP User-Agent that identifies the application. **kwargs - The keyword arguments are all optional and required parameters for the OAuth calls. """ self.discovery = discovery self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_agent = user_agent self.params = kwargs self.request_token = {} required = {} for uriinfo in discovery.itervalues(): for name, value in uriinfo['parameters'].iteritems(): if value['required'] and not name.startswith('oauth_'): required[name] = 1 for key in required.iterkeys(): if key not in self.params: raise MissingParameter('Required parameter %s not supplied' % key) def step1_get_authorize_url(self, oauth_callback='oob'): """Returns a URI to redirect to the provider. oauth_callback - Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If oauth_callback is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } body = urllib.urlencode({'oauth_callback': oauth_callback}) uri = _oauth_uri('request', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers, body=body) if resp['status'] != '200': logging.error('Failed to retrieve temporary authorization: %s', content) raise RequestError('Invalid response %s.' % resp['status']) self.request_token = dict(parse_qsl(content)) auth_params = copy.copy(self.params) auth_params['oauth_token'] = self.request_token['oauth_token'] return _oauth_uri('authorize', self.discovery, auth_params) def step2_exchange(self, verifier): """Exhanges an authorized request token for OAuthCredentials. Args: verifier: string, dict - either the verifier token, or a dictionary of the query parameters to the callback, which contains the oauth_verifier. Returns: The Credentials object. """ if not (isinstance(verifier, str) or isinstance(verifier, unicode)): verifier = verifier['oauth_verifier'] token = oauth.Token( self.request_token['oauth_token'], self.request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, token) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } uri = _oauth_uri('access', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers) if resp['status'] != '200': logging.error('Failed to retrieve access token: %s', content) raise RequestError('Invalid response %s.' % resp['status']) oauth_params = dict(parse_qsl(content)) token = oauth.Token( oauth_params['oauth_token'], oauth_params['oauth_token_secret']) return OAuthCredentials(consumer, token, self.user_agent)
[ [ 8, 0, 0.0342, 0.0083, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0414, 0.0021, 0, 0.66, 0.0476, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0476, 0.0021, 0, 0.66,...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import copy", "import httplib2", "import logging", "import oauth2 as oauth", "import urllib", "import urlparse", "from anyjson import simplejson", "tr...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
[ [ 8, 0, 0.1259, 0.037, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1556, 0.0074, 0, 0.66, 0.125, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1704, 0.0074, 0, 0.66, ...
[ "\"\"\"Utilities for Google App Engine\n\nUtilities for making it easier to use the\nGoogle API Client for Python on Google App Engine.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import pickle", "from google.appengine.ext import db", "from apiclient.oauth import OAuthCredentials", "...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 1.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle import threading from apiclient.oauth import Storage as BaseStorage class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def get(self): """Retrieve Credential from file. Returns: apiclient.oauth.Credentials """ self._lock.acquire() try: f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() credentials.set_store(self.put) except: credentials = None self._lock.release() return credentials def put(self, credentials): """Write a pickled Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._lock.acquire() f = open(self._filename, 'w') f.write(pickle.dumps(credentials)) f.close() self._lock.release()
[ [ 8, 0, 0.2619, 0.0635, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.3175, 0.0159, 0, 0.66, 0.2, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.3492, 0.0159, 0, 0.66, ...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 1.0 credentials.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import pickle", "import threading", "from apiclient.oauth import Storage as BaseStorage", "class Storage(BaseStorage):\n \"\"\"Store and retr...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value)) class FlowThreeLeggedField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): print "In to_python", value if value is None: return None if isinstance(value, apiclient.oauth.FlowThreeLegged): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value))
[ [ 1, 0, 0.2679, 0.0179, 0, 0.66, 0, 629, 0, 1, 0, 0, 629, 0, 0 ], [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0.2, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.6...
[ "import apiclient", "import base64", "import pickle", "from django.db import models", "class OAuthCredentialsField(models.Field):\n\n __metaclass__ = models.SubfieldBase\n\n def db_type(self):\n return 'VARCHAR'\n\n def to_python(self, value):", " __metaclass__ = models.SubfieldBase", " def db_t...
__version__ = "1.0c2"
[ [ 14, 0, 1, 1, 0, 0.66, 0, 162, 1, 0, 0, 0, 0, 3, 0 ] ]
[ "__version__ = \"1.0c2\"" ]
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import urllib from errors import HttpError from oauth2client.anyjson import simplejson FLAGS = gflags.FLAGS gflags.DEFINE_boolean('dump_request_response', False, 'Dump all http server requests and responses. ' ) def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if FLAGS.dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/1.0' if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if FLAGS.dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): body = simplejson.loads(content) if isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class MediaModel(JsonModel): """Model class for requests that return Media. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = 'media' def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch
[ [ 8, 0, 0.0519, 0.0182, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0649, 0.0026, 0, 0.66, 0.0625, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0701, 0.0026, 0, 0.66,...
[ "\"\"\"Model objects for requests and responses.\n\nEach API may support one or more serializations, such\nas JSON, Atom, etc. The model classes are responsible\nfor converting between the wire format and the Python\nobject representation.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import...
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from oauth2client.anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" if self.resp.get('content-type', '').startswith('application/json'): try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): reason = self.content else: reason = self.resp.reason return reason def __repr__(self): if self.uri: return '<HttpError %s when requesting %s returned "%s">' % ( self.resp.status, self.uri, self._get_reason()) else: return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(Error): """Error occured during resumable upload.""" pass class BatchError(HttpError): """Error occured during batch operations.""" def __init__(self, reason, resp=None, content=None): self.resp = resp self.content = content self.reason = reason def __repr__(self): return '<BatchError %s "%s">' % (self.resp.status, self.reason) __str__ = __repr__ class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
[ [ 8, 0, 0.1545, 0.0407, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.187, 0.0081, 0, 0.66, 0.0769, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2114, 0.0081, 0, 0.66, ...
[ "\"\"\"Errors for the library.\n\nAll exceptions defined by the library\nshould be defined in this file.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "from oauth2client.anyjson import simplejson", "class Error(Exception):\n \"\"\"Base error for this module.\"\"\"\n pass", " \"\"\"Base...
""" iri2uri Converts an IRI to a URI. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" __history__ = """ """ import urlparse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF ), (0xE000, 0xF8FF ), (0xF900, 0xFDCF ), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD ), (0x20000, 0x2FFFD ), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD ), (0x50000, 0x5FFFD ), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD ), (0x80000, 0x8FFFD ), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD ), (0xB0000, 0xBFFFD ), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD ), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD ), (0x100000, 0x10FFFD) ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri ,unicode): (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri) authority = authority.encode('idna') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ u"ftp://ftp.is.co.za/rfc/rfc1808.txt", u"http://www.ietf.org/rfc/rfc2396.txt", u"ldap://[2001:db8::7]/c=GB?objectClass?one", u"mailto:John.Doe@example.com", u"news:comp.infosystems.www.servers.unix", u"tel:+1-816-555-1212", u"telnet://192.0.2.16:80/", u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """ Test that the right type of escaping is done for each part of the URI.""" self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}")) self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}")) self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}")) self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))) self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8'))) unittest.main()
[ [ 8, 0, 0.0318, 0.0545, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0636, 0.0091, 0, 0.66, 0.0909, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0727, 0.0091, 0, 0.66...
[ "\"\"\"\niri2uri\n\nConverts an IRI to a URI.\n\n\"\"\"", "__author__ = \"Joe Gregorio (joe@bitworking.org)\"", "__copyright__ = \"Copyright 2006, Joe Gregorio\"", "__contributors__ = []", "__version__ = \"1.0.0\"", "__license__ = \"MIT\"", "__history__ = \"\"\"\n\"\"\"", "import urlparse", "escape_...
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import base64 import socket import struct import sys if getattr(socket, 'socket', None) is None: raise ImportError('socket.socket missing, proxy support unusable') PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 PROXY_TYPE_HTTP_NO_TUNNEL = 4 _defaultproxy = None _orgsocket = socket.socket class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified")) class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None self.__httptunnel = True def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def sendall(self, content, *args): """ override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed """ if not self.__httptunnel: content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args) def __rewriteproxy(self, header): """ rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. """ host, endpt = None, None hdrs = header.split("\r\n") for hdr in hdrs: if hdr.lower().startswith("host:"): host = hdr elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): endpt = hdr if host and endpt: hdrs.remove(host) hdrs.remove(endpt) host = host.split(" ")[1] endpt = endpt.split(" ") if (self.__proxy[4] != None and self.__proxy[5] != None): hdrs.insert(0, self.__getauthheader()) hdrs.insert(0, "Host: %s" % host) hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) return "\r\n".join(hdrs) def __getauthheader(self): auth = self.__proxy[4] + ":" + self.__proxy[5] return "Proxy-Authorization: Basic " + base64.b64encode(auth) def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1],portnum)) if destpair[1] == 443: self.__negotiatehttp(destpair[0],destpair[1]) else: self.__httptunnel = False elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
[ [ 8, 0, 0.0365, 0.0708, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 0.0845, 0.0205, 0, 0.66, 0.04, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0982, 0.0023, 0, 0.66, ...
[ "\"\"\"SocksiPy - Python SOCKS module.\nVersion 1.00\n\nCopyright 2006 Dan-Haim. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright ...
import Cookie import datetime import time import email.utils import calendar import base64 import hashlib import hmac import re import logging # Ripped from the Tornado Framework's web.py # http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09 # # Tornado is licensed under the Apache Licence, Version 2.0 # (http://www.apache.org/licenses/LICENSE-2.0.html). # # Example: # from vendor.prayls.lilcookies import LilCookies # cookieutil = LilCookies(self, application_settings['cookie_secret']) # cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100) # cookieutil.get_secure_cookie(name = 'mykey') class LilCookies: @staticmethod def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s @staticmethod def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 @staticmethod def _signature_from_secret(cookie_secret, *parts): """ Takes a secret salt value to create a signature for values in the `parts` param.""" hash = hmac.new(cookie_secret, digestmod=hashlib.sha1) for part in parts: hash.update(part) return hash.hexdigest() @staticmethod def _signed_cookie_value(cookie_secret, name, value): """ Returns a signed value for use in a cookie. This is helpful to have in its own method if you need to re-use this function for other needs. """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp) return "|".join([value, timestamp, signature]) @staticmethod def _verified_cookie_value(cookie_secret, name, signed_value): """Returns the un-encrypted value given the signed value if it validates, or None.""" value = signed_value if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1]) if not LilCookies._time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None def __init__(self, handler, cookie_secret): """You must specify the cookie_secret to use any of the secure methods. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. """ if len(cookie_secret) < 45: raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret) self.handler = handler self.request = handler.request self.response = handler.response self.cookie_secret = cookie_secret def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" if name in self.cookies(): return self._cookies[name].value return default def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ name = LilCookies._utf8(name) value = LilCookies._utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp, localtime=False, usegmt=True) if path: new_cookie[name]["path"] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v # The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush. for vals in new_cookie.values(): self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None))) def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies().iterkeys(): self.clear_cookie(name) def set_secure_cookie(self, name, value, expires_days=30, **kwargs): """Signs and timestamps a cookie so it cannot be forged. To read a cookie set with this method, use get_secure_cookie(). """ value = LilCookies._signed_cookie_value(self.cookie_secret, name, value) self.set_cookie(name, value, expires_days=expires_days, **kwargs) def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None.""" if value is None: value = self.get_cookie(name) return LilCookies._verified_cookie_value(self.cookie_secret, name, value) def _cookie_signature(self, *parts): return LilCookies._signature_from_secret(self.cookie_secret)
[ [ 1, 0, 0.006, 0.006, 0, 0.66, 0, 32, 0, 1, 0, 0, 32, 0, 0 ], [ 1, 0, 0.0119, 0.006, 0, 0.66, 0.1, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0179, 0.006, 0, 0.66, ...
[ "import Cookie", "import datetime", "import time", "import email.utils", "import calendar", "import base64", "import hashlib", "import hmac", "import re", "import logging", "class LilCookies:\n\n @staticmethod\n def _utf8(s):\n if isinstance(s, unicode):\n return s.encode(\"utf-8\")\n ...
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
[ [ 14, 0, 0.1667, 0.0556, 0, 0.66, 0, 189, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0.66, 0.3333, 295, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.6111, 0.0556, 0, 0...
[ "manual_verstr = \"1.5\"", "auto_build_num = \"211\"", "verstr = manual_verstr + \".\" + auto_build_num", "try:\n from pyutil.version_class import Version as pyutil_Version\n __version__ = pyutil_Version(verstr)\nexcept (ImportError, ValueError):\n # Maybe there is no pyutil installed.\n from dist...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
[ [ 8, 0, 0.2927, 0.561, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.6098, 0.0244, 0, 0.66, 0.25, 311, 0, 1, 0, 0, 311, 0, 0 ], [ 1, 0, 0.6341, 0.0244, 0, 0.66, ...
[ "\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
[ [ 8, 0, 0.3, 0.575, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.625, 0.025, 0, 0.66, 0.3333, 311, 0, 1, 0, 0, 311, 0, 0 ], [ 1, 0, 0.65, 0.025, 0, 0.66, 0.6...
[ "\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou...
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
[ [ 1, 0, 0.0204, 0.0068, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0272, 0.0068, 0, 0.66, 0.0833, 614, 0, 1, 0, 0, 614, 0, 0 ], [ 14, 0, 0.0408, 0.0068, 0, ...
[ "import re", "import urllib", "RESERVED = \":/?#[]@!$&'()*+,;=\"", "OPERATOR = \"+./;?|!@\"", "EXPLODE = \"*+\"", "MODIFIER = \":^\"", "TEMPLATE = re.compile(r\"{(?P<operator>[\\+\\./;\\?|!@])?(?P<varlist>[^}]+)}\", re.UNICODE)", "VAR = re.compile(r\"^(?P<varname>[^=\\+\\*:\\^]+)((?P<explode>[\\+\\*])...
#! /usr/bin/python # $Id: testupnpigd.py,v 1.4 2008/10/11 10:27:20 nanard Exp $ # MiniUPnP project # Author : Thomas Bernard # This Sample code is public domain. # website : http://miniupnp.tuxfamily.org/ # import the python miniupnpc module import miniupnpc import socket import BaseHTTPServer # function definition def list_redirections(): i = 0 while True: p = u.getgenericportmapping(i) if p==None: break print i, p i = i + 1 #define the handler class for HTTP connections class handler_class(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write("OK MON GARS") # create the object u = miniupnpc.UPnP() #print 'inital(default) values :' #print ' discoverdelay', u.discoverdelay #print ' lanaddr', u.lanaddr #print ' multicastif', u.multicastif #print ' minissdpdsocket', u.minissdpdsocket u.discoverdelay = 200; try: print 'Discovering... delay=%ums' % u.discoverdelay ndevices = u.discover() print ndevices, 'device(s) detected' # select an igd u.selectigd() # display information about the IGD and the internet connection print 'local ip address :', u.lanaddr externalipaddress = u.externalipaddress() print 'external ip address :', externalipaddress print u.statusinfo(), u.connectiontype() #instanciate a HTTPd object. The port is assigned by the system. httpd = BaseHTTPServer.HTTPServer((u.lanaddr, 0), handler_class) eport = httpd.server_port # find a free port for the redirection r = u.getspecificportmapping(eport, 'TCP') while r != None and eport < 65536: eport = eport + 1 r = u.getspecificportmapping(eport, 'TCP') print 'trying to redirect %s port %u TCP => %s port %u TCP' % (externalipaddress, eport, u.lanaddr, httpd.server_port) b = u.addportmapping(eport, 'TCP', u.lanaddr, httpd.server_port, 'UPnP IGD Tester port %u' % eport, '') if b: print 'Success. Now waiting for some HTTP request on http://%s:%u' % (externalipaddress ,eport) try: httpd.handle_request() httpd.server_close() except KeyboardInterrupt, details: print "CTRL-C exception!", details b = u.deleteportmapping(eport, 'TCP') if b: print 'Successfully deleted port mapping' else: print 'Failed to remove port mapping' else: print 'Failed' httpd.server_close() except Exception, e: print 'Exception :', e
[ [ 1, 0, 0.0526, 0.0526, 0, 0.66, 0, 772, 0, 1, 0, 0, 772, 0, 0 ], [ 1, 0, 0.1053, 0.0526, 0, 0.66, 0.25, 687, 0, 1, 0, 0, 687, 0, 0 ], [ 1, 0, 0.1579, 0.0526, 0, 0....
[ "import miniupnpc", "import socket", "import BaseHTTPServer", "def list_redirections():\n\ti = 0\n\twhile True:\n\t\tp = u.getgenericportmapping(i)\n\t\tif p==None:\n\t\t\tbreak\n\t\tprint(i, p)\n\t\ti = i + 1", "\ti = 0", "\twhile True:\n\t\tp = u.getgenericportmapping(i)\n\t\tif p==None:\n\t\t\tbreak\n\...
#! /usr/bin/python # $Id: setup.py,v 1.3 2009/04/17 20:59:42 nanard Exp $ # the MiniUPnP Project (c) 2007 Thomas Bernard # http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ # # python script to build the miniupnpc module under unix # # replace libminiupnpc.a by libminiupnpc.so for shared library usage from distutils.core import setup, Extension setup(name="miniupnpc", version="1.3", ext_modules=[ Extension(name="miniupnpc", sources=["miniupnpcmodule.c"], extra_objects=["libminiupnpc.a"]) ])
[ [ 1, 0, 0.6, 0.0667, 0, 0.66, 0, 152, 0, 2, 0, 0, 152, 0, 0 ], [ 8, 0, 0.8, 0.3333, 0, 0.66, 1, 234, 3, 3, 0, 0, 0, 0, 2 ] ]
[ "from distutils.core import setup, Extension", "setup(name=\"miniupnpc\", version=\"1.3\",\n ext_modules=[\n\t Extension(name=\"miniupnpc\", sources=[\"miniupnpcmodule.c\"],\n\t\t\t extra_objects=[\"libminiupnpc.a\"])\n\t\t\t ])" ]
#! /usr/bin/python # $Id: setupmingw32.py,v 1.1 2007/06/12 23:04:13 nanard Exp $ # the MiniUPnP Project (c) 2007 Thomas Bernard # http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ # # python script to build the miniupnpc module under unix # from distutils.core import setup, Extension setup(name="miniupnpc", version="1.0-RC6", ext_modules=[ Extension(name="miniupnpc", sources=["miniupnpcmodule.c"], libraries=["ws2_32"], extra_objects=["libminiupnpc.a"]) ])
[ [ 1, 0, 0.5333, 0.0667, 0, 0.66, 0, 152, 0, 2, 0, 0, 152, 0, 0 ], [ 8, 0, 0.7667, 0.4, 0, 0.66, 1, 234, 3, 3, 0, 0, 0, 0, 2 ] ]
[ "from distutils.core import setup, Extension", "setup(name=\"miniupnpc\", version=\"1.0-RC6\",\n ext_modules=[\n\t Extension(name=\"miniupnpc\", sources=[\"miniupnpcmodule.c\"],\n\t libraries=[\"ws2_32\"],\n\t\t\t extra_objects=[\"libminiupnpc.a\"])\n\t\t\t ])" ]
#! /usr/bin/python # MiniUPnP project # Author : Thomas Bernard # This Sample code is public domain. # website : http://miniupnp.tuxfamily.org/ # import the python miniupnpc module import miniupnpc import sys # create the object u = miniupnpc.UPnP() print 'inital(default) values :' print ' discoverdelay', u.discoverdelay print ' lanaddr', u.lanaddr print ' multicastif', u.multicastif print ' minissdpdsocket', u.minissdpdsocket u.discoverdelay = 200; #u.minissdpdsocket = '../minissdpd/minissdpd.sock' # discovery process, it usualy takes several seconds (2 seconds or more) print 'Discovering... delay=%ums' % u.discoverdelay print u.discover(), 'device(s) detected' # select an igd try: u.selectigd() except Exception, e: print 'Exception :', e sys.exit(1) # display information about the IGD and the internet connection print 'local ip address :', u.lanaddr print 'external ip address :', u.externalipaddress() print u.statusinfo(), u.connectiontype() #print u.addportmapping(64000, 'TCP', # '192.168.1.166', 63000, 'port mapping test', '') #print u.deleteportmapping(64000, 'TCP') port = 0 proto = 'UDP' # list the redirections : i = 0 while True: p = u.getgenericportmapping(i) if p==None: break print i, p (port, proto, (ihost,iport), desc, c, d, e) = p #print port, desc i = i + 1 print u.getspecificportmapping(port, proto)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 772, 0, 1, 0, 0, 772, 0, 0 ], [ 1, 0, 0.6667, 0.3333, 0, 0.66, 1, 509, 0, 1, 0, 0, 509, 0, 0 ] ]
[ "import miniupnpc", "import sys" ]
#! /usr/bin/python import dbus bus = dbus.SessionBus() proxy = bus.get_object('org.xchat.service', '/org/xchat/Remote') remote = dbus.Interface(proxy, 'org.xchat.connection') path = remote.Connect ("example.py", "Python example", "Example of a D-Bus client written in python", "1.0") proxy = bus.get_object('org.xchat.service', path) xchat = dbus.Interface(proxy, 'org.xchat.plugin') channels = xchat.ListGet ("channels") while xchat.ListNext (channels): name = xchat.ListStr (channels, "channel") print "------- " + name + " -------" xchat.SetContext (xchat.ListInt (channels, "context")) xchat.EmitPrint ("Channel Message", ["John", "Hi there", "@"]) users = xchat.ListGet ("users") while xchat.ListNext (users): print "Nick: " + xchat.ListStr (users, "nick") xchat.ListFree (users) xchat.ListFree (channels) print xchat.Strip ("\00312Blue\003 \002Bold!\002", -1, 1|2)
[ [ 1, 0, 0.1071, 0.0357, 0, 0.66, 0, 551, 0, 1, 0, 0, 551, 0, 0 ], [ 14, 0, 0.1786, 0.0357, 0, 0.66, 0.1, 857, 3, 0, 0, 0, 971, 10, 1 ], [ 14, 0, 0.2143, 0.0357, 0, ...
[ "import dbus", "bus = dbus.SessionBus()", "proxy = bus.get_object('org.xchat.service', '/org/xchat/Remote')", "remote = dbus.Interface(proxy, 'org.xchat.connection')", "path = remote.Connect (\"example.py\",\n\t\t \"Python example\",\n\t\t \"Example of a D-Bus client written in python\",\n\t\t ...
print("only a test")
[ [ 8, 0, 1, 0.5, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(\"only a test\")" ]
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = [name for name in os.listdir('.') if os.path.isdir(name)] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-lstdc++...
from scipy.sparse import coo_matrix from scipy.io import mmwrite from numpy.random import permutation M = N = 10 for nnz in [0, 1, 2, 5, 8, 10, 15, 20, 30, 50, 80, 100]: P = permutation(M * N)[:nnz] I = P / N J = P % N V = permutation(nnz) + 1 A = coo_matrix( (V,(I,J)) , shape=(M,N)) filename = '%03d_nonzeros.mtx' % (nnz,) mmwrite(filename, A)
[ [ 1, 0, 0.0667, 0.0667, 0, 0.66, 0, 683, 0, 1, 0, 0, 683, 0, 0 ], [ 1, 0, 0.1333, 0.0667, 0, 0.66, 0.25, 670, 0, 1, 0, 0, 670, 0, 0 ], [ 1, 0, 0.2, 0.0667, 0, 0.66,...
[ "from scipy.sparse import coo_matrix", "from scipy.io import mmwrite", "from numpy.random import permutation", "M = N = 10", "for nnz in [0, 1, 2, 5, 8, 10, 15, 20, 30, 50, 80, 100]:\n P = permutation(M * N)[:nnz]\n I = P / N\n J = P % N\n V = permutation(nnz) + 1\n\n A = coo_matrix( (V,(I,J)...
import os import inspect # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # on windows we have to do /bigobj if env['PLATFORM'] == "win32" or env['PLATFORM'] == "win64": env.Append(CPPFLAGS = "/bigobj") # find all .cus & .cpps in the current and backend/ directories sources = [] directories = ['.', 'backend'] extensions = ['*.cu', '*.cpp'] # finall all backend-specific files if env['backend'] == 'cuda' or env['backend'] == 'ocelot': directories.append(os.path.join('backend','cuda')) elif env['backend'] == 'omp': directories.append(os.path.join('backend','omp')) for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) sources.extend(env.Glob(regexp)) # filter test files using a regular expression if 'tests' in env: import re pattern = re.compile(env['tests']) necessary_sources = set(['testframework.cu']) filtered_sources = [] for f in sources: if str(f) in necessary_sources or pattern.search(f.get_contents()): filtered_sources.append(f) sources = filtered_sources # add the directory containing this file to the include path this_file = inspect.currentframe().f_code.co_filename this_dir = os.path.dirname(this_file) env.Append(CPPPATH = [this_dir]) tester = env.Program('tester', sources)
[ [ 1, 0, 0.0175, 0.0175, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0351, 0.0175, 0, 0.66, 0.0714, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 7, 0, 0.1228, 0.0877, 0, ...
[ "import os", "import inspect", "try:\n Import('env')\nexcept:\n exec(open(\"../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-lstdc++\")", " env.Ap...
import os import glob from warnings import warn cusp_abspath = os.path.abspath("../../cusp/") # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # this function builds a trivial source file from a Cusp header def trivial_source_from_header(source, target, env): src_abspath = str(source[0]) src_relpath = os.path.relpath(src_abspath, cusp_abspath) include = os.path.join('cusp', src_relpath) target_filename = str(target[0]) fid = open(target_filename, 'w') fid.write('#include <' + include + '>\n') fid.close() # CUFile builds a trivial .cu file from a Cusp header cu_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cu', src_suffix = '.h') env.Append(BUILDERS = {'CUFile' : cu_from_header_builder}) # CPPFile builds a trivial .cpp file from a Cusp header cpp_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cpp', src_suffix = '.h') env.Append(BUILDERS = {'CPPFile' : cpp_from_header_builder}) # find all user-includable .h files in the cusp tree and generate trivial source files #including them extensions = ['.h'] folders = ['', # main folder 'gallery/', 'graph/', 'io/', 'krylov/', 'precond/', 'relaxation/'] sources = [] for folder in folders: for ext in extensions: pattern = os.path.join(os.path.join(cusp_abspath, folder), "*" + ext) for fullpath in glob.glob(pattern): headerfilename = os.path.basename(fullpath) cu = env.CUFile(headerfilename.replace('.h', '.cu'), fullpath) cpp = env.CPPFile(headerfilename.replace('.h', '_cpp.cpp'), fullpath) sources.append(cu) #sources.append(cpp) # TODO: re-enable this # insure that all files #include <cusp/detail/config.h> fid = open(fullpath) if '#include <cusp/detail/config.h>' not in fid.read(): warn('Header <cusp/' + folder + headerfilename + '> does not include <cusp/detail/config.h>') # and the file with main() sources.append('main.cu') tester = env.Program('tester', sources)
[ [ 1, 0, 0.0141, 0.0141, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0282, 0.0141, 0, 0.66, 0.0667, 958, 0, 1, 0, 0, 958, 0, 0 ], [ 1, 0, 0.0423, 0.0141, 0, ...
[ "import os", "import glob", "from warnings import warn", "cusp_abspath = os.path.abspath(\"../../cusp/\")", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
#!/usr/bin/env python import os,csv device_id = '0' # index of the device to use binary_filename = '../spmv' # command used to run the tests output_file = 'benchmark_output.log' # file where results are stored # The unstructured matrices are available online: # http://www.nvidia.com/content/NV_Research/matrices.zip mats = [] unstructured_path = '~/scratch/Matrices/williams/mm/' unstructured_mats = [('Dense','dense2.mtx'), ('Protein','pdb1HYS.mtx'), ('FEM/Spheres','consph.mtx'), ('FEM/Cantilever','cant.mtx'), ('Wind Tunnel','pwtk.mtx'), ('FEM/Harbor','rma10.mtx'), ('QCD','qcd5_4.mtx'), ('FEM/Ship','shipsec1.mtx'), ('Economics','mac_econ_fwd500.mtx'), ('Epidemiology','mc2depi.mtx'), ('FEM/Accelerator','cop20k_A.mtx'), ('Circuit','scircuit.mtx'), ('Webbase','webbase-1M.mtx'), ('LP','rail4284.mtx') ] unstructured_mats = [ mat + (unstructured_path,) for mat in unstructured_mats] structured_path = '~/scratch/Matrices/stencil/' structured_mats = [('Laplacian_3pt_stencil', '3pt_1000000.mtx'), ('Laplacian_5pt_stencil', '5pt_1000x1000.mtx'), ('Laplacian_7pt_stencil', '7pt_100x100x100.mtx'), ('Laplacian_9pt_stencil', '9pt_1000x1000.mtx'), ('Laplacian_27pt_stencil', '27pt_100x100x100.mtx')] structured_mats = [ mat + (structured_path,) for mat in structured_mats] # assemble suite of matrices trials = unstructured_mats + structured_mats def run_tests(value_type): # remove previous result (if present) open(output_file,'w').close() # run benchmark for each file for matrix,filename,path in trials: matrix_filename = path + filename # setup the command to execute cmd = binary_filename cmd += ' ' + matrix_filename # e.g. pwtk.mtx cmd += ' --device=' + device_id # e.g. 0 or 1 cmd += ' --value_type=' + value_type # e.g. float or double # execute the benchmark on this file os.system(cmd) # process output_file matrices = {} results = {} kernels = set() # fid = open(output_file) for line in fid.readlines(): tokens = dict( [tuple(part.split('=')) for part in line.split()] ) if 'file' in tokens: file = os.path.split(tokens['file'])[1] matrices[file] = tokens results[file] = {} else: kernel = tokens['kernel'] results[file][kernel] = tokens kernels.add(tokens['kernel']) ## put CPU results before GPU results #kernels = ['csr_serial'] + sorted(kernels - set(['csr_serial'])) kernels = sorted(kernels) # write out CSV formatted results def write_csv(field): fid = open('bench_' + value_type + '_' + field + '.csv','w') writer = csv.writer(fid) writer.writerow(['matrix','file','rows','cols','nonzeros'] + kernels) for (matrix,file,path) in trials: line = [matrix, file, matrices[file]['rows'], matrices[file]['cols'], matrices[file]['nonzeros']] matrix_results = results[file] for kernel in kernels: if kernel in matrix_results: line.append( matrix_results[kernel][field] ) else: line.append(' ') writer.writerow( line ) fid.close() write_csv('gflops') #GFLOP/s write_csv('gbytes') #GBytes/s run_tests('float') run_tests('double')
[ [ 1, 0, 0.0189, 0.0094, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 14, 0, 0.0377, 0.0094, 0, 0.66, 0.0714, 689, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0566, 0.0094, 0, ...
[ "import os,csv", "device_id = '0' # index of the device to use", "binary_filename = '../spmv' # command used to run the tests", "output_file = 'benchmark_output.log' # file where results are stored", "mats = []", "unstructured_path = '~/scratch/Matrices/williams/mm/'", "unstruct...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
[ [ 1, 0, 0.0345, 0.0345, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.069, 0.0345, 0, 0.66, 0.1111, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.1034, 0.0345, 0, 0...
[ "import os", "import inspect", "import glob", "try:\n Import('env')\nexcept:\n exec(open(\"../../build/build-env.py\"))\n env = Environment()", " Import('env')", " exec(open(\"../../build/build-env.py\"))", " env = Environment()", "if env['PLATFORM'] == \"darwin\":\n env.Append(LINKFLAGS = \"-l...
#!/usr/bin/python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import json import httplib from urlparse import urlparse if len(sys.argv) == 3: appId = sys.argv[1]; appSecret = sys.argv[2]; print("Deleting test users for app " + appId); else: print("Must specify appId and appSecret."); exit(-1); host = "graph.facebook.com"; fmtGet = "/{0}/accounts/test-users?access_token={0}|{1}"; fmtDel = "/{0}?method=delete&access_token={1}|{2}"; usersPath = fmtGet.format(appId, appSecret); while usersPath: print("Getting users via: " + usersPath); conn = httplib.HTTPSConnection(host); conn.request("GET", usersPath); users = json.loads(conn.getresponse().read()); print "Got", len(users["data"]), "users."; for user in users["data"]: print("Deleting user {0}".format(user["id"])); delPath = fmtDel.format(user["id"], appId, appSecret); conn = httplib.HTTPSConnection(host); conn.request("GET", delPath); deleteResult = conn.getresponse().read(); if (deleteResult <> "true"): print("delete failed, got " + deleteResult); if not "paging" in users: break; paging = users["paging"]; if not "next" in users["paging"]: break; nextUrl = paging["next"]; prefix = "https://graph.facebook.com"; if not nextUrl.startswith(prefix): print("Paging url does not start with "+prefix); break; usersPath = nextUrl[len(prefix):]; print("Continuing next page at: " + usersPath);
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 463, 0, 1, 0, 0, 463, 0, 0 ], [ 1, 0, 0.6, 0.2, 0, 0.66, 0.6667, ...
[ "import sys", "import json", "import httplib", "from urlparse import urlparse" ]
#!/usr/bin/python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import json import httplib from urlparse import urlparse if len(sys.argv) == 3: appId = sys.argv[1]; appSecret = sys.argv[2]; print("Deleting test users for app " + appId); else: print("Must specify appId and appSecret."); exit(-1); host = "graph.facebook.com"; fmtGet = "/{0}/accounts/test-users?access_token={0}|{1}"; fmtDel = "/{0}?method=delete&access_token={1}|{2}"; usersPath = fmtGet.format(appId, appSecret); while usersPath: print("Getting users via: " + usersPath); conn = httplib.HTTPSConnection(host); conn.request("GET", usersPath); users = json.loads(conn.getresponse().read()); print "Got", len(users["data"]), "users."; for user in users["data"]: print("Deleting user {0}".format(user["id"])); delPath = fmtDel.format(user["id"], appId, appSecret); conn = httplib.HTTPSConnection(host); conn.request("GET", delPath); deleteResult = conn.getresponse().read(); if (deleteResult <> "true"): print("delete failed, got " + deleteResult); if not "paging" in users: break; paging = users["paging"]; if not "next" in users["paging"]: break; nextUrl = paging["next"]; prefix = "https://graph.facebook.com"; if not nextUrl.startswith(prefix): print("Paging url does not start with "+prefix); break; usersPath = nextUrl[len(prefix):]; print("Continuing next page at: " + usersPath);
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 463, 0, 1, 0, 0, 463, 0, 0 ], [ 1, 0, 0.6, 0.2, 0, 0.66, 0.6667, ...
[ "import sys", "import json", "import httplib", "from urlparse import urlparse" ]
#!/usr/bin/python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import json import httplib from urlparse import urlparse if len(sys.argv) == 3: appId = sys.argv[1]; appSecret = sys.argv[2]; print("Deleting test users for app " + appId); else: print("Must specify appId and appSecret."); exit(-1); host = "graph.facebook.com"; fmtGet = "/{0}/accounts/test-users?access_token={0}|{1}"; fmtDel = "/{0}?method=delete&access_token={1}|{2}"; usersPath = fmtGet.format(appId, appSecret); while usersPath: print("Getting users via: " + usersPath); conn = httplib.HTTPSConnection(host); conn.request("GET", usersPath); users = json.loads(conn.getresponse().read()); print "Got", len(users["data"]), "users."; for user in users["data"]: print("Deleting user {0}".format(user["id"])); delPath = fmtDel.format(user["id"], appId, appSecret); conn = httplib.HTTPSConnection(host); conn.request("GET", delPath); deleteResult = conn.getresponse().read(); if (deleteResult <> "true"): print("delete failed, got " + deleteResult); if not "paging" in users: break; paging = users["paging"]; if not "next" in users["paging"]: break; nextUrl = paging["next"]; prefix = "https://graph.facebook.com"; if not nextUrl.startswith(prefix): print("Paging url does not start with "+prefix); break; usersPath = nextUrl[len(prefix):]; print("Continuing next page at: " + usersPath);
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 463, 0, 1, 0, 0, 463, 0, 0 ], [ 1, 0, 0.6, 0.2, 0, 0.66, 0.6667, ...
[ "import sys", "import json", "import httplib", "from urlparse import urlparse" ]
#!/usr/bin/python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import json import httplib from urlparse import urlparse if len(sys.argv) == 3: appId = sys.argv[1]; appSecret = sys.argv[2]; print("Deleting test users for app " + appId); else: print("Must specify appId and appSecret."); exit(-1); host = "graph.facebook.com"; fmtGet = "/{0}/accounts/test-users?access_token={0}|{1}"; fmtDel = "/{0}?method=delete&access_token={1}|{2}"; usersPath = fmtGet.format(appId, appSecret); while usersPath: print("Getting users via: " + usersPath); conn = httplib.HTTPSConnection(host); conn.request("GET", usersPath); users = json.loads(conn.getresponse().read()); print "Got", len(users["data"]), "users."; for user in users["data"]: print("Deleting user {0}".format(user["id"])); delPath = fmtDel.format(user["id"], appId, appSecret); conn = httplib.HTTPSConnection(host); conn.request("GET", delPath); deleteResult = conn.getresponse().read(); if (deleteResult <> "true"): print("delete failed, got " + deleteResult); if not "paging" in users: break; paging = users["paging"]; if not "next" in users["paging"]: break; nextUrl = paging["next"]; prefix = "https://graph.facebook.com"; if not nextUrl.startswith(prefix): print("Paging url does not start with "+prefix); break; usersPath = nextUrl[len(prefix):]; print("Continuing next page at: " + usersPath);
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 463, 0, 1, 0, 0, 463, 0, 0 ], [ 1, 0, 0.6, 0.2, 0, 0.66, 0.6667, ...
[ "import sys", "import json", "import httplib", "from urlparse import urlparse" ]
#!/usr/bin/env python import time t = time.time() u = time.gmtime(t) s = time.strftime('%a, %e %b %Y %T GMT', u) print 'Content-Type: text/javascript' print 'Cache-Control: no-cache' print 'Date: ' + s print 'Expires: ' + s print '' print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
[ [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 14, 0, 0.2727, 0.0909, 0, 0.66, 0.1111, 15, 3, 0, 0, 0, 654, 10, 1 ], [ 14, 0, 0.3636, 0.0909, 0, ...
[ "import time", "t = time.time()", "u = time.gmtime(t)", "s = time.strftime('%a, %e %b %Y %T GMT', u)", "print('Content-Type: text/javascript')", "print('Cache-Control: no-cache')", "print('Date: ' + s)", "print('Expires: ' + s)", "print('')", "print('var timeskew = new Date().getTime() - ' + str(t...
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
[ [ 14, 0, 0.0557, 0.0033, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0689, 0.0033, 0, 0.66, 0.0333, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0721, 0.0033, 0, 0...
[ "__author__ = 'afshar@google.com (Ali Afshar)'", "import os", "import httplib2", "import sessions", "from google.appengine.ext import db", "from google.appengine.ext.webapp import template", "from apiclient.discovery import build_from_document", "from apiclient.http import MediaUpload", "from oauth2...
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' # Add the library location to the path import sys sys.path.insert(0, 'lib') import os import httplib2 import sessions from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build from apiclient.http import MediaUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import AccessTokenRefreshError from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') def SibPath(name): """Generate a path that is a sibling of this file. Args: name: Name of sibling file. Returns: Path to sibling file. """ return os.path.join(os.path.dirname(__file__), name) # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session-secret SESSION_SECRET = open(SibPath('session.secret')).read() INDEX_HTML = open(SibPath('index.html')).read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials. The CredentialsProperty is provided by the Google API Python Client, and is used by the Storage classes to store OAuth 2.0 credentials in the data store.""" credentials = CredentialsProperty() def CreateService(service, version, creds): """Create a Google API service. Load an API service from a discovery document and authorize it with the provided credentials. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). creds: Credentials used to authorize service. Returns: Authorized Google API service. """ # Instantiate an Http instance http = httplib2.Http() # Authorize the Http instance with the passed credentials creds.authorize(http) # Build a service from the passed discovery document path return build(service, version, http=http) class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.ids = [] @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get('state')) class BaseDriveHandler(webapp.RequestHandler): """Base request handler for drive applications. Adds Authorization support for Drive. """ def CreateOAuthFlow(self): """Create OAuth2.0 flow controller This controller can be used to perform all parts of the OAuth 2.0 dance including exchanging an Authorization code. Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = flow_from_clientsecrets('client_secrets.json', scope='') # Dynamically set the redirect_uri based on the request URL. This is extremely # convenient for debugging to an alternative host without manually setting the # redirect URI. flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0] return flow def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. code = self.request.get('code') if not code: # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. users_service = CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. userid = users_service.userinfo().get().execute().get('id') # Store the user id in the user's cookie-based session. session = sessions.LilCookies(self, SESSION_SECRET) session.set_secure_cookie(name='userid', value=userid) # Store the credentials in the data store using the userid as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.redirect(uri) def RespondJSON(self, data): """Generate a JSON response and return it to the client. Args: data: The data that will be converted to JSON to return. """ self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(data)) def CreateAuthorizedService(self, service, version): """Create an authorize service instance. The service can only ever retrieve the credentials from the session. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). Returns: Authorized service or redirect to authorization flow if no credentials. """ # For the service, the session holds the credentials creds = self.GetSessionCredentials() if creds: # If the session contains credentials, use them to create a Drive service # instance. return CreateService(service, version, creds) else: # If no credentials could be loaded from the session, redirect the user to # the authorization page. self.RedirectAuth() def CreateDrive(self): """Create a drive client instance.""" return self.CreateAuthorizedService('drive', 'v2') def CreateUserInfo(self): """Create a user info client instance.""" return self.CreateAuthorizedService('oauth2', 'v2') class MainPage(BaseDriveHandler): """Web handler for the main page. Handles requests and returns the user interface for Open With and Create cases. Responsible for parsing the state provided from the Drive UI and acting appropriately. """ def get(self): """Handle GET for Create New and Open With. This creates an authorized client, and checks whether a resource id has been passed or not. If a resource ID has been passed, this is the Open With use-case, otherwise it is the Create New use-case. """ # Generate a state instance for the request, this includes the action, and # the file id(s) that have been sent from the Drive user interface. drive_state = DriveState.FromRequest(self.request) if drive_state.action == 'open' and len(drive_state.ids) > 0: code = self.request.get('code') if code: code = '?code=%s' % code self.redirect('/#edit/%s%s' % (drive_state.ids[0], code)) return # Fetch the credentials by extracting an OAuth 2.0 authorization code from # the request URL. If the code is not present, redirect to the OAuth 2.0 # authorization URL. creds = self.GetCodeCredentials() if not creds: return self.RedirectAuth() # Extract the numerical portion of the client_id from the stored value in # the OAuth flow. You could also store this value as a separate variable # somewhere. client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0] self.RenderTemplate() def RenderTemplate(self): """Render a named template in a context.""" self.response.headers['Content-Type'] = 'text/html' self.response.out.write(INDEX_HTML) class ServiceHandler(BaseDriveHandler): """Web handler for the service to read and write to Drive.""" def post(self): """Called when HTTP POST requests are received by the web application. The POST body is JSON which is deserialized and used as values to create a new file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() # Create a new file data structure. resource = { 'title': data['title'], 'description': data['description'], 'mimeType': data['mimeType'], } try: # Make an insert request to create a new file. A MediaInMemoryUpload # instance is used to upload the file body. resource = service.files().insert( body=resource, media_body=MediaInMemoryUpload( data.get('content', ''), data['mimeType'], resumable=True) ).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: resp, f['content'] = service._http.request(downloadUrl) else: f['content'] = '' else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() def put(self): """Called when HTTP PUT requests are received by the web application. The PUT body is JSON which is deserialized and used as values to update a file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() try: # Create a new file data structure. content = data.get('content') if 'content' in data: data.pop('content') if content is not None: # Make an update request to update the file. A MediaInMemoryUpload # instance is used to upload the file body. Because of a limitation, this # request must be made in two parts, the first to update the metadata, and # the second to update the body. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data, media_body=MediaInMemoryUpload( content, data['mimeType'], resumable=True) ).execute() else: # Only update the metadata, a patch request is prefered but not yet # supported on Google App Engine; see # http://code.google.com/p/googleappengine/issues/detail?id=6316. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body) class UserHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateUserInfo() if service is None: return try: result = service.userinfo().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class AboutHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateDrive() if service is None: return try: result = service.about().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] # Create an WSGI application suitable for running on App Engine application = webapp.WSGIApplication( [('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler), ('/user', UserHandler)], # XXX Set to False in production. debug=True ) def main(): """Main entry point for executing a request with this handler.""" run_wsgi_app(application) if __name__ == "__main__": main()
[ [ 14, 0, 0.0281, 0.0017, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0347, 0.0017, 0, 0.66, 0.0303, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 8, 0, 0.0364, 0.0017, 0, 0...
[ "__author__ = 'afshar@google.com (Ali Afshar)'", "import sys", "sys.path.insert(0, 'lib')", "import os", "import httplib2", "import sessions", "from google.appengine.ext import webapp", "from google.appengine.ext.webapp.util import run_wsgi_app", "from google.appengine.ext import db", "from google...
#!/usr/bin/env python # Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module to enforce different constraints on flags. A validator represents an invariant, enforced over a one or more flags. See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual. """ __author__ = 'olexiy@google.com (Olexiy Oryeshko)' class Error(Exception): """Thrown If validator constraint is not satisfied.""" class Validator(object): """Base class for flags validators. Users should NOT overload these classes, and use gflags.Register... methods instead. """ # Used to assign each validator an unique insertion_index validators_count = 0 def __init__(self, checker, message): """Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user """ self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered (CL/18694236) self.insertion_index = Validator.validators_count def Verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._GetInputToCheckerFunction(flag_values) if not self.checker(param): raise Error(self.message) def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded') def PrintFlagsWithValues(self, flag_values): raise NotImplementedError('This method should be overloaded') def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator. """ raise NotImplementedError('This method should be overloaded') class SimpleValidator(Validator): """Validator behind RegisterValidator() method. Validates that a single flag passes its checker function. The checker function takes the flag value and returns True (if value looks fine) or, if flag value is not valid, either returns False or raises an Exception.""" def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name def GetFlagsNames(self): return [self.flag_name] def PrintFlagsWithValues(self, flag_values): return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value) def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag. """ return flag_values[self.flag_name].value class DictionaryValidator(Validator): """Validator behind RegisterDictionaryValidator method. Validates that flag values pass their common checker function. The checker function takes flag values and returns True (if values look fine) or, if values are not valid, either returns False or raises an Exception. """ def __init__(self, flag_names, checker, message): """Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names) def PrintFlagsWithValues(self, flag_values): prefix = 'flags ' flags_with_values = [] for key in self.flag_names: flags_with_values.append('%s=%s' % (key, flag_values[key].value)) return prefix + ', '.join(flags_with_values) def GetFlagsNames(self): return self.flag_names
[ [ 8, 0, 0.1818, 0.0267, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.2032, 0.0053, 0, 0.66, 0.2, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 3, 0, 0.2219, 0.0107, 0, 0.66, ...
[ "\"\"\"Module to enforce different constraints on flags.\n\nA validator represents an invariant, enforced over a one or more flags.\nSee 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.\n\"\"\"", "__author__ = 'olexiy@google.com (Olexiy Oryeshko)'", "class Error(Exception):\n \"\"\"Thrown If val...
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import hashlib import logging import time from OpenSSL import crypto from anyjson import simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds class AppIdentityError(Exception): pass class Verifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was singed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return Verifier(pubkey) class Signer(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey, The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in P12 format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ pkey = crypto.load_pkcs12(key, password).get_privatekey() return Signer(pkey) def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logging.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed
[ [ 1, 0, 0.0738, 0.0041, 0, 0.66, 0, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.0779, 0.0041, 0, 0.66, 0.0625, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 1, 0, 0.082, 0.0041, 0, 0...
[ "import base64", "import hashlib", "import logging", "import time", "from OpenSSL import crypto", "from anyjson import simplejson", "CLOCK_SKEW_SECS = 300 # 5 minutes in seconds", "AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds", "MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds", "cla...
# Copyright 2011 Google Inc. All Rights Reserved. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '<client id>', 'userAgent': '<user agent>', 'scope': '<scope>' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import errno import logging import os import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials from locked_file import LockedFile logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or list of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ filename = os.path.realpath(os.path.expanduser(filename)) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly)) finally: _multistores_lock.release() if type(scope) is list: scope = ' '.join(scope) return multistore._get_storage(client_id, user_agent, scope) class _MultiStore(object): """A file backed store for multiple credentials.""" def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._file = LockedFile(filename, 'r+b', 'rb') self._thread_lock = threading.Lock() self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # (client_id, user_agent, scope) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, client_id, user_agent, scope): self._multistore = multistore self._client_id = client_id self._user_agent = user_agent self._scope = scope def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential( self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(credentials, self._scope) def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._delete_credential(self._client_id, self._user_agent, self._scope) def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._file.filename()): old_umask = os.umask(0177) try: open(self._file.filename(), 'a+b').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() self._file.open_and_lock() if not self._file.is_locked(): self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._file.filename()) if os.path.getsize(self._file.filename()) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" self._file.unlock_and_close() self._thread_lock.release() def _locked_json_read(self): """Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON. """ assert self._thread_lock.locked() self._file.file_handle().seek(0) return simplejson.load(self._file.file_handle()) def _locked_json_write(self, data): """Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written. """ assert self._thread_lock.locked() if self._read_only: return self._file.file_handle().seek(0) simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2) self._file.file_handle().truncate() def _refresh_data_cache(self): """Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store. """ self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. ' 'Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object. """ raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = { 'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2] } raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_credential(self, client_id, user_agent, scope): """Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present """ key = (client_id, user_agent, scope) return self._data.get(key, None) def _update_credential(self, cred, scope): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: cred: The OAuth2Credential to update/set scope: The scope(s) that this credential covers """ key = (cred.client_id, cred.user_agent, scope) self._data[key] = cred self._write() def _delete_credential(self, client_id, user_agent, scope): """Delete a credential and write the multistore. This must be called when the multistore is locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: The scope(s) that this credential covers """ key = (client_id, user_agent, scope) try: del self._data[key] except KeyError: pass self._write() def _get_storage(self, client_id, user_agent, scope): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, client_id, user_agent, scope)
[ [ 8, 0, 0.0437, 0.0741, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0847, 0.0026, 0, 0.66, 0.0588, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0899, 0.0026, 0, 0.66,...
[ "\"\"\"Multi-credential file store with lock support.\n\nThis module implements a JSON credential store where multiple\ncredentials can be stored in one file. That file supports locking\nboth in a single process and across processes.\n\nThe credential themselves are keyed off of:\n* client_id", "__author__ = 'jb...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover # Should work for Python2.6 and higher. import json as simplejson except ImportError: # pragma: no cover try: import simplejson except ImportError: # Try to import from django, should work on App Engine from django.utils import simplejson
[ [ 8, 0, 0.5312, 0.1562, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.6562, 0.0312, 0, 0.66, 0.5, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 7, 0, 0.875, 0.2812, 0, 0.66, ...
[ "\"\"\"Utility module to import a JSON module\n\nHides all the messy details of exactly where\nwe get a simplejson module from.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "try: # pragma: no cover\n # Should work for Python2.6 and higher.\n import json as simplejson\nexcept ImportError: #...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse from anyjson import simplejson HAS_OPENSSL = False try: from oauth2client.crypt import Signer from oauth2client.crypt import make_signed_jwt from oauth2client.crypt import verify_signed_jwt_with_certs HAS_OPENSSL = True except ImportError: pass try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' # Constant to use for the out of band OAuth 2.0 flow. OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob' class Error(Exception): """Base error for this module.""" pass class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" pass class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" pass class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ pass class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" pass class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" pass def _abstract(): raise NotImplementedError('You need to override this function') class MemoryCache(object): """httplib2 Cache implementation which only caches locally.""" def __init__(self): self.cache = {} def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value def delete(self, key): self.cache.pop(key, None) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Credentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract() def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ _abstract() def _to_json(self, strip): """Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: if member in d: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] try: m = __import__(module) except ImportError: # In case there's an object from the old package structure, update it module = module.replace('.apiclient', '') m = __import__(module) m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ return Credentials() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() def delete(self): """Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None """ self.acquire_lock() try: return self.locked_delete() finally: self.release_lock() class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. id_token: object, The identity of the resource owner. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not self.access_token: logger.info('Attempting refresh to obtain initial access_token') self._refresh(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} self.apply(headers) if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) if resp.status == 401: logger.info('Refreshing due to a 401') self._refresh(request_orig) self.apply(headers) return request_orig(uri, method, body, headers, redirections, connection_type) else: return (resp, content) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. setattr(http.request, 'credentials', self) return http def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ self._refresh(http.request) def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ headers['Authorization'] = 'Bearer ' + self.access_token def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ data = simplejson.loads(s) if 'token_expiry' in data and not isinstance(data['token_expiry'], datetime.datetime): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], data.get('id_token', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = datetime.datetime.utcnow() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ if not self.store: self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refreshing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except: pass raise AccessTokenRefreshError(error_msg) class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable that when passed a Credential will store the credential back to where it came from. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed.") class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion_type': self.assertion_type, 'assertion': assertion, 'grant_type': 'assertion', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() if HAS_OPENSSL: # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then # don't create the SignedJwtAssertionCredentials or the verify_id_token() # method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in P12 format. scope: string or list of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key. user_agent: string, HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. kwargs: kwargs, Additional parameters to add to the JWT token, for example prn=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( 'http://oauth.net/grant_type/jwt/1.0/bearer', user_agent, token_uri=token_uri, ) if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.private_key = private_key self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], data['private_key'], data['private_key_password'], data['scope'], data['user_agent'], data['token_uri'], data['kwargs'] ) retval.invalid = data['invalid'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logger.debug(str(payload)) return make_signed_jwt( Signer.from_string(self.private_key, self.private_key_password), payload) # Only used in verify_id_token(), which is always calling to the same URI # for the certs. _cached_http = httplib2.Http(MemoryCache()) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = _cached_http resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri = 'postmessage', http=None, user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token'): """Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token """ flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent, 'https://accounts.google.com/o/oauth2/auth', token_uri) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials def credentials_from_clientsecrets_and_code(filename, scope, code, message = None, redirect_uri = 'postmessage', http=None): """Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ flow = flow_from_clientsecrets(filename, scope, message) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = { 'access_type': 'offline', } self.params.update(kwargs) self.redirect_uri = None def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ self.redirect_uri = redirect_uri query = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, } query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def step2_exchange(self, code, http=None): """Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError if a problem occured exchanging the code for a refresh_token. """ if not (isinstance(code, str) or isinstance(code, unicode)): if 'code' not in code: if 'error' in code: error_msg = code['error'] else: error_msg = 'No code was supplied in the query parameters.' raise FlowExchangeError(error_msg) else: code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if simplejson.loads fails? d = simplejson.loads(content) access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token: %s' % content) return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, id_token=d.get('id_token', None)) else: logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except: pass raise FlowExchangeError(error_msg) def flow_from_clientsecrets(filename, scope, message=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) to request. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, None, # user_agent client_info['auth_uri'], client_info['token_uri']) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
[ [ 8, 0, 0.0145, 0.0035, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0176, 0.0009, 0, 0.66, 0.0244, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0193, 0.0009, 0, 0.66,...
[ "\"\"\"An OAuth 2.0 client.\n\nTools for interacting with OAuth 2.0 protected resources.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import base64", "import clientsecrets", "import copy", "import datetime", "import httplib2", "import logging", "import os", "import sys", "im...
# Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
[ [ 8, 0, 0.1619, 0.0476, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.2, 0.0095, 0, 0.66, 0.0909, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2286, 0.0095, 0, 0.66, ...
[ "\"\"\"Utilities for reading OAuth 2.0 client secret files.\n\nA client_secrets.json file contains all the information needed to interact with\nan OAuth 2.0 protected service.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "from anyjson import simplejson", "TYPE_WEB = 'web'", "TYPE_INSTALL...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import os import stat import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask) def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._create_file_if_needed() f = open(self._filename, 'wb') f.write(credentials.to_json()) f.close() def locked_delete(self): """Delete Credentials file. Args: credentials: Credentials, the credentials to store. """ os.unlink(self._filename)
[ [ 8, 0, 0.1604, 0.0472, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1981, 0.0094, 0, 0.66, 0.125, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.217, 0.0094, 0, 0.66, ...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 2.0\ncredentials.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import os", "import stat", "import threading", "from anyjson import simplejson", "from client import Storage as BaseStorage", "from clien...
__version__ = "1.0c2"
[ [ 14, 0, 1, 1, 0, 0.66, 0, 162, 1, 0, 0, 0, 0, 3, 0 ] ]
[ "__version__ = \"1.0c2\"" ]
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save() def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query).delete()
[ [ 8, 0, 0.1371, 0.0403, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1694, 0.0081, 0, 0.66, 0.1111, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1855, 0.0081, 0, 0.66,...
[ "\"\"\"OAuth 2.0 utilities for Django.\n\nUtilities for using OAuth 2.0 in conjunction with\nthe Django datastore.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import oauth2client", "import base64", "import pickle", "from django.db import models", "from oauth2client.client import St...
# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
[ [ 8, 0, 0.0814, 0.1105, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1453, 0.0058, 0, 0.66, 0.0833, 162, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1512, 0.0058, 0, 0.66...
[ "\"\"\"MIME-Type Parser\n\nThis module provides basic functions for handling mime-types. It can handle\nmatching mime-types against a list of media-ranges. See section 14.1 of the\nHTTP specification [RFC 2616] for a complete explanation.\n\n http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1", "__v...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from oauth2client.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] def _prettyPrintSchema(self, schema, seen=None, dent=0): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" def __init__(self, schema, seen, dent=0): """Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % str(value), schema.get('description', '')) elif stype == 'integer': value = schema.get('default', '42') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'number': value = schema.get('default', '3.14') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema)
[ [ 8, 0, 0.1205, 0.1452, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.2046, 0.0033, 0, 0.66, 0.2, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2112, 0.0033, 0, 0.66, ...
[ "\"\"\"Schema processing for discovery based APIs\n\nSchemas holds an APIs discovery schemas. It can return those schema as\ndeserialized JSON objects, or pretty print them as prototype objects that\nconform to the schema.\n\nFor example, given the schema:", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", ...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson
[ [ 8, 0, 0.5312, 0.1562, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.6562, 0.0312, 0, 0.66, 0.5, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 7, 0, 0.875, 0.2812, 0, 0.66, ...
[ "\"\"\"Utility module to import a JSON module\n\nHides all the messy details of exactly where\nwe get a simplejson module from.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "try: # pragma: no cover\n import simplejson\nexcept ImportError: # pragma: no cover\n try:\n # Try to import from...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy import httplib2 import logging import oauth2 as oauth import urllib import urlparse from anyjson import simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Error occurred during request.""" pass class MissingParameter(Error): pass class CredentialsInvalidError(Error): pass def _abstract(): raise NotImplementedError('You need to override this function') def _oauth_uri(name, discovery, params): """Look up the OAuth URI from the discovery document and add query parameters based on params. name - The name of the OAuth URI to lookup, one of 'request', 'access', or 'authorize'. discovery - Portion of discovery document the describes the OAuth endpoints. params - Dictionary that is used to form the query parameters for the specified URI. """ if name not in ['request', 'access', 'authorize']: raise KeyError(name) keys = discovery[name]['parameters'].keys() query = {} for key in keys: if key in params: query[key] = params[key] return discovery[name]['url'] + '?' + urllib.urlencode(query) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. """ def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. """ def get(self): """Retrieve credential. Returns: apiclient.oauth.Credentials """ _abstract() def put(self, credentials): """Write a credential. Args: credentials: Credentials, the credentials to store. """ _abstract() class OAuthCredentials(Credentials): """Credentials object for OAuth 1.0a """ def __init__(self, consumer, token, user_agent): """ consumer - An instance of oauth.Consumer. token - An instance of oauth.Token constructed with the access token and secret. user_agent - The HTTP User-Agent to provide for this application. """ self.consumer = consumer self.token = token self.user_agent = user_agent self.store = None # True if the credentials have been revoked self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, "_invalid", False) def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: req = oauth.Request.from_consumer_and_token( self.consumer, self.token, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, self.token) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] # Update the stored credential if it becomes invalid. if response_code == 401: logging.info('Access token no longer valid: %s' % content) self._invalid = True if self.store is not None: self.store(self) raise CredentialsInvalidError("Credentials are no longer valid.") return resp, content http.request = new_request return http class TwoLeggedOAuthCredentials(Credentials): """Two Legged Credentials object for OAuth 1.0a. The Two Legged object is created directly, not from a flow. Once you authorize and httplib2.Http instance you can change the requestor and that change will propogate to the authorized httplib2.Http instance. For example: http = httplib2.Http() http = credentials.authorize(http) credentials.requestor = 'foo@example.info' http.request(...) credentials.requestor = 'bar@example.info' http.request(...) """ def __init__(self, consumer_key, consumer_secret, user_agent): """ Args: consumer_key: string, An OAuth 1.0 consumer key consumer_secret: string, An OAuth 1.0 consumer secret user_agent: string, The HTTP User-Agent to provide for this application. """ self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.user_agent = user_agent self.store = None # email address of the user to act on the behalf of. self._requestor = None @property def invalid(self): """True if the credentials are invalid, such as being revoked. Always returns False for Two Legged Credentials. """ return False def getrequestor(self): return self._requestor def setrequestor(self, email): self._requestor = email requestor = property(getrequestor, setrequestor, None, 'The email address of the user to act on behalf of') def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: # add in xoauth_requestor_id=self._requestor to the uri if self._requestor is None: raise MissingParameter( 'Requestor must be set before using TwoLeggedOAuthCredentials') parsed = list(urlparse.urlparse(uri)) q = parse_qsl(parsed[4]) q.append(('xoauth_requestor_id', self._requestor)) parsed[4] = urllib.urlencode(q) uri = urlparse.urlunparse(parsed) req = oauth.Request.from_consumer_and_token( self.consumer, None, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, None) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] if response_code == 401: logging.info('Access token no longer valid: %s' % content) # Do not store the invalid state of the Credentials because # being 2LO they could be reinstated in the future. raise CredentialsInvalidError("Credentials are invalid.") return resp, content http.request = new_request return http class FlowThreeLegged(Flow): """Does the Three Legged Dance for OAuth 1.0a. """ def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs): """ discovery - Section of the API discovery document that describes the OAuth endpoints. consumer_key - OAuth consumer key consumer_secret - OAuth consumer secret user_agent - The HTTP User-Agent that identifies the application. **kwargs - The keyword arguments are all optional and required parameters for the OAuth calls. """ self.discovery = discovery self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_agent = user_agent self.params = kwargs self.request_token = {} required = {} for uriinfo in discovery.itervalues(): for name, value in uriinfo['parameters'].iteritems(): if value['required'] and not name.startswith('oauth_'): required[name] = 1 for key in required.iterkeys(): if key not in self.params: raise MissingParameter('Required parameter %s not supplied' % key) def step1_get_authorize_url(self, oauth_callback='oob'): """Returns a URI to redirect to the provider. oauth_callback - Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If oauth_callback is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } body = urllib.urlencode({'oauth_callback': oauth_callback}) uri = _oauth_uri('request', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers, body=body) if resp['status'] != '200': logging.error('Failed to retrieve temporary authorization: %s', content) raise RequestError('Invalid response %s.' % resp['status']) self.request_token = dict(parse_qsl(content)) auth_params = copy.copy(self.params) auth_params['oauth_token'] = self.request_token['oauth_token'] return _oauth_uri('authorize', self.discovery, auth_params) def step2_exchange(self, verifier): """Exhanges an authorized request token for OAuthCredentials. Args: verifier: string, dict - either the verifier token, or a dictionary of the query parameters to the callback, which contains the oauth_verifier. Returns: The Credentials object. """ if not (isinstance(verifier, str) or isinstance(verifier, unicode)): verifier = verifier['oauth_verifier'] token = oauth.Token( self.request_token['oauth_token'], self.request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, token) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } uri = _oauth_uri('access', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers) if resp['status'] != '200': logging.error('Failed to retrieve access token: %s', content) raise RequestError('Invalid response %s.' % resp['status']) oauth_params = dict(parse_qsl(content)) token = oauth.Token( oauth_params['oauth_token'], oauth_params['oauth_token_secret']) return OAuthCredentials(consumer, token, self.user_agent)
[ [ 8, 0, 0.0342, 0.0083, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0414, 0.0021, 0, 0.66, 0.0476, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0476, 0.0021, 0, 0.66,...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import copy", "import httplib2", "import logging", "import oauth2 as oauth", "import urllib", "import urlparse", "from anyjson import simplejson", "tr...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
[ [ 8, 0, 0.1259, 0.037, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1556, 0.0074, 0, 0.66, 0.125, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1704, 0.0074, 0, 0.66, ...
[ "\"\"\"Utilities for Google App Engine\n\nUtilities for making it easier to use the\nGoogle API Client for Python on Google App Engine.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import pickle", "from google.appengine.ext import db", "from apiclient.oauth import OAuthCredentials", "...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 1.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle import threading from apiclient.oauth import Storage as BaseStorage class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def get(self): """Retrieve Credential from file. Returns: apiclient.oauth.Credentials """ self._lock.acquire() try: f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() credentials.set_store(self.put) except: credentials = None self._lock.release() return credentials def put(self, credentials): """Write a pickled Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._lock.acquire() f = open(self._filename, 'w') f.write(pickle.dumps(credentials)) f.close() self._lock.release()
[ [ 8, 0, 0.2619, 0.0635, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.3175, 0.0159, 0, 0.66, 0.2, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.3492, 0.0159, 0, 0.66, ...
[ "\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 1.0 credentials.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import pickle", "import threading", "from apiclient.oauth import Storage as BaseStorage", "class Storage(BaseStorage):\n \"\"\"Store and retr...
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value)) class FlowThreeLeggedField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): print "In to_python", value if value is None: return None if isinstance(value, apiclient.oauth.FlowThreeLegged): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value))
[ [ 1, 0, 0.2679, 0.0179, 0, 0.66, 0, 629, 0, 1, 0, 0, 629, 0, 0 ], [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0.2, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.6...
[ "import apiclient", "import base64", "import pickle", "from django.db import models", "class OAuthCredentialsField(models.Field):\n\n __metaclass__ = models.SubfieldBase\n\n def db_type(self):\n return 'VARCHAR'\n\n def to_python(self, value):", " __metaclass__ = models.SubfieldBase", " def db_t...
__version__ = "1.0c2"
[ [ 14, 0, 1, 1, 0, 0.66, 0, 162, 1, 0, 0, 0, 0, 3, 0 ] ]
[ "__version__ = \"1.0c2\"" ]
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import urllib from errors import HttpError from oauth2client.anyjson import simplejson FLAGS = gflags.FLAGS gflags.DEFINE_boolean('dump_request_response', False, 'Dump all http server requests and responses. ' ) def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if FLAGS.dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/1.0' if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if FLAGS.dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): body = simplejson.loads(content) if isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class MediaModel(JsonModel): """Model class for requests that return Media. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = 'media' def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch
[ [ 8, 0, 0.0519, 0.0182, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0649, 0.0026, 0, 0.66, 0.0625, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0701, 0.0026, 0, 0.66,...
[ "\"\"\"Model objects for requests and responses.\n\nEach API may support one or more serializations, such\nas JSON, Atom, etc. The model classes are responsible\nfor converting between the wire format and the Python\nobject representation.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "import...
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from oauth2client.anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" if self.resp.get('content-type', '').startswith('application/json'): try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): reason = self.content else: reason = self.resp.reason return reason def __repr__(self): if self.uri: return '<HttpError %s when requesting %s returned "%s">' % ( self.resp.status, self.uri, self._get_reason()) else: return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(Error): """Error occured during resumable upload.""" pass class BatchError(HttpError): """Error occured during batch operations.""" def __init__(self, reason, resp=None, content=None): self.resp = resp self.content = content self.reason = reason def __repr__(self): return '<BatchError %s "%s">' % (self.resp.status, self.reason) __str__ = __repr__ class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
[ [ 8, 0, 0.1545, 0.0407, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.187, 0.0081, 0, 0.66, 0.0769, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.2114, 0.0081, 0, 0.66, ...
[ "\"\"\"Errors for the library.\n\nAll exceptions defined by the library\nshould be defined in this file.\n\"\"\"", "__author__ = 'jcgregorio@google.com (Joe Gregorio)'", "from oauth2client.anyjson import simplejson", "class Error(Exception):\n \"\"\"Base error for this module.\"\"\"\n pass", " \"\"\"Base...
""" iri2uri Converts an IRI to a URI. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" __history__ = """ """ import urlparse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF ), (0xE000, 0xF8FF ), (0xF900, 0xFDCF ), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD ), (0x20000, 0x2FFFD ), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD ), (0x50000, 0x5FFFD ), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD ), (0x80000, 0x8FFFD ), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD ), (0xB0000, 0xBFFFD ), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD ), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD ), (0x100000, 0x10FFFD) ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri ,unicode): (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri) authority = authority.encode('idna') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ u"ftp://ftp.is.co.za/rfc/rfc1808.txt", u"http://www.ietf.org/rfc/rfc2396.txt", u"ldap://[2001:db8::7]/c=GB?objectClass?one", u"mailto:John.Doe@example.com", u"news:comp.infosystems.www.servers.unix", u"tel:+1-816-555-1212", u"telnet://192.0.2.16:80/", u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """ Test that the right type of escaping is done for each part of the URI.""" self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}")) self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}")) self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}")) self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))) self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8'))) unittest.main()
[ [ 8, 0, 0.0318, 0.0545, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0636, 0.0091, 0, 0.66, 0.0909, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0727, 0.0091, 0, 0.66...
[ "\"\"\"\niri2uri\n\nConverts an IRI to a URI.\n\n\"\"\"", "__author__ = \"Joe Gregorio (joe@bitworking.org)\"", "__copyright__ = \"Copyright 2006, Joe Gregorio\"", "__contributors__ = []", "__version__ = \"1.0.0\"", "__license__ = \"MIT\"", "__history__ = \"\"\"\n\"\"\"", "import urlparse", "escape_...
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import base64 import socket import struct import sys if getattr(socket, 'socket', None) is None: raise ImportError('socket.socket missing, proxy support unusable') PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 PROXY_TYPE_HTTP_NO_TUNNEL = 4 _defaultproxy = None _orgsocket = socket.socket class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified")) class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None self.__httptunnel = True def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def sendall(self, content, *args): """ override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed """ if not self.__httptunnel: content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args) def __rewriteproxy(self, header): """ rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. """ host, endpt = None, None hdrs = header.split("\r\n") for hdr in hdrs: if hdr.lower().startswith("host:"): host = hdr elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): endpt = hdr if host and endpt: hdrs.remove(host) hdrs.remove(endpt) host = host.split(" ")[1] endpt = endpt.split(" ") if (self.__proxy[4] != None and self.__proxy[5] != None): hdrs.insert(0, self.__getauthheader()) hdrs.insert(0, "Host: %s" % host) hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) return "\r\n".join(hdrs) def __getauthheader(self): auth = self.__proxy[4] + ":" + self.__proxy[5] return "Proxy-Authorization: Basic " + base64.b64encode(auth) def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1],portnum)) if destpair[1] == 443: self.__negotiatehttp(destpair[0],destpair[1]) else: self.__httptunnel = False elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
[ [ 8, 0, 0.0365, 0.0708, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 0.0845, 0.0205, 0, 0.66, 0.04, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0982, 0.0023, 0, 0.66, ...
[ "\"\"\"SocksiPy - Python SOCKS module.\nVersion 1.00\n\nCopyright 2006 Dan-Haim. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright ...
import Cookie import datetime import time import email.utils import calendar import base64 import hashlib import hmac import re import logging # Ripped from the Tornado Framework's web.py # http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09 # # Tornado is licensed under the Apache Licence, Version 2.0 # (http://www.apache.org/licenses/LICENSE-2.0.html). # # Example: # from vendor.prayls.lilcookies import LilCookies # cookieutil = LilCookies(self, application_settings['cookie_secret']) # cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100) # cookieutil.get_secure_cookie(name = 'mykey') class LilCookies: @staticmethod def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s @staticmethod def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 @staticmethod def _signature_from_secret(cookie_secret, *parts): """ Takes a secret salt value to create a signature for values in the `parts` param.""" hash = hmac.new(cookie_secret, digestmod=hashlib.sha1) for part in parts: hash.update(part) return hash.hexdigest() @staticmethod def _signed_cookie_value(cookie_secret, name, value): """ Returns a signed value for use in a cookie. This is helpful to have in its own method if you need to re-use this function for other needs. """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp) return "|".join([value, timestamp, signature]) @staticmethod def _verified_cookie_value(cookie_secret, name, signed_value): """Returns the un-encrypted value given the signed value if it validates, or None.""" value = signed_value if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1]) if not LilCookies._time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None def __init__(self, handler, cookie_secret): """You must specify the cookie_secret to use any of the secure methods. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. """ if len(cookie_secret) < 45: raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret) self.handler = handler self.request = handler.request self.response = handler.response self.cookie_secret = cookie_secret def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" if name in self.cookies(): return self._cookies[name].value return default def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ name = LilCookies._utf8(name) value = LilCookies._utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp, localtime=False, usegmt=True) if path: new_cookie[name]["path"] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v # The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush. for vals in new_cookie.values(): self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None))) def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies().iterkeys(): self.clear_cookie(name) def set_secure_cookie(self, name, value, expires_days=30, **kwargs): """Signs and timestamps a cookie so it cannot be forged. To read a cookie set with this method, use get_secure_cookie(). """ value = LilCookies._signed_cookie_value(self.cookie_secret, name, value) self.set_cookie(name, value, expires_days=expires_days, **kwargs) def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None.""" if value is None: value = self.get_cookie(name) return LilCookies._verified_cookie_value(self.cookie_secret, name, value) def _cookie_signature(self, *parts): return LilCookies._signature_from_secret(self.cookie_secret)
[ [ 1, 0, 0.006, 0.006, 0, 0.66, 0, 32, 0, 1, 0, 0, 32, 0, 0 ], [ 1, 0, 0.0119, 0.006, 0, 0.66, 0.1, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0179, 0.006, 0, 0.66, ...
[ "import Cookie", "import datetime", "import time", "import email.utils", "import calendar", "import base64", "import hashlib", "import hmac", "import re", "import logging", "class LilCookies:\n\n @staticmethod\n def _utf8(s):\n if isinstance(s, unicode):\n return s.encode(\"utf-8\")\n ...
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
[ [ 14, 0, 0.1667, 0.0556, 0, 0.66, 0, 189, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0.66, 0.3333, 295, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.6111, 0.0556, 0, 0...
[ "manual_verstr = \"1.5\"", "auto_build_num = \"211\"", "verstr = manual_verstr + \".\" + auto_build_num", "try:\n from pyutil.version_class import Version as pyutil_Version\n __version__ = pyutil_Version(verstr)\nexcept (ImportError, ValueError):\n # Maybe there is no pyutil installed.\n from dist...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
[ [ 8, 0, 0.2927, 0.561, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.6098, 0.0244, 0, 0.66, 0.25, 311, 0, 1, 0, 0, 311, 0, 0 ], [ 1, 0, 0.6341, 0.0244, 0, 0.66, ...
[ "\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
[ [ 8, 0, 0.3, 0.575, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.625, 0.025, 0, 0.66, 0.3333, 311, 0, 1, 0, 0, 311, 0, 0 ], [ 1, 0, 0.65, 0.025, 0, 0.66, 0.6...
[ "\"\"\"\nThe MIT License\n\nCopyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including withou...
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
[ [ 1, 0, 0.0204, 0.0068, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0272, 0.0068, 0, 0.66, 0.0833, 614, 0, 1, 0, 0, 614, 0, 0 ], [ 14, 0, 0.0408, 0.0068, 0, ...
[ "import re", "import urllib", "RESERVED = \":/?#[]@!$&'()*+,;=\"", "OPERATOR = \"+./;?|!@\"", "EXPLODE = \"*+\"", "MODIFIER = \":^\"", "TEMPLATE = re.compile(r\"{(?P<operator>[\\+\\./;\\?|!@])?(?P<varlist>[^}]+)}\", re.UNICODE)", "VAR = re.compile(r\"^(?P<varname>[^=\\+\\*:\\^]+)((?P<explode>[\\+\\*])...
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
[ [ 1, 0, 0.3514, 0.0135, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3649, 0.0135, 0, 0.66, 0.1111, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.3784, 0.0135, 0, ...
[ "import os", "import re", "import tempfile", "import shutil", "ignore_pattern = re.compile('^(.svn|target|bin|classes)')", "java_pattern = re.compile('^.*\\.java')", "annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')", "def process_dir(dir):\n files = os.listdir(dir)\n for...
import sys, os, popen2 def cmd(comando): out = popen2.popen3(comando) try: return out[0].read() except: print "Imposible de ejecutar Comando: <"+comando+">" print raw_input("Nos vemos luego, enter para salir") sys.exit(1) def cargar(): directoriosTest = cmd("cd .. && ls Source/*Tests/bin/Debug/*.Tests.dll") archivos = [] directoriosTest = directoriosTest.split("\n") for archivo in directoriosTest: print ">Encontrado: "+archivo archivos.append(archivo) return archivos def nombrar(cadena): cadenas = cadena.split("/") final = "" escribir = False for cad in cadenas: if escribir: if (cad == "bin") or (cad == "Debug"): final += "../" else: final += cad+"/" if cad == "Source": escribir = True return final[:-1] def contar(cadena, num): try: l = cadena.split(',') k = l[num].split(':') return int(k[1]) except: return 0 def filtrar(texto, archivo, i=0): ok__ = 0 error__ = 0 not__ = 0 try: cadena = "\n"+str(i)+"-"*35+"\n.../"+nombrar(archivo)+":\n" texto = texto.split("\n") for linea in texto: if "Tests run:" in linea: ok__ += contar(linea, 0) error__ += contar(linea, 1) not__ += contar(linea, 2) cadena += " -->"+linea+"_"*6 if "Failures: 0" in linea: cadena += "OK" l = [ok__, error__, not__, cadena] return l else: os.system("color C && echo ") cadena += "ERROR!!!" l = [ok__, error__, not__, cadena] return l os.system("color C && echo ") cadena += "__FAIL__ !!" l = [ok__, error__, not__, cadena] return l except: print "Saliendo: 2" return [0,0,0,""] def ejecutar(archivos): i = 1 ok_ = 0 error_ = 0 not_c = 0 path = cmd("whereis nunit-console") path = path.split(" ")[1] print ">Path NUnit= "+path+"\n\n" for archivo in archivos: try: salida = cmd("cd .. && "+path+" "+archivo) l = filtrar(salida, archivo, i) ok_ += l[0] error_ += l[1] not_c += l[2] print l[3] except: print "Saliendo: 1 (enter)" raw_input("") sys.exit(1) i += 1 print print "Estado Final: " print " -Corridos:", ok_ print " -Corridos y Fallados:", error_ print " -No Corridos:", not_c def ayuda(): print "inserte ayuda aqui" def main(): tests = cargar() print "\n",len(tests),"Tests Detectados;\nCorriendo los Tests: aguarde...\n" ejecutar(tests) help = raw_input("\n\nTERMINADO! (enter para salir; help y enter para ayuda)") if "help" in help: ayuda() raw_input("\nFIN! (enter para salir)") if __name__ == "__main__": os.system("clear") print "--_Bienvenidos_--" print "\nInciando ambiente y buscando tests...\n\n" main()
[ [ 1, 0, 0.0085, 0.0085, 0, 0.66, 0, 509, 0, 3, 0, 0, 509, 0, 0 ], [ 2, 0, 0.0551, 0.0678, 0, 0.66, 0.1111, 604, 0, 1, 1, 0, 0, 0, 6 ], [ 14, 1, 0.0339, 0.0085, 1, 0...
[ "import sys, os, popen2", "def cmd(comando):\n\tout = popen2.popen3(comando)\n\ttry:\n\t\treturn out[0].read()\n\texcept:\n\t\tprint(\"Imposible de ejecutar Comando: <\"+comando+\">\")\n\t\tprint(raw_input(\"Nos vemos luego, enter para salir\"))\n\t\tsys.exit(1)", "\tout = popen2.popen3(comando)", "\ttry:\n\t...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') fin2=open('time_err_n3.dat') todo=fin.read().split('\n') todo2=fin2.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] ys2=[float(x.split()[1]) for x in todo2 if x] yerr=[float(x.split()[2]) for x in todo if x] yerr2=[float(x.split()[2]) for x in todo2 if x] diff=reduce(lambda x,y:x+y, [ys2[i]/ys[i] for i in range(len(ys))], 0)/len(ys) title("Comparacion de strassen vs algoritmo en $cw$") xlabel("Cantidad de Personas") ylabel("Tiempo de ejecucion (s)") errorbar(xs,ys,yerr,marker='_',color='k',ls='None',label="Strassen con umbral=4") errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="Algoritmo tradicional") legend(loc="upper left") #text(1,.06,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff)) savefig('ej3_times_vs.png',dpi=640./8) show()
[ [ 1, 0, 0.1304, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0.66, 0.0556, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2609, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "fin2=open('time_err_n3.dat')", "todo=fin.read().split('\\n')", "todo2=fin2.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "ys2=[float(x.split()[1]) for x in todo2 if x]"...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $cw$") xlabel("Cantidad de Personas") ylabel("Tiempo de ejecucion (s)") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[(x**2.81)*.000004 for x in xs],label=r"$c \times n^{log_2(7)}$") ylim(0,0.08) legend(loc=0) savefig('ej3_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1667, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.0714, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $cw$\")", "xlabel(\"Cantidad de ...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') fin2=open('time_err_n3.dat') todo=fin.read().split('\n') todo2=fin2.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] ys2=[float(x.split()[1]) for x in todo2 if x] yerr=[float(x.split()[2]) for x in todo if x] yerr2=[float(x.split()[2]) for x in todo2 if x] diff=reduce(lambda x,y:x+y, [ys2[i]/ys[i] for i in range(len(ys))], 0)/len(ys) title("Comparacion de strassen vs algoritmo en $cw$") xlabel("Cantidad de Personas") ylabel("Tiempo de ejecucion (s)") errorbar(xs,ys,yerr,marker='_',color='k',ls='None',label="Strassen con umbral=4") errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="Algoritmo tradicional") legend(loc="upper left") #text(1,.06,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff)) savefig('ej3_times_vs.png',dpi=640./8) show()
[ [ 1, 0, 0.1304, 0.0435, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2174, 0.0435, 0, 0.66, 0.0556, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.2609, 0.0435, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "fin2=open('time_err_n3.dat')", "todo=fin.read().split('\\n')", "todo2=fin2.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "ys2=[float(x.split()[1]) for x in todo2 if x]"...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $cw$") xlabel("Cantidad de Personas") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x**2.81*150 for x in xs],label=r"$c \times n^{log_2(7)}$") legend(loc=0) ylim(0,.27e7) savefig('ej3_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $cw$\")", "xlabel(\"Cantidad de Personas\")", "ylabel(\"Cantidad de operaciones\")"...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="cw" tamanios_entrada=sorted(range(1,45)*2) def prueba(tamanio_entrada): out=str(tamanio_entrada) for i in range(tamanio_entrada): out+='\n' li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i])) out+=str(len(li))+' '+' '.join(li) return out ender="-1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas))) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.06','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0385, 0.0385, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0769, 0.0385, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1154, 0.0385, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="cw_n3" tamanios_entrada=sorted(range(1,45)*2) def prueba(tamanio_entrada): out=str(tamanio_entrada) for i in range(tamanio_entrada): out+='\n' li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i])) out+=str(len(li))+' '+' '.join(li) return out ender="-1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas))) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.06','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err_n3.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err_n3.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts_n3.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts_n3.dat"
[ [ 1, 0, 0.0385, 0.0385, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0769, 0.0385, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1154, 0.0385, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin2=open('time_err_n3.dat') todo2=fin2.read().split('\n') xs=[float(x.split()[0]) for x in todo2 if x] ys2=[float(x.split()[1]) for x in todo2 if x] yerr2=[float(x.split()[2]) for x in todo2 if x] title("Tiempo de ejecución de algoritmo cubico de $cw$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="$algoritmo cubico$") plot(xs,[x**3*.00000024 for x in xs],color='r',label=r"$c \times n^3$") legend(loc="upper left") #text(1,.6,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff)) savefig('ej3_times_n3.png',dpi=640./8) show()
[ [ 1, 0, 0.1667, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.0769, 965, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin2=open('time_err_n3.dat')", "todo2=fin2.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo2 if x]", "ys2=[float(x.split()[1]) for x in todo2 if x]", "yerr2=[float(x.split()[2]) for x in todo2 if x]", "title(\"Tiempo de ejecución de algoritmo cubico de $cw...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin2=open('time_err_n3.dat') todo2=fin2.read().split('\n') xs=[float(x.split()[0]) for x in todo2 if x] ys2=[float(x.split()[1]) for x in todo2 if x] yerr2=[float(x.split()[2]) for x in todo2 if x] title("Tiempo de ejecución de algoritmo cubico de $cw$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys2,yerr2,marker='_',color='b',ls='None',label="$algoritmo cubico$") plot(xs,[x**3*.00000024 for x in xs],color='r',label=r"$c \times n^3$") legend(loc="upper left") #text(1,.6,"en promedio,\nalgoritmo_cubico/strassen="+str("%.3f"%diff)) savefig('ej3_times_n3.png',dpi=640./8) show()
[ [ 1, 0, 0.1667, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.0769, 965, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin2=open('time_err_n3.dat')", "todo2=fin2.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo2 if x]", "ys2=[float(x.split()[1]) for x in todo2 if x]", "yerr2=[float(x.split()[2]) for x in todo2 if x]", "title(\"Tiempo de ejecución de algoritmo cubico de $cw...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="cw" tamanios_entrada=sorted(range(1,45)*2) def prueba(tamanio_entrada): out=str(tamanio_entrada) for i in range(tamanio_entrada): out+='\n' li=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint(0,tamanio_entrada))] if x!=i])) out+=str(len(li))+' '+' '.join(li) return out ender="-1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas))) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.06','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0385, 0.0385, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0769, 0.0385, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1154, 0.0385, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def prueba(tamanio_entrada):\n\tout=str(tamanio_entrada)\n\tfor i in range(tamanio_entrada):\n\t\tout+='\\n'\n\t\tli=list(set([str(x+1) for x in [randint(0,tamanio_entrada-1) for am in range(randint...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $cw$") xlabel("Cantidad de Personas") ylabel("Tiempo de ejecucion (s)") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[(x**2.81)*.000004 for x in xs],label=r"$c \times n^{log_2(7)}$") ylim(0,0.08) legend(loc=0) savefig('ej3_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1667, 0.0556, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0.0714, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3333, 0.0556, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $cw$\")", "xlabel(\"Cantidad de ...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $cw$") xlabel("Cantidad de Personas") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x**2.81*150 for x in xs],label=r"$c \times n^{log_2(7)}$") legend(loc=0) ylim(0,.27e7) savefig('ej3_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $cw$\")", "xlabel(\"Cantidad de Personas\")", "ylabel(\"Cantidad de operaciones\")"...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $matching$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[x*.000000025+.0000005 for x in xs],label=r"$c \times x$") legend(loc=0) savefig('ej1_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $matching$\")", "xlabel(\"Tamano...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $matching$") xlabel("Tamano de entrada") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) savefig('ej1_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1875, 0.0625, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.3125, 0.0625, 0, 0.66, 0.0833, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.375, 0.0625, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $matching$\")", "xlabel(\"Tamano de entrada\")", "ylabel(\"Cantidad de operaciones\...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="matching" tamanios_entrada=sorted(range(3,300)[::5]) def prueba(tamanio_entrada): return str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)]) ender="-1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas))) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.2','2']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0952, 0.0476, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1429, 0.0476, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def prueba(tamanio_entrada):\n\treturn str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])", "\treturn str(tamanio_entrada)+' '+' '.join([str(ran...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="matching" tamanios_entrada=sorted(range(3,300)[::5]) def prueba(tamanio_entrada): return str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)]) ender="-1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas))) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.2','2']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0952, 0.0476, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1429, 0.0476, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed", "from math import sqrt", "def prueba(tamanio_entrada):\n\treturn str(tamanio_entrada)+' '+' '.join([str(randint(0,tamanio_entrada/2)) for x in range(tamanio_entrada)])", "\treturn str(tamanio_entrada)+' '+' '.join([str(ran...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $matching$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[x*.000000025+.0000005 for x in xs],label=r"$c \times x$") legend(loc=0) savefig('ej1_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $matching$\")", "xlabel(\"Tamano...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $matching$") xlabel("Tamano de entrada") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$") legend(loc=0) savefig('ej1_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1875, 0.0625, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.3125, 0.0625, 0, 0.66, 0.0833, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.375, 0.0625, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $matching$\")", "xlabel(\"Tamano de entrada\")", "ylabel(\"Cantidad de operaciones\...
#!/usr/bin/env python from Tkinter import * from random import * from math import sqrt import subprocess def prueba(tamanio_entrada): cant=int(random()*tamanio_entrada) w=randint(3,int(2*sqrt(tamanio_entrada))) h=tamanio_entrada/w vs=[] for v in range(cant): orient=choice(['-','|']) if orient=='|': l=randint(1,int(h*.5)) x,y=randint(1,w),randint(1,h-l) else: l=randint(1,int(w*.5)) x,y=randint(1,w-l),randint(1,h) ok=True for v2 in vs: if orient=='-': if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False if orient=='|': if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False if ok: vs.append((x,y,orient,l,randint(0,10))) offsx,offsy=randint(0,800),randint(0,800) return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs]) factor=20 maxx,maxy,w=0,0,0 sp=Spinbox(from_=100,to=1000,increment=1) canvas = Canvas(width=factor+factor*maxx, height=factor+factor*maxy, bg='lightblue') def change(): global canvas caso=prueba(int(sp.get())) print caso print vallas=[[int(x[0])]+[int(x[1])]+[x[2]]+[int(x[3])]+[int(x[4])] for x in map(lambda x:x.split(),caso[1:].split('\n')) if len(x)==5] maxx=max([x[0]+x[3] for x in vallas if x[2]=='-']+[x[0] for x in vallas if x[2]=='|']+[3]) maxy=max([x[1]+x[3] for x in vallas if x[2]=='|']+[x[1] for x in vallas if x[2]=='-']+[3]) w=int(caso.split()[0]) fp=subprocess.Popen(['./floodmapa'], shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) fp.stdin.write(caso+"\n") r=fp.stdout.read().split() miny=int(r.pop()) minx=int(r.pop()) canvas.delete("all") canvas.config(width=factor+factor*(maxx-minx), height=factor+factor*(maxy-miny)) ii,jj=0,0 for i in r: jj=0 for j in i: if j=='0': canvas.create_rectangle(jj*factor, ii*factor, jj*factor+factor, ii*factor+factor, fill="white", width=0) jj+=1 ii+=1 for v in vallas: v[0]-=minx v[1]-=miny canvas.create_line(v[0]*factor,v[1]*factor,(v[0]+(v[2]=='-' and v[3] or 0))*factor,(v[1]+(v[2]=='|' and v[3] or 0))*factor,fill=(v[4]<w and 'gray70' or 'black')) change() Button(text="random",command=change).grid(row=0,column=1) sp.grid(row=0,column=0) canvas.grid(row=2,columnspan=2) mainloop()
[ [ 1, 0, 0.0405, 0.0135, 0, 0.66, 0, 368, 0, 1, 0, 0, 368, 0, 0 ], [ 1, 0, 0.0541, 0.0135, 0, 0.66, 0.0714, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0676, 0.0135, 0, ...
[ "from Tkinter import *", "from random import *", "from math import sqrt", "import subprocess", "def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-','|'])\n\t\tif orien...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $flood$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[x*.00000035+.00004 for x in xs],label=r"$c \times n$") legend(loc=0) savefig('ej2_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $flood$\")", "xlabel(\"Tamano de...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $flood$") xlabel("Tamano de entrada") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x*10+2000 for x in xs],label=r"$c \times n$") legend(loc=0) savefig('ej2_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1875, 0.0625, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.3125, 0.0625, 0, 0.66, 0.0833, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.375, 0.0625, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $flood$\")", "xlabel(\"Tamano de entrada\")", "ylabel(\"Cantidad de operaciones\")"...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed,choice from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="flood" tamanios_entrada=sorted(range(100,5000)[::35]) def prueba(tamanio_entrada): cant=int(random()*tamanio_entrada) w=randint(3,int(2*sqrt(tamanio_entrada))) h=tamanio_entrada/w vs=[] for v in range(cant): orient=choice(['-','|']) if orient=='|': l=randint(1,int(h*.5)) x,y=randint(1,w),randint(1,h-l) else: l=randint(1,int(w*.5)) x,y=randint(1,w-l),randint(1,h) ok=True for v2 in vs: if orient=='-': if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False if orient=='|': if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False if ok: vs.append((x,y,orient,l,randint(0,10))) offsx,offsy=randint(0,800),randint(0,800) return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs]) ender="-1 -1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)) + '\n'+ender) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.05','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0476, 0.0238, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0714, 0.0238, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed,choice", "from math import sqrt", "def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-...
#!/usr/bin/env python import getopt,sys import subprocess from random import random,randint,seed,choice from math import sqrt seed(1234) # defino el seed para hacer el experimento reproducible ejecutable="flood" tamanios_entrada=sorted(range(100,5000)[::35]) def prueba(tamanio_entrada): cant=int(random()*tamanio_entrada) w=randint(3,int(2*sqrt(tamanio_entrada))) h=tamanio_entrada/w vs=[] for v in range(cant): orient=choice(['-','|']) if orient=='|': l=randint(1,int(h*.5)) x,y=randint(1,w),randint(1,h-l) else: l=randint(1,int(w*.5)) x,y=randint(1,w-l),randint(1,h) ok=True for v2 in vs: if orient=='-': if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False if orient=='|': if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False if ok: vs.append((x,y,orient,l,randint(0,10))) offsx,offsy=randint(0,800),randint(0,800) return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs]) ender="-1 -1" pruebas=[(n,prueba(n)) for n in tamanios_entrada] open('test.in','w').write('\n'.join(map(lambda x:x[1],pruebas)) + '\n'+ender) def runtest(pruebas,args): fp=subprocess.Popen(['./'+ejecutable]+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) for prueba in pruebas: fp.stdin.write(prueba[1]+"\n") # le manda la instancia r=fp.stdout.readline().rstrip() # recibo el resultado print "tamanio: ",prueba[0]," ",args[0],"=",r yield prueba[0],r # lo devuelvo fp.stdin.write(ender+"\n") def usage(): print "Usage:" print "-t (o --time) para calcular tiempos" print "-c (o --count) para contar operaciones" sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() if not opts: usage() opts=map(lambda x: x[0],opts) out="" if "--time" in opts or "-t" in opts: for i in runtest(pruebas,['time','0.05','3']): # para cada caso de prueba... vals=map(float,i[1].split()) # obtengo la lista de los tiempos val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio err=max([abs(x-val) for x in vals]) # calculo el error dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida out += dat open('time_err.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a time_err.dat" out="" if "--count" in opts or "-c" in opts: for i in runtest(pruebas,['count']): #para cada caso de prueba.. dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida out += dat open('counts.dat','w').write(out) # lo guardo en el archivo print "\nOutput escrito a counts.dat"
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 588, 0, 2, 0, 0, 588, 0, 0 ], [ 1, 0, 0.0476, 0.0238, 0, 0.66, 0.1667, 394, 0, 1, 0, 0, 394, 0, 0 ], [ 1, 0, 0.0714, 0.0238, 0, ...
[ "import getopt,sys", "import subprocess", "from random import random,randint,seed,choice", "from math import sqrt", "def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('time_err.dat') todo=fin.read().split('\n') xs=[float(x.split()[0]) for x in todo if x] ys=[float(x.split()[1]) for x in todo if x] yerr=[float(x.split()[2]) for x in todo if x] title("Tiempo de ejecucion de $flood$") xlabel("Tamano de entrada") ylabel("Tiempo de ejecucion") errorbar(xs,ys,yerr,marker='_',color='k',ls='None') plot(xs,[x*.00000035+.00004 for x in xs],label=r"$c \times n$") legend(loc=0) savefig('ej2_times.png',dpi=640./8) show()
[ [ 1, 0, 0.1765, 0.0588, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.2941, 0.0588, 0, 0.66, 0.0769, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.3529, 0.0588, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('time_err.dat')", "todo=fin.read().split('\\n')", "xs=[float(x.split()[0]) for x in todo if x]", "ys=[float(x.split()[1]) for x in todo if x]", "yerr=[float(x.split()[2]) for x in todo if x]", "title(\"Tiempo de ejecucion de $flood$\")", "xlabel(\"Tamano de...
#!/usr/bin/env python from Tkinter import * from random import * from math import sqrt import subprocess def prueba(tamanio_entrada): cant=int(random()*tamanio_entrada) w=randint(3,int(2*sqrt(tamanio_entrada))) h=tamanio_entrada/w vs=[] for v in range(cant): orient=choice(['-','|']) if orient=='|': l=randint(1,int(h*.5)) x,y=randint(1,w),randint(1,h-l) else: l=randint(1,int(w*.5)) x,y=randint(1,w-l),randint(1,h) ok=True for v2 in vs: if orient=='-': if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False if orient=='|': if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False if ok: vs.append((x,y,orient,l,randint(0,10))) offsx,offsy=randint(0,800),randint(0,800) return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs]) factor=20 maxx,maxy,w=0,0,0 sp=Spinbox(from_=100,to=1000,increment=1) canvas = Canvas(width=factor+factor*maxx, height=factor+factor*maxy, bg='lightblue') def change(): global canvas caso=prueba(int(sp.get())) print caso print vallas=[[int(x[0])]+[int(x[1])]+[x[2]]+[int(x[3])]+[int(x[4])] for x in map(lambda x:x.split(),caso[1:].split('\n')) if len(x)==5] maxx=max([x[0]+x[3] for x in vallas if x[2]=='-']+[x[0] for x in vallas if x[2]=='|']+[3]) maxy=max([x[1]+x[3] for x in vallas if x[2]=='|']+[x[1] for x in vallas if x[2]=='-']+[3]) w=int(caso.split()[0]) fp=subprocess.Popen(['./floodmapa'], shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE) fp.stdin.write(caso+"\n") r=fp.stdout.read().split() miny=int(r.pop()) minx=int(r.pop()) canvas.delete("all") canvas.config(width=factor+factor*(maxx-minx), height=factor+factor*(maxy-miny)) ii,jj=0,0 for i in r: jj=0 for j in i: if j=='0': canvas.create_rectangle(jj*factor, ii*factor, jj*factor+factor, ii*factor+factor, fill="white", width=0) jj+=1 ii+=1 for v in vallas: v[0]-=minx v[1]-=miny canvas.create_line(v[0]*factor,v[1]*factor,(v[0]+(v[2]=='-' and v[3] or 0))*factor,(v[1]+(v[2]=='|' and v[3] or 0))*factor,fill=(v[4]<w and 'gray70' or 'black')) change() Button(text="random",command=change).grid(row=0,column=1) sp.grid(row=0,column=0) canvas.grid(row=2,columnspan=2) mainloop()
[ [ 1, 0, 0.0405, 0.0135, 0, 0.66, 0, 368, 0, 1, 0, 0, 368, 0, 0 ], [ 1, 0, 0.0541, 0.0135, 0, 0.66, 0.0714, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0676, 0.0135, 0, ...
[ "from Tkinter import *", "from random import *", "from math import sqrt", "import subprocess", "def prueba(tamanio_entrada):\n\tcant=int(random()*tamanio_entrada)\n\tw=randint(3,int(2*sqrt(tamanio_entrada)))\n\th=tamanio_entrada/w\n\tvs=[]\n\tfor v in range(cant):\n\t\torient=choice(['-','|'])\n\t\tif orien...
#!/usr/bin/env python # coding: utf-8 from matplotlib.pyplot import * fin=open('counts.dat') todo=fin.read().split('\n') xs=[int(x.split()[0]) for x in todo if x] ys=[int(x.split()[1]) for x in todo if x] title("Cantidad de operaciones de $flood$") xlabel("Tamano de entrada") ylabel("Cantidad de operaciones") plot(xs,ys,'kx',label="__nolabel__") plot(xs,[x*10+2000 for x in xs],label=r"$c \times n$") legend(loc=0) savefig('ej2_counts.png',dpi=640./8) show()
[ [ 1, 0, 0.1875, 0.0625, 0, 0.66, 0, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.3125, 0.0625, 0, 0.66, 0.0833, 225, 3, 1, 0, 0, 693, 10, 1 ], [ 14, 0, 0.375, 0.0625, 0, ...
[ "from matplotlib.pyplot import *", "fin=open('counts.dat')", "todo=fin.read().split('\\n')", "xs=[int(x.split()[0]) for x in todo if x]", "ys=[int(x.split()[1]) for x in todo if x]", "title(\"Cantidad de operaciones de $flood$\")", "xlabel(\"Tamano de entrada\")", "ylabel(\"Cantidad de operaciones\")"...