\n\"\"\"\n\nDEFAULT_ERROR_CONTENT_TYPE = \"text/html\"\n\ndef _quote_html(html):\n return html.replace(\"&\", \"&\").replace(\"<\", \"<\").replace(\">\", \">\")\n\nclass HTTPServer(SocketServer.TCPServer):\n\n allow_reuse_address = 1 # Seems to make sense in testing environment\n\n def server_bind(self):\n \"\"\"Override server_bind to store the server name.\"\"\"\n SocketServer.TCPServer.server_bind(self)\n host, port = self.socket.getsockname()[:2]\n self.server_name = socket.getfqdn(host)\n self.server_port = port\n\n\nclass BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):\n\n \"\"\"HTTP request handler base class.\n\n The following explanation of HTTP serves to guide you through the\n code as well as to expose any misunderstandings I may have about\n HTTP (so you don't need to read the code to figure out I'm wrong\n :-).\n\n HTTP (HyperText Transfer Protocol) is an extensible protocol on\n top of a reliable stream transport (e.g. TCP/IP). The protocol\n recognizes three parts to a request:\n\n 1. One line identifying the request type and path\n 2. An optional set of RFC-822-style headers\n 3. An optional data part\n\n The headers and data are separated by a blank line.\n\n The first line of the request has the form\n\n \n\n where is a (case-sensitive) keyword such as GET or POST,\n is a string containing path information for the request,\n and should be the string \"HTTP/1.0\" or \"HTTP/1.1\".\n is encoded using the URL encoding scheme (using %xx to signify\n the ASCII character with hex code xx).\n\n The specification specifies that lines are separated by CRLF but\n for compatibility with the widest range of clients recommends\n servers also handle LF. Similarly, whitespace in the request line\n is treated sensibly (allowing multiple spaces between components\n and allowing trailing whitespace).\n\n Similarly, for output, lines ought to be separated by CRLF pairs\n but most clients grok LF characters just fine.\n\n If the first line of the request has the form\n\n \n\n (i.e. is left out) then this is assumed to be an HTTP\n 0.9 request; this form has no optional headers and data part and\n the reply consists of just the data.\n\n The reply form of the HTTP 1.x protocol again has three parts:\n\n 1. One line giving the response code\n 2. An optional set of RFC-822-style headers\n 3. The data\n\n Again, the headers and data are separated by a blank line.\n\n The response code line has the form\n\n \n\n where is the protocol version (\"HTTP/1.0\" or \"HTTP/1.1\"),\n is a 3-digit response code indicating success or\n failure of the request, and is an optional\n human-readable string explaining what the response code means.\n\n This server parses the request and the headers, and then calls a\n function specific to the request type (). Specifically,\n a request SPAM will be handled by a method do_SPAM(). If no\n such method exists the server sends an error response to the\n client. If it exists, it is called with no arguments:\n\n do_SPAM()\n\n Note that the request name is case sensitive (i.e. SPAM and spam\n are different requests).\n\n The various request details are stored in instance variables:\n\n - client_address is the client IP address in the form (host,\n port);\n\n - command, path and version are the broken-down request line;\n\n - headers is an instance of mimetools.Message (or a derived\n class) containing the header information;\n\n - rfile is a file object open for reading positioned at the\n start of the optional input data part;\n\n - wfile is a file object open for writing.\n\n IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!\n\n The first thing to be written must be the response line. Then\n follow 0 or more header lines, then a blank line, and then the\n actual data (if any). The meaning of the header lines depends on\n the command executed by the server; in most cases, when data is\n returned, there should be at least one header line of the form\n\n Content-type: /\n\n where and should be registered MIME types,\n e.g. \"text/html\" or \"text/plain\".\n\n \"\"\"\n\n # The Python system version, truncated to its first component.\n sys_version = \"Python/\" + sys.version.split()[0]\n\n # The server software version. You may want to override this.\n # The format is multiple whitespace-separated strings,\n # where each string is of the form name[/version].\n server_version = \"BaseHTTP/\" + __version__\n\n # The default request version. This only affects responses up until\n # the point where the request line is parsed, so it mainly decides what\n # the client gets back when sending a malformed request line.\n # Most web servers default to HTTP 0.9, i.e. don't send a status line.\n default_request_version = \"HTTP/0.9\"\n\n def parse_request(self):\n \"\"\"Parse a request (internal).\n\n The request should be stored in self.raw_requestline; the results\n are in self.command, self.path, self.request_version and\n self.headers.\n\n Return True for success, False for failure; on failure, an\n error is sent back.\n\n \"\"\"\n self.command = None # set in case of error on the first line\n self.request_version = version = self.default_request_version\n self.close_connection = 1\n requestline = self.raw_requestline\n if requestline[-2:] == '\\r\\n':\n requestline = requestline[:-2]\n elif requestline[-1:] == '\\n':\n requestline = requestline[:-1]\n self.requestline = requestline\n words = requestline.split()\n if len(words) == 3:\n [command, path, version] = words\n if version[:5] != 'HTTP/':\n self.send_error(400, \"Bad request version (%r)\" % version)\n return False\n try:\n base_version_number = version.split('/', 1)[1]\n version_number = base_version_number.split(\".\")\n # RFC 2145 section 3.1 says there can be only one \".\" and\n # - major and minor numbers MUST be treated as\n # separate integers;\n # - HTTP/2.4 is a lower version than HTTP/2.13, which in\n # turn is lower than HTTP/12.3;\n # - Leading zeros MUST be ignored by recipients.\n if len(version_number) != 2:\n raise ValueError\n version_number = int(version_number[0]), int(version_number[1])\n except (ValueError, IndexError):\n self.send_error(400, \"Bad request version (%r)\" % version)\n return False\n if version_number >= (1, 1) and self.protocol_version >= \"HTTP/1.1\":\n self.close_connection = 0\n if version_number >= (2, 0):\n self.send_error(505,\n \"Invalid HTTP Version (%s)\" % base_version_number)\n return False\n elif len(words) == 2:\n [command, path] = words\n self.close_connection = 1\n if command != 'GET':\n self.send_error(400,\n \"Bad HTTP/0.9 request type (%r)\" % command)\n return False\n elif not words:\n return False\n else:\n self.send_error(400, \"Bad request syntax (%r)\" % requestline)\n return False\n self.command, self.path, self.request_version = command, path, version\n\n # Examine the headers and look for a Connection directive\n self.headers = self.MessageClass(self.rfile, 0)\n\n conntype = self.headers.get('Connection', \"\")\n if conntype.lower() == 'close':\n self.close_connection = 1\n elif (conntype.lower() == 'keep-alive' and\n self.protocol_version >= \"HTTP/1.1\"):\n self.close_connection = 0\n return True\n\n def handle_one_request(self):\n \"\"\"Handle a single HTTP request.\n\n You normally don't need to override this method; see the class\n __doc__ string for information on how to handle specific HTTP\n commands such as GET and POST.\n\n \"\"\"\n self.raw_requestline = self.rfile.readline()\n if not self.raw_requestline:\n self.close_connection = 1\n return\n if not self.parse_request(): # An error code has been sent, just exit\n return\n mname = 'do_' + self.command\n if not hasattr(self, mname):\n self.send_error(501, \"Unsupported method (%r)\" % self.command)\n return\n method = getattr(self, mname)\n method()\n\n def handle(self):\n \"\"\"Handle multiple requests if necessary.\"\"\"\n self.close_connection = 1\n\n self.handle_one_request()\n while not self.close_connection:\n self.handle_one_request()\n\n def send_error(self, code, message=None):\n \"\"\"Send and log an error reply.\n\n Arguments are the error code, and a detailed message.\n The detailed message defaults to the short entry matching the\n response code.\n\n This sends an error response (so it must be called before any\n output has been generated), logs the error, and finally sends\n a piece of HTML explaining the error to the user.\n\n \"\"\"\n\n try:\n short, long = self.responses[code]\n except KeyError:\n short, long = '???', '???'\n if message is None:\n message = short\n explain = long\n self.log_error(\"code %d, message %s\", code, message)\n # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)\n content = (self.error_message_format %\n {'code': code, 'message': _quote_html(message), 'explain': explain})\n self.send_response(code, message)\n self.send_header(\"Content-Type\", self.error_content_type)\n self.send_header('Connection', 'close')\n self.end_headers()\n if self.command != 'HEAD' and code >= 200 and code not in (204, 304):\n self.wfile.write(content)\n\n error_message_format = DEFAULT_ERROR_MESSAGE\n error_content_type = DEFAULT_ERROR_CONTENT_TYPE\n\n def send_response(self, code, message=None):\n \"\"\"Send the response header and log the response code.\n\n Also send two standard headers with the server software\n version and the current date.\n\n \"\"\"\n self.log_request(code)\n if message is None:\n if code in self.responses:\n message = self.responses[code][0]\n else:\n message = ''\n if self.request_version != 'HTTP/0.9':\n self.wfile.write(\"%s %d %s\\r\\n\" %\n (self.protocol_version, code, message))\n # print (self.protocol_version, code, message)\n self.send_header('Server', self.version_string())\n self.send_header('Date', self.date_time_string())\n\n def send_header(self, keyword, value):\n \"\"\"Send a MIME header.\"\"\"\n if self.request_version != 'HTTP/0.9':\n self.wfile.write(\"%s: %s\\r\\n\" % (keyword, value))\n\n if keyword.lower() == 'connection':\n if value.lower() == 'close':\n self.close_connection = 1\n elif value.lower() == 'keep-alive':\n self.close_connection = 0\n\n def end_headers(self):\n \"\"\"Send the blank line ending the MIME headers.\"\"\"\n if self.request_version != 'HTTP/0.9':\n self.wfile.write(\"\\r\\n\")\n\n def log_request(self, code='-', size='-'):\n \"\"\"Log an accepted request.\n\n This is called by send_response().\n\n \"\"\"\n\n self.log_message('\"%s\" %s %s',\n self.requestline, str(code), str(size))\n\n def log_error(self, format, *args):\n \"\"\"Log an error.\n\n This is called when a request cannot be fulfilled. By\n default it passes the message on to log_message().\n\n Arguments are the same as for log_message().\n\n XXX This should go to the separate error log.\n\n \"\"\"\n\n self.log_message(format, *args)\n\n def log_message(self, format, *args):\n \"\"\"Log an arbitrary message.\n\n This is used by all other logging functions. Override\n it if you have specific logging wishes.\n\n The first argument, FORMAT, is a format string for the\n message to be logged. If the format string contains\n any % escapes requiring parameters, they should be\n specified as subsequent arguments (it's just like\n printf!).\n\n The client host and current date/time are prefixed to\n every message.\n\n \"\"\"\n\n sys.stderr.write(\"%s - - [%s] %s\\n\" %\n (self.address_string(),\n self.log_date_time_string(),\n format%args))\n\n def version_string(self):\n \"\"\"Return the server software version string.\"\"\"\n return self.server_version + ' ' + self.sys_version\n\n def date_time_string(self, timestamp=None):\n \"\"\"Return the current date and time formatted for a message header.\"\"\"\n if timestamp is None:\n timestamp = time.time()\n year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)\n s = \"%s, %02d %3s %4d %02d:%02d:%02d GMT\" % (\n self.weekdayname[wd],\n day, self.monthname[month], year,\n hh, mm, ss)\n return s\n\n def log_date_time_string(self):\n \"\"\"Return the current time formatted for logging.\"\"\"\n now = time.time()\n year, month, day, hh, mm, ss, x, y, z = time.localtime(now)\n s = \"%02d/%3s/%04d %02d:%02d:%02d\" % (\n day, self.monthname[month], year, hh, mm, ss)\n return s\n\n weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n monthname = [None,\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n def address_string(self):\n \"\"\"Return the client address formatted for logging.\n\n This version looks up the full hostname using gethostbyaddr(),\n and tries to find a name that contains at least one dot.\n\n \"\"\"\n\n host, port = self.client_address[:2]\n return socket.getfqdn(host)\n\n # Essentially static class variables\n\n # The version of the HTTP protocol we support.\n # Set this to HTTP/1.1 to enable automatic keepalive\n protocol_version = \"HTTP/1.0\"\n\n # The Message-like class used to parse headers\n MessageClass = mimetools.Message\n\n # Table mapping response codes to messages; entries have the\n # form {code: (shortmessage, longmessage)}.\n # See RFC 2616.\n responses = {\n 100: ('Continue', 'Request received, please continue'),\n 101: ('Switching Protocols',\n 'Switching to new protocol; obey Upgrade header'),\n\n 200: ('OK', 'Request fulfilled, document follows'),\n 201: ('Created', 'Document created, URL follows'),\n 202: ('Accepted',\n 'Request accepted, processing continues off-line'),\n 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),\n 204: ('No Content', 'Request fulfilled, nothing follows'),\n 205: ('Reset Content', 'Clear input form for further input.'),\n 206: ('Partial Content', 'Partial content follows.'),\n\n 300: ('Multiple Choices',\n 'Object has several resources -- see URI list'),\n 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),\n 302: ('Found', 'Object moved temporarily -- see URI list'),\n 303: ('See Other', 'Object moved -- see Method and URL list'),\n 304: ('Not Modified',\n 'Document has not changed since given time'),\n 305: ('Use Proxy',\n 'You must use proxy specified in Location to access this '\n 'resource.'),\n 307: ('Temporary Redirect',\n 'Object moved temporarily -- see URI list'),\n\n 400: ('Bad Request',\n 'Bad request syntax or unsupported method'),\n 401: ('Unauthorized',\n 'No permission -- see authorization schemes'),\n 402: ('Payment Required',\n 'No payment -- see charging schemes'),\n 403: ('Forbidden',\n 'Request forbidden -- authorization will not help'),\n 404: ('Not Found', 'Nothing matches the given URI'),\n 405: ('Method Not Allowed',\n 'Specified method is invalid for this server.'),\n 406: ('Not Acceptable', 'URI not available in preferred format.'),\n 407: ('Proxy Authentication Required', 'You must authenticate with '\n 'this proxy before proceeding.'),\n 408: ('Request Timeout', 'Request timed out; try again later.'),\n 409: ('Conflict', 'Request conflict.'),\n 410: ('Gone',\n 'URI no longer exists and has been permanently removed.'),\n 411: ('Length Required', 'Client must specify Content-Length.'),\n 412: ('Precondition Failed', 'Precondition in headers is false.'),\n 413: ('Request Entity Too Large', 'Entity is too large.'),\n 414: ('Request-URI Too Long', 'URI is too long.'),\n 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),\n 416: ('Requested Range Not Satisfiable',\n 'Cannot satisfy request range.'),\n 417: ('Expectation Failed',\n 'Expect condition could not be satisfied.'),\n\n 500: ('Internal Server Error', 'Server got itself in trouble'),\n 501: ('Not Implemented',\n 'Server does not support this operation'),\n 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),\n 503: ('Service Unavailable',\n 'The server cannot process the request due to a high load'),\n 504: ('Gateway Timeout',\n 'The gateway server did not receive a timely response'),\n 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),\n }\n\n\ndef test(HandlerClass = BaseHTTPRequestHandler,\n ServerClass = HTTPServer, protocol=\"HTTP/1.0\"):\n \"\"\"Test the HTTP request handler class.\n\n This runs an HTTP server on port 8000 (or the first command line\n argument).\n\n \"\"\"\n\n if sys.argv[1:]:\n port = int(sys.argv[1])\n else:\n port = 8000\n server_address = ('', port)\n\n HandlerClass.protocol_version = protocol\n httpd = ServerClass(server_address, HandlerClass)\n\n sa = httpd.socket.getsockname()\n print \"Serving HTTP on\", sa[0], \"port\", sa[1], \"...\"\n httpd.serve_forever()\n\n\nif __name__ == '__main__':\n test()\n"}}},{"rowIdx":281918,"cells":{"repo_name":{"kind":"string","value":"canglade/NLP"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"logging/cloud-client/export_test.py"},"copies":{"kind":"string","value":"4"},"content":{"kind":"string","value":"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport random\nimport string\n\nfrom gcp_devrel.testing import eventually_consistent\nfrom google.cloud import logging\nimport pytest\n\nimport export\n\nBUCKET = os.environ['CLOUD_STORAGE_BUCKET']\nTEST_SINK_NAME_TMPL = 'example_sink_{}'\nTEST_SINK_FILTER = 'severity>=CRITICAL'\n\n\ndef _random_id():\n return ''.join(\n random.choice(string.ascii_uppercase + string.digits)\n for _ in range(6))\n\n\n@pytest.yield_fixture\ndef example_sink():\n client = logging.Client()\n\n sink = client.sink(\n TEST_SINK_NAME_TMPL.format(_random_id()),\n TEST_SINK_FILTER,\n 'storage.googleapis.com/{bucket}'.format(bucket=BUCKET))\n\n sink.create()\n\n yield sink\n\n try:\n sink.delete()\n except:\n pass\n\n\ndef test_list(example_sink, capsys):\n @eventually_consistent.call\n def _():\n export.list_sinks()\n out, _ = capsys.readouterr()\n assert example_sink.name in out\n\n\ndef test_create(capsys):\n sink_name = TEST_SINK_NAME_TMPL.format(_random_id())\n\n try:\n export.create_sink(\n sink_name,\n BUCKET,\n TEST_SINK_FILTER)\n # Clean-up the temporary sink.\n finally:\n try:\n logging.Client().sink(sink_name).delete()\n except:\n pass\n\n out, _ = capsys.readouterr()\n assert sink_name in out\n\n\ndef test_update(example_sink, capsys):\n updated_filter = 'severity>=INFO'\n export.update_sink(example_sink.name, updated_filter)\n\n example_sink.reload()\n assert example_sink.filter_ == updated_filter\n\n\ndef test_delete(example_sink, capsys):\n export.delete_sink(example_sink.name)\n assert not example_sink.exists()\n"}}},{"rowIdx":281919,"cells":{"repo_name":{"kind":"string","value":"mozilla/olympia"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"src/olympia/shelves/migrations/0003_auto_20200720_1509.py"},"copies":{"kind":"string","value":"6"},"content":{"kind":"string","value":"# Generated by Django 2.2.14 on 2020-07-20 15:09\n\nfrom django.db import migrations, models\nimport olympia.shelves.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('shelves', '0002_auto_20200716_1254'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='shelf',\n name='criteria',\n field=models.CharField(help_text='e.g., ?recommended=true&sort=random&type=extension', max_length=200,),\n ),\n migrations.AlterField(\n model_name='shelf',\n name='shelf_type',\n field=models.CharField(choices=[('categories', 'categories'), ('collections', 'collections'), ('extension', 'extension'), ('recommendations', 'recommendations'), ('search', 'search'), ('theme', 'theme')], max_length=200, verbose_name='type'),\n ),\n ]\n"}}},{"rowIdx":281920,"cells":{"repo_name":{"kind":"string","value":"acsone/odoo"},"ref":{"kind":"string","value":"refs/heads/8.0"},"path":{"kind":"string","value":"addons/website_forum/models/forum.py"},"copies":{"kind":"string","value":"233"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nimport uuid\nfrom werkzeug.exceptions import Forbidden\n\nimport logging\nimport openerp\n\nfrom openerp import api, tools\nfrom openerp import SUPERUSER_ID\nfrom openerp.addons.website.models.website import slug\nfrom openerp.exceptions import Warning\nfrom openerp.osv import osv, fields\nfrom openerp.tools import html2plaintext\nfrom openerp.tools.translate import _\n\n_logger = logging.getLogger(__name__)\n\nclass KarmaError(Forbidden):\n \"\"\" Karma-related error, used for forum and posts. \"\"\"\n pass\n\n\nclass Forum(osv.Model):\n \"\"\"TDE TODO: set karma values for actions dynamic for a given forum\"\"\"\n _name = 'forum.forum'\n _description = 'Forums'\n _inherit = ['mail.thread', 'website.seo.metadata']\n\n def init(self, cr):\n \"\"\" Add forum uuid for user email validation. \"\"\"\n forum_uuids = self.pool['ir.config_parameter'].search(cr, SUPERUSER_ID, [('key', '=', 'website_forum.uuid')])\n if not forum_uuids:\n self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'website_forum.uuid', str(uuid.uuid4()), ['base.group_system'])\n\n _columns = {\n 'name': fields.char('Name', required=True, translate=True),\n 'faq': fields.html('Guidelines'),\n 'description': fields.html('Description', translate=True),\n # karma generation\n 'karma_gen_question_new': fields.integer('Asking a question'),\n 'karma_gen_question_upvote': fields.integer('Question upvoted'),\n 'karma_gen_question_downvote': fields.integer('Question downvoted'),\n 'karma_gen_answer_upvote': fields.integer('Answer upvoted'),\n 'karma_gen_answer_downvote': fields.integer('Answer downvoted'),\n 'karma_gen_answer_accept': fields.integer('Accepting an answer'),\n 'karma_gen_answer_accepted': fields.integer('Answer accepted'),\n 'karma_gen_answer_flagged': fields.integer('Answer flagged'),\n # karma-based actions\n 'karma_ask': fields.integer('Ask a question'),\n 'karma_answer': fields.integer('Answer a question'),\n 'karma_edit_own': fields.integer('Edit its own posts'),\n 'karma_edit_all': fields.integer('Edit all posts'),\n 'karma_close_own': fields.integer('Close its own posts'),\n 'karma_close_all': fields.integer('Close all posts'),\n 'karma_unlink_own': fields.integer('Delete its own posts'),\n 'karma_unlink_all': fields.integer('Delete all posts'),\n 'karma_upvote': fields.integer('Upvote'),\n 'karma_downvote': fields.integer('Downvote'),\n 'karma_answer_accept_own': fields.integer('Accept an answer on its own questions'),\n 'karma_answer_accept_all': fields.integer('Accept an answer to all questions'),\n 'karma_editor_link_files': fields.integer('Linking files (Editor)'),\n 'karma_editor_clickable_link': fields.integer('Clickable links (Editor)'),\n 'karma_comment_own': fields.integer('Comment its own posts'),\n 'karma_comment_all': fields.integer('Comment all posts'),\n 'karma_comment_convert_own': fields.integer('Convert its own answers to comments and vice versa'),\n 'karma_comment_convert_all': fields.integer('Convert all answers to comments and vice versa'),\n 'karma_comment_unlink_own': fields.integer('Unlink its own comments'),\n 'karma_comment_unlink_all': fields.integer('Unlink all comments'),\n 'karma_retag': fields.integer('Change question tags'),\n 'karma_flag': fields.integer('Flag a post as offensive'),\n }\n\n def _get_default_faq(self, cr, uid, context=None):\n fname = openerp.modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html')\n with open(fname, 'r') as f:\n return f.read()\n return False\n\n _defaults = {\n 'description': 'This community is for professionals and enthusiasts of our products and services.',\n 'faq': _get_default_faq,\n 'karma_gen_question_new': 0, # set to null for anti spam protection\n 'karma_gen_question_upvote': 5,\n 'karma_gen_question_downvote': -2,\n 'karma_gen_answer_upvote': 10,\n 'karma_gen_answer_downvote': -2,\n 'karma_gen_answer_accept': 2,\n 'karma_gen_answer_accepted': 15,\n 'karma_gen_answer_flagged': -100,\n 'karma_ask': 3, # set to not null for anti spam protection\n 'karma_answer': 3, # set to not null for anti spam protection\n 'karma_edit_own': 1,\n 'karma_edit_all': 300,\n 'karma_close_own': 100,\n 'karma_close_all': 500,\n 'karma_unlink_own': 500,\n 'karma_unlink_all': 1000,\n 'karma_upvote': 5,\n 'karma_downvote': 50,\n 'karma_answer_accept_own': 20,\n 'karma_answer_accept_all': 500,\n 'karma_editor_link_files': 20,\n 'karma_editor_clickable_link': 20,\n 'karma_comment_own': 3,\n 'karma_comment_all': 5,\n 'karma_comment_convert_own': 50,\n 'karma_comment_convert_all': 500,\n 'karma_comment_unlink_own': 50,\n 'karma_comment_unlink_all': 500,\n 'karma_retag': 75,\n 'karma_flag': 500,\n }\n\n def create(self, cr, uid, values, context=None):\n if context is None:\n context = {}\n create_context = dict(context, mail_create_nolog=True)\n return super(Forum, self).create(cr, uid, values, context=create_context)\n\n def _tag_to_write_vals(self, cr, uid, ids, tags='', context=None):\n User = self.pool['res.users']\n Tag = self.pool['forum.tag']\n result = {}\n for forum in self.browse(cr, uid, ids, context=context):\n post_tags = []\n existing_keep = []\n for tag in filter(None, tags.split(',')):\n if tag.startswith('_'): # it's a new tag\n # check that not already created meanwhile or maybe excluded by the limit on the search\n tag_ids = Tag.search(cr, uid, [('name', '=', tag[1:])], context=context)\n if tag_ids:\n existing_keep.append(int(tag_ids[0]))\n else:\n # check if user have Karma needed to create need tag\n user = User.browse(cr, uid, uid, context=context)\n if user.exists() and user.karma >= forum.karma_retag:\n post_tags.append((0, 0, {'name': tag[1:], 'forum_id': forum.id}))\n else:\n existing_keep.append(int(tag))\n post_tags.insert(0, [6, 0, existing_keep])\n result[forum.id] = post_tags\n\n return result\n\n\nclass Post(osv.Model):\n _name = 'forum.post'\n _description = 'Forum Post'\n _inherit = ['mail.thread', 'website.seo.metadata']\n _order = \"is_correct DESC, vote_count DESC, write_date DESC\"\n\n def _get_user_vote(self, cr, uid, ids, field_name, arg, context):\n res = dict.fromkeys(ids, 0)\n vote_ids = self.pool['forum.post.vote'].search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context)\n for vote in self.pool['forum.post.vote'].browse(cr, uid, vote_ids, context=context):\n res[vote.post_id.id] = vote.vote\n return res\n\n def _get_vote_count(self, cr, uid, ids, field_name, arg, context):\n res = dict.fromkeys(ids, 0)\n for post in self.browse(cr, uid, ids, context=context):\n for vote in post.vote_ids:\n res[post.id] += int(vote.vote)\n return res\n\n def _get_post_from_vote(self, cr, uid, ids, context=None):\n result = {}\n for vote in self.pool['forum.post.vote'].browse(cr, uid, ids, context=context):\n result[vote.post_id.id] = True\n return result.keys()\n\n def _get_user_favourite(self, cr, uid, ids, field_name, arg, context):\n res = dict.fromkeys(ids, False)\n for post in self.browse(cr, uid, ids, context=context):\n if uid in [f.id for f in post.favourite_ids]:\n res[post.id] = True\n return res\n\n def _get_favorite_count(self, cr, uid, ids, field_name, arg, context):\n res = dict.fromkeys(ids, 0)\n for post in self.browse(cr, uid, ids, context=context):\n res[post.id] += len(post.favourite_ids)\n return res\n\n def _get_post_from_hierarchy(self, cr, uid, ids, context=None):\n post_ids = set(ids)\n for post in self.browse(cr, SUPERUSER_ID, ids, context=context):\n if post.parent_id:\n post_ids.add(post.parent_id.id)\n return list(post_ids)\n\n def _get_child_count(self, cr, uid, ids, field_name=False, arg={}, context=None):\n res = dict.fromkeys(ids, 0)\n for post in self.browse(cr, uid, ids, context=context):\n if post.parent_id:\n res[post.parent_id.id] = len(post.parent_id.child_ids)\n else:\n res[post.id] = len(post.child_ids)\n return res\n\n def _get_uid_answered(self, cr, uid, ids, field_name, arg, context=None):\n res = dict.fromkeys(ids, False)\n for post in self.browse(cr, uid, ids, context=context):\n res[post.id] = any(answer.create_uid.id == uid for answer in post.child_ids)\n return res\n\n def _get_has_validated_answer(self, cr, uid, ids, field_name, arg, context=None):\n res = dict.fromkeys(ids, False)\n ans_ids = self.search(cr, uid, [('parent_id', 'in', ids), ('is_correct', '=', True)], context=context)\n for answer in self.browse(cr, uid, ans_ids, context=context):\n res[answer.parent_id.id] = True\n return res\n\n def _is_self_reply(self, cr, uid, ids, field_name, arg, context=None):\n res = dict.fromkeys(ids, False)\n for post in self.browse(cr, uid, ids, context=context):\n res[post.id] = post.parent_id and post.parent_id.create_uid == post.create_uid or False\n return res\n\n def _get_post_karma_rights(self, cr, uid, ids, field_name, arg, context=None):\n user = self.pool['res.users'].browse(cr, uid, uid, context=context)\n res = dict.fromkeys(ids, False)\n for post in self.browse(cr, SUPERUSER_ID, ids, context=context):\n res[post.id] = {\n 'karma_ask': post.forum_id.karma_ask,\n 'karma_answer': post.forum_id.karma_answer,\n 'karma_accept': post.parent_id and post.parent_id.create_uid.id == uid and post.forum_id.karma_answer_accept_own or post.forum_id.karma_answer_accept_all,\n 'karma_edit': post.create_uid.id == uid and post.forum_id.karma_edit_own or post.forum_id.karma_edit_all,\n 'karma_close': post.create_uid.id == uid and post.forum_id.karma_close_own or post.forum_id.karma_close_all,\n 'karma_unlink': post.create_uid.id == uid and post.forum_id.karma_unlink_own or post.forum_id.karma_unlink_all,\n 'karma_upvote': post.forum_id.karma_upvote,\n 'karma_downvote': post.forum_id.karma_downvote,\n 'karma_comment': post.create_uid.id == uid and post.forum_id.karma_comment_own or post.forum_id.karma_comment_all,\n 'karma_comment_convert': post.create_uid.id == uid and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all,\n }\n res[post.id].update({\n 'can_ask': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_ask'],\n 'can_answer': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_answer'],\n 'can_accept': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_accept'],\n 'can_edit': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_edit'],\n 'can_close': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_close'],\n 'can_unlink': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_unlink'],\n 'can_upvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_upvote'],\n 'can_downvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_downvote'],\n 'can_comment': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment'],\n 'can_comment_convert': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment_convert'],\n 'can_view': (uid == SUPERUSER_ID or\n user.karma >= res[post.id]['karma_close'] or\n post.create_uid.karma > 0),\n })\n return res\n\n _columns = {\n 'name': fields.char('Title'),\n 'forum_id': fields.many2one('forum.forum', 'Forum', required=True),\n 'content': fields.html('Content', strip_style=True),\n 'tag_ids': fields.many2many('forum.tag', 'forum_tag_rel', 'forum_id', 'forum_tag_id', 'Tags'),\n 'state': fields.selection([('active', 'Active'), ('close', 'Close'), ('offensive', 'Offensive')], 'Status'),\n 'views': fields.integer('Number of Views'),\n 'active': fields.boolean('Active'),\n 'is_correct': fields.boolean('Valid Answer', help='Correct Answer or Answer on this question accepted.'),\n 'website_message_ids': fields.one2many(\n 'mail.message', 'res_id',\n domain=lambda self: [\n '&', ('model', '=', self._name), ('type', 'in', ['email', 'comment'])\n ],\n string='Post Messages', help=\"Comments on forum post\",\n ),\n # history\n 'create_date': fields.datetime('Asked on', select=True, readonly=True),\n 'create_uid': fields.many2one('res.users', 'Created by', select=True, readonly=True),\n 'write_date': fields.datetime('Update on', select=True, readonly=True),\n 'write_uid': fields.many2one('res.users', 'Updated by', select=True, readonly=True),\n # vote fields\n 'vote_ids': fields.one2many('forum.post.vote', 'post_id', 'Votes'),\n 'user_vote': fields.function(_get_user_vote, string='My Vote', type='integer'),\n 'vote_count': fields.function(\n _get_vote_count, string=\"Votes\", type='integer',\n store={\n 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['vote_ids'], 10),\n 'forum.post.vote': (_get_post_from_vote, [], 10),\n }),\n # favorite fields\n 'favourite_ids': fields.many2many('res.users', string='Favourite'),\n 'user_favourite': fields.function(_get_user_favourite, string=\"My Favourite\", type='boolean'),\n 'favourite_count': fields.function(\n _get_favorite_count, string='Favorite Count', type='integer',\n store={\n 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['favourite_ids'], 10),\n }),\n # hierarchy\n 'parent_id': fields.many2one('forum.post', 'Question', ondelete='cascade'),\n 'self_reply': fields.function(\n _is_self_reply, 'Reply to own question', type='boolean',\n store={\n 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['parent_id', 'create_uid'], 10),\n }),\n 'child_ids': fields.one2many('forum.post', 'parent_id', 'Answers'),\n 'child_count': fields.function(\n _get_child_count, string=\"Answers\", type='integer',\n store={\n 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids'], 10),\n }),\n 'uid_has_answered': fields.function(\n _get_uid_answered, string='Has Answered', type='boolean',\n ),\n 'has_validated_answer': fields.function(\n _get_has_validated_answer, string='Has a Validated Answered', type='boolean',\n store={\n 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids', 'is_correct'], 10),\n }\n ),\n # closing\n 'closed_reason_id': fields.many2one('forum.post.reason', 'Reason'),\n 'closed_uid': fields.many2one('res.users', 'Closed by', select=1),\n 'closed_date': fields.datetime('Closed on', readonly=True),\n # karma\n 'karma_ask': fields.function(_get_post_karma_rights, string='Karma to ask', type='integer', multi='_get_post_karma_rights'),\n 'karma_answer': fields.function(_get_post_karma_rights, string='Karma to answer', type='integer', multi='_get_post_karma_rights'),\n 'karma_accept': fields.function(_get_post_karma_rights, string='Karma to accept this answer', type='integer', multi='_get_post_karma_rights'),\n 'karma_edit': fields.function(_get_post_karma_rights, string='Karma to edit', type='integer', multi='_get_post_karma_rights'),\n 'karma_close': fields.function(_get_post_karma_rights, string='Karma to close', type='integer', multi='_get_post_karma_rights'),\n 'karma_unlink': fields.function(_get_post_karma_rights, string='Karma to unlink', type='integer', multi='_get_post_karma_rights'),\n 'karma_upvote': fields.function(_get_post_karma_rights, string='Karma to upvote', type='integer', multi='_get_post_karma_rights'),\n 'karma_downvote': fields.function(_get_post_karma_rights, string='Karma to downvote', type='integer', multi='_get_post_karma_rights'),\n 'karma_comment': fields.function(_get_post_karma_rights, string='Karma to comment', type='integer', multi='_get_post_karma_rights'),\n 'karma_comment_convert': fields.function(_get_post_karma_rights, string='karma to convert as a comment', type='integer', multi='_get_post_karma_rights'),\n # access rights\n 'can_ask': fields.function(_get_post_karma_rights, string='Can Ask', type='boolean', multi='_get_post_karma_rights'),\n 'can_answer': fields.function(_get_post_karma_rights, string='Can Answer', type='boolean', multi='_get_post_karma_rights'),\n 'can_accept': fields.function(_get_post_karma_rights, string='Can Accept', type='boolean', multi='_get_post_karma_rights'),\n 'can_edit': fields.function(_get_post_karma_rights, string='Can Edit', type='boolean', multi='_get_post_karma_rights'),\n 'can_close': fields.function(_get_post_karma_rights, string='Can Close', type='boolean', multi='_get_post_karma_rights'),\n 'can_unlink': fields.function(_get_post_karma_rights, string='Can Unlink', type='boolean', multi='_get_post_karma_rights'),\n 'can_upvote': fields.function(_get_post_karma_rights, string='Can Upvote', type='boolean', multi='_get_post_karma_rights'),\n 'can_downvote': fields.function(_get_post_karma_rights, string='Can Downvote', type='boolean', multi='_get_post_karma_rights'),\n 'can_comment': fields.function(_get_post_karma_rights, string='Can Comment', type='boolean', multi='_get_post_karma_rights'),\n 'can_comment_convert': fields.function(_get_post_karma_rights, string='Can Convert to Comment', type='boolean', multi='_get_post_karma_rights'),\n 'can_view': fields.function(_get_post_karma_rights, string='Can View', type='boolean', multi='_get_post_karma_rights'),\n }\n\n _defaults = {\n 'state': 'active',\n 'views': 0,\n 'active': True,\n 'vote_ids': list(),\n 'favourite_ids': list(),\n 'child_ids': list(),\n }\n\n def name_get(self, cr, uid, ids, context=None):\n result = []\n for post in self.browse(cr, uid, ids, context=context):\n if post.parent_id and not post.name:\n result.append((post.id, '%s (%s)' % (post.parent_id.name, post.id)))\n else:\n result.append((post.id, '%s' % (post.name)))\n return result\n\n def create(self, cr, uid, vals, context=None):\n if context is None:\n context = {}\n create_context = dict(context, mail_create_nolog=True)\n post_id = super(Post, self).create(cr, uid, vals, context=create_context)\n post = self.browse(cr, uid, post_id, context=context)\n # karma-based access\n if not post.parent_id and not post.can_ask:\n raise KarmaError('Not enough karma to create a new question')\n elif post.parent_id and not post.can_answer:\n raise KarmaError('Not enough karma to answer to a question')\n # messaging and chatter\n base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')\n if post.parent_id:\n body = _(\n '
' %\n (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))\n )\n self.message_post(cr, uid, post_id, subject=post.name, body=body, subtype='website_forum.mt_question_new', context=context)\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_question_new, context=context)\n return post_id\n\n def check_mail_message_access(self, cr, uid, mids, operation, model_obj=None, context=None):\n for post in self.browse(cr, uid, mids, context=context):\n # Make sure only author or moderator can edit/delete messages\n if operation in ('write', 'unlink') and not post.can_edit:\n raise KarmaError('Not enough karma to edit a post.')\n return super(Post, self).check_mail_message_access(\n cr, uid, mids, operation, model_obj=model_obj, context=context)\n\n def write(self, cr, uid, ids, vals, context=None):\n posts = self.browse(cr, uid, ids, context=context)\n if 'state' in vals:\n if vals['state'] in ['active', 'close'] and any(not post.can_close for post in posts):\n raise KarmaError('Not enough karma to close or reopen a post.')\n if 'active' in vals:\n if any(not post.can_unlink for post in posts):\n raise KarmaError('Not enough karma to delete or reactivate a post')\n if 'is_correct' in vals:\n if any(not post.can_accept for post in posts):\n raise KarmaError('Not enough karma to accept or refuse an answer')\n # update karma except for self-acceptance\n mult = 1 if vals['is_correct'] else -1\n for post in self.browse(cr, uid, ids, context=context):\n if vals['is_correct'] != post.is_correct and post.create_uid.id != uid:\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * mult, context=context)\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * mult, context=context)\n if any(key not in ['state', 'active', 'is_correct', 'closed_uid', 'closed_date', 'closed_reason_id'] for key in vals.keys()) and any(not post.can_edit for post in posts):\n raise KarmaError('Not enough karma to edit a post.')\n\n res = super(Post, self).write(cr, uid, ids, vals, context=context)\n # if post content modify, notify followers\n if 'content' in vals or 'name' in vals:\n for post in posts:\n if post.parent_id:\n body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit'\n obj_id = post.parent_id.id\n else:\n body, subtype = _('Question Edited'), 'website_forum.mt_question_edit'\n obj_id = post.id\n self.message_post(cr, uid, obj_id, body=body, subtype=subtype, context=context)\n return res\n\n\n def reopen(self, cr, uid, ids, context=None):\n if any(post.parent_id or post.state != 'close'\n for post in self.browse(cr, uid, ids, context=context)):\n return False\n\n reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7')\n reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8')\n for post in self.browse(cr, uid, ids, context=context):\n if post.closed_reason_id.id in (reason_offensive, reason_spam):\n _logger.info('Upvoting user <%s>, reopening spam/offensive question',\n post.create_uid)\n # TODO: in master, consider making this a tunable karma parameter\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id],\n post.forum_id.karma_gen_question_downvote * -5,\n context=context)\n self.pool['forum.post'].write(cr, SUPERUSER_ID, ids, {'state': 'active'}, context=context)\n\n def close(self, cr, uid, ids, reason_id, context=None):\n if any(post.parent_id for post in self.browse(cr, uid, ids, context=context)):\n return False\n\n reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7')\n reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8')\n if reason_id in (reason_offensive, reason_spam):\n for post in self.browse(cr, uid, ids, context=context):\n _logger.info('Downvoting user <%s> for posting spam/offensive contents',\n post.create_uid)\n # TODO: in master, consider making this a tunable karma parameter\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id],\n post.forum_id.karma_gen_question_downvote * 5,\n context=context)\n\n self.pool['forum.post'].write(cr, uid, ids, {\n 'state': 'close',\n 'closed_uid': uid,\n 'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT),\n 'closed_reason_id': reason_id,\n }, context=context)\n\n def unlink(self, cr, uid, ids, context=None):\n posts = self.browse(cr, uid, ids, context=context)\n if any(not post.can_unlink for post in posts):\n raise KarmaError('Not enough karma to unlink a post')\n # if unlinking an answer with accepted answer: remove provided karma\n for post in posts:\n if post.is_correct:\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * -1, context=context)\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * -1, context=context)\n return super(Post, self).unlink(cr, uid, ids, context=context)\n\n def vote(self, cr, uid, ids, upvote=True, context=None):\n Vote = self.pool['forum.post.vote']\n vote_ids = Vote.search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context)\n new_vote = '1' if upvote else '-1'\n voted_forum_ids = set()\n if vote_ids:\n for vote in Vote.browse(cr, uid, vote_ids, context=context):\n if upvote:\n new_vote = '0' if vote.vote == '-1' else '1'\n else:\n new_vote = '0' if vote.vote == '1' else '-1'\n Vote.write(cr, uid, vote_ids, {'vote': new_vote}, context=context)\n voted_forum_ids.add(vote.post_id.id)\n for post_id in set(ids) - voted_forum_ids:\n for post_id in ids:\n Vote.create(cr, uid, {'post_id': post_id, 'vote': new_vote}, context=context)\n return {'vote_count': self._get_vote_count(cr, uid, ids, None, None, context=context)[ids[0]], 'user_vote': new_vote}\n\n def convert_answer_to_comment(self, cr, uid, id, context=None):\n \"\"\" Tools to convert an answer (forum.post) to a comment (mail.message).\n The original post is unlinked and a new comment is posted on the question\n using the post create_uid as the comment's author. \"\"\"\n post = self.browse(cr, SUPERUSER_ID, id, context=context)\n if not post.parent_id:\n return False\n\n # karma-based action check: use the post field that computed own/all value\n if not post.can_comment_convert:\n raise KarmaError('Not enough karma to convert an answer to a comment')\n\n # post the message\n question = post.parent_id\n values = {\n 'author_id': post.create_uid.partner_id.id,\n 'body': html2plaintext(post.content),\n 'type': 'comment',\n 'subtype': 'mail.mt_comment',\n 'date': post.create_date,\n }\n message_id = self.pool['forum.post'].message_post(\n cr, uid, question.id,\n context=dict(context, mail_create_nosubscribe=True),\n **values)\n\n # unlink the original answer, using SUPERUSER_ID to avoid karma issues\n self.pool['forum.post'].unlink(cr, SUPERUSER_ID, [post.id], context=context)\n\n return message_id\n\n def convert_comment_to_answer(self, cr, uid, message_id, default=None, context=None):\n \"\"\" Tool to convert a comment (mail.message) into an answer (forum.post).\n The original comment is unlinked and a new answer from the comment's author\n is created. Nothing is done if the comment's author already answered the\n question. \"\"\"\n comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)\n post = self.pool['forum.post'].browse(cr, uid, comment.res_id, context=context)\n user = self.pool['res.users'].browse(cr, uid, uid, context=context)\n if not comment.author_id or not comment.author_id.user_ids: # only comment posted by users can be converted\n return False\n\n # karma-based action check: must check the message's author to know if own / all\n karma_convert = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all\n can_convert = uid == SUPERUSER_ID or user.karma >= karma_convert\n if not can_convert:\n raise KarmaError('Not enough karma to convert a comment to an answer')\n\n # check the message's author has not already an answer\n question = post.parent_id if post.parent_id else post\n post_create_uid = comment.author_id.user_ids[0]\n if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids):\n return False\n\n # create the new post\n post_values = {\n 'forum_id': question.forum_id.id,\n 'content': comment.body,\n 'parent_id': question.id,\n }\n # done with the author user to have create_uid correctly set\n new_post_id = self.pool['forum.post'].create(cr, post_create_uid.id, post_values, context=context)\n\n # delete comment\n self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [comment.id], context=context)\n\n return new_post_id\n\n def unlink_comment(self, cr, uid, id, message_id, context=None):\n comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)\n post = self.pool['forum.post'].browse(cr, uid, id, context=context)\n user = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context)\n if not comment.model == 'forum.post' or not comment.res_id == id:\n return False\n\n # karma-based action check: must check the message's author to know if own or all\n karma_unlink = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_unlink_own or post.forum_id.karma_comment_unlink_all\n can_unlink = uid == SUPERUSER_ID or user.karma >= karma_unlink\n if not can_unlink:\n raise KarmaError('Not enough karma to unlink a comment')\n\n return self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [message_id], context=context)\n\n def set_viewed(self, cr, uid, ids, context=None):\n cr.execute(\"\"\"UPDATE forum_post SET views = views+1 WHERE id IN %s\"\"\", (tuple(ids),))\n return True\n\n def _get_access_link(self, cr, uid, mail, partner, context=None):\n post = self.pool['forum.post'].browse(cr, uid, mail.res_id, context=context)\n res_id = post.parent_id and \"%s#answer-%s\" % (post.parent_id.id, post.id) or post.id\n return \"/forum/%s/question/%s\" % (post.forum_id.id, res_id)\n\n @api.cr_uid_ids_context\n def message_post(self, cr, uid, thread_id, type='notification', subtype=None, context=None, **kwargs):\n if thread_id and type == 'comment': # user comments have a restriction on karma\n if isinstance(thread_id, (list, tuple)):\n post_id = thread_id[0]\n else:\n post_id = thread_id\n post = self.browse(cr, uid, post_id, context=context)\n if not post.can_comment:\n raise KarmaError('Not enough karma to comment')\n return super(Post, self).message_post(cr, uid, thread_id, type=type, subtype=subtype, context=context, **kwargs)\n\n\nclass PostReason(osv.Model):\n _name = \"forum.post.reason\"\n _description = \"Post Closing Reason\"\n _order = 'name'\n _columns = {\n 'name': fields.char('Post Reason', required=True, translate=True),\n }\n\n\nclass Vote(osv.Model):\n _name = 'forum.post.vote'\n _description = 'Vote'\n _columns = {\n 'post_id': fields.many2one('forum.post', 'Post', ondelete='cascade', required=True),\n 'user_id': fields.many2one('res.users', 'User', required=True),\n 'vote': fields.selection([('1', '1'), ('-1', '-1'), ('0', '0')], 'Vote', required=True),\n 'create_date': fields.datetime('Create Date', select=True, readonly=True),\n\n # TODO master: store these two\n 'forum_id': fields.related('post_id', 'forum_id', type='many2one', relation='forum.forum', string='Forum'),\n 'recipient_id': fields.related('post_id', 'create_uid', type='many2one', relation='res.users', string='To', help=\"The user receiving the vote\"),\n }\n _defaults = {\n 'user_id': lambda self, cr, uid, ctx: uid,\n 'vote': lambda *args: '1',\n }\n\n def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma):\n _karma_upd = {\n '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma},\n '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma},\n '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0}\n }\n return _karma_upd[old_vote][new_vote]\n\n def create(self, cr, uid, vals, context=None):\n vote_id = super(Vote, self).create(cr, uid, vals, context=context)\n vote = self.browse(cr, uid, vote_id, context=context)\n\n # own post check\n if vote.user_id.id == vote.post_id.create_uid.id:\n raise Warning('Not allowed to vote for its own post')\n # karma check\n if vote.vote == '1' and not vote.post_id.can_upvote:\n raise KarmaError('Not enough karma to upvote.')\n elif vote.vote == '-1' and not vote.post_id.can_downvote:\n raise KarmaError('Not enough karma to downvote.')\n\n # karma update\n if vote.post_id.parent_id:\n karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)\n else:\n karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)\n return vote_id\n\n def write(self, cr, uid, ids, values, context=None):\n if 'vote' in values:\n for vote in self.browse(cr, uid, ids, context=context):\n # own post check\n if vote.user_id.id == vote.post_id.create_uid.id:\n raise Warning('Not allowed to vote for its own post')\n # karma check\n if (values['vote'] == '1' or vote.vote == '-1' and values['vote'] == '0') and not vote.post_id.can_upvote:\n raise KarmaError('Not enough karma to upvote.')\n elif (values['vote'] == '-1' or vote.vote == '1' and values['vote'] == '0') and not vote.post_id.can_downvote:\n raise KarmaError('Not enough karma to downvote.')\n\n # karma update\n if vote.post_id.parent_id:\n karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)\n else:\n karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)\n self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)\n res = super(Vote, self).write(cr, uid, ids, values, context=context)\n return res\n\n\nclass Tags(osv.Model):\n _name = \"forum.tag\"\n _description = \"Tag\"\n _inherit = ['website.seo.metadata']\n\n def _get_posts_count(self, cr, uid, ids, field_name, arg, context=None):\n return dict((tag_id, self.pool['forum.post'].search_count(cr, uid, [('tag_ids', 'in', tag_id)], context=context)) for tag_id in ids)\n\n def _get_tag_from_post(self, cr, uid, ids, context=None):\n return list(set(\n [tag.id for post in self.pool['forum.post'].browse(cr, SUPERUSER_ID, ids, context=context) for tag in post.tag_ids]\n ))\n\n _columns = {\n 'name': fields.char('Name', required=True),\n 'forum_id': fields.many2one('forum.forum', 'Forum', required=True),\n 'post_ids': fields.many2many('forum.post', 'forum_tag_rel', 'tag_id', 'post_id', 'Posts'),\n 'posts_count': fields.function(\n _get_posts_count, type='integer', string=\"Number of Posts\",\n store={\n 'forum.post': (_get_tag_from_post, ['tag_ids'], 10),\n }\n ),\n 'create_uid': fields.many2one('res.users', 'Created by', readonly=True),\n }\n"}}},{"rowIdx":281921,"cells":{"repo_name":{"kind":"string","value":"eamonnmag/invenio-search"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"docs/_ext/ultramock.py"},"copies":{"kind":"string","value":"164"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n#\n# This file is part of Invenio.\n# Copyright (C) 2015 CERN.\n#\n# Invenio is free software; you can redistribute it\n# and/or modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# Invenio is distributed in the hope that it will be\n# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Invenio; if not, write to the\n# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307, USA.\n#\n# In applying this license, CERN does not\n# waive the privileges and immunities granted to it by virtue of its status\n# as an Intergovernmental Organization or submit itself to any jurisdiction.\n\n\"\"\"Hijacks `mock` to fake as many non-available modules as possible.\"\"\"\nimport sys\nimport types\n\ntry:\n import unittest.mock as mock\nexcept ImportError:\n import mock\n\n# skip `_is_magic` check.\norig_is_magic = mock._is_magic\ndef always_false(*args, **kwargs):\n return False\n\n\n# avoid spec configuration for mocked classes with super classes.\n# honestly this does not happen very often and is kind of a tricky case.\norig_mock_add_spec = mock.NonCallableMock._mock_add_spec\ndef mock_add_spec_fake(self, spec, spec_set):\n orig_mock_add_spec(self, None, None)\n\n\n# special MagicMock with empty docs\nclass MyMagicMock(mock.MagicMock):\n \"\"\"\"\"\"\n\n\n# set up a fake class-metaclass hierarchy\nclass SuperMockMetaMeta(MyMagicMock):\n __metaclass__ = MyMagicMock()\n\n\nclass SuperMockMeta(MyMagicMock):\n __metaclass__ = SuperMockMetaMeta\n\n\nclass SuperMock(MyMagicMock):\n __metaclass__ = SuperMockMeta\n\n\nclass MockedModule(types.ModuleType):\n def __init__(self, name):\n super(types.ModuleType, self).__init__(name)\n self.__name__ = super.__name__\n self.__file__ = self.__name__.replace('.', '/') + '.py'\n sys.modules[self.__name__] = self\n\n def __getattr__(self, key):\n obj = SuperMock\n setattr(self, key, obj)\n return obj\n\n\n# overwrite imports\norig_import = __import__\ndef import_mock(name, *args, **kwargs):\n try:\n return orig_import(name, *args, **kwargs)\n except ImportError:\n return MockedModule(name)\nimport_patch = mock.patch('__builtin__.__import__', side_effect=import_mock)\n\n\n# public methods\ndef activate():\n mock._is_magic = always_false\n mock.NonCallableMock._mock_add_spec = mock_add_spec_fake\n import_patch.start()\n\n\ndef deactivate():\n import_patch.stop()\n mock.NonCallableMock._mock_add_spec = orig_mock_add_spec\n mock._is_magic = orig_is_magic\n"}}},{"rowIdx":281922,"cells":{"repo_name":{"kind":"string","value":"abadger/ansible-modules-core"},"ref":{"kind":"string","value":"refs/heads/devel"},"path":{"kind":"string","value":"cloud/openstack/os_subnets_facts.py"},"copies":{"kind":"string","value":"4"},"content":{"kind":"string","value":"#!/usr/bin/python\n\n# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.\n#\n# This module is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This software is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this software. If not, see .\n\ntry:\n import shade\n HAS_SHADE = True\nexcept ImportError:\n HAS_SHADE = False\n\nDOCUMENTATION = '''\n---\nmodule: os_subnets_facts\nshort_description: Retrieve facts about one or more OpenStack subnets.\nversion_added: \"2.0\"\nauthor: \"Davide Agnello (@dagnello)\"\ndescription:\n - Retrieve facts about one or more subnets from OpenStack.\nrequirements:\n - \"python >= 2.6\"\n - \"shade\"\noptions:\n subnet:\n description:\n - Name or ID of the subnet\n required: false\n filters:\n description:\n - A dictionary of meta data to use for further filtering. Elements of\n this dictionary may be additional dictionaries.\n required: false\nextends_documentation_fragment: openstack\n'''\n\nEXAMPLES = '''\n- name: Gather facts about previously created subnets\n os_subnets_facts:\n auth:\n auth_url: https://your_api_url.com:9000/v2.0\n username: user\n password: password\n project_name: someproject\n\n- name: Show openstack subnets\n debug:\n var: openstack_subnets\n\n- name: Gather facts about a previously created subnet by name\n os_subnets_facts:\n auth:\n auth_url: https://your_api_url.com:9000/v2.0\n username: user\n password: password\n project_name: someproject\n name: subnet1\n\n- name: Show openstack subnets\n debug:\n var: openstack_subnets\n\n- name: Gather facts about a previously created subnet with filter\n # Note: name and filters parameters are not mutually exclusive\n os_subnets_facts:\n auth:\n auth_url: https://your_api_url.com:9000/v2.0\n username: user\n password: password\n project_name: someproject\n filters:\n tenant_id: 55e2ce24b2a245b09f181bf025724cbe\n\n- name: Show openstack subnets\n debug:\n var: openstack_subnets\n'''\n\nRETURN = '''\nopenstack_subnets:\n description: has all the openstack facts about the subnets\n returned: always, but can be null\n type: complex\n contains:\n id:\n description: Unique UUID.\n returned: success\n type: string\n name:\n description: Name given to the subnet.\n returned: success\n type: string\n network_id:\n description: Network ID this subnet belongs in.\n returned: success\n type: string\n cidr:\n description: Subnet's CIDR.\n returned: success\n type: string\n gateway_ip:\n description: Subnet's gateway ip.\n returned: success\n type: string\n enable_dhcp:\n description: DHCP enable flag for this subnet.\n returned: success\n type: bool\n ip_version:\n description: IP version for this subnet.\n returned: success\n type: int\n tenant_id:\n description: Tenant id associated with this subnet.\n returned: success\n type: string\n dns_nameservers:\n description: DNS name servers for this subnet.\n returned: success\n type: list of strings\n allocation_pools:\n description: Allocation pools associated with this subnet.\n returned: success\n type: list of dicts\n'''\n\ndef main():\n\n argument_spec = openstack_full_argument_spec(\n name=dict(required=False, default=None),\n filters=dict(required=False, type='dict', default=None)\n )\n module = AnsibleModule(argument_spec)\n\n if not HAS_SHADE:\n module.fail_json(msg='shade is required for this module')\n\n try:\n cloud = shade.openstack_cloud(**module.params)\n subnets = cloud.search_subnets(module.params['name'],\n module.params['filters'])\n module.exit_json(changed=False, ansible_facts=dict(\n openstack_subnets=subnets))\n\n except shade.OpenStackCloudException as e:\n module.fail_json(msg=str(e))\n\n# this is magic, see lib/ansible/module_common.py\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.openstack import *\nif __name__ == '__main__':\n main()\n"}}},{"rowIdx":281923,"cells":{"repo_name":{"kind":"string","value":"viki9698/jizhanggroup"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"django/contrib/gis/gdal/tests/test_srs.py"},"copies":{"kind":"string","value":"351"},"content":{"kind":"string","value":"from django.contrib.gis.gdal import SpatialReference, CoordTransform, OGRException, SRSException\nfrom django.utils import unittest\n\n\nclass TestSRS:\n def __init__(self, wkt, **kwargs):\n self.wkt = wkt\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n# Some Spatial Reference examples\nsrlist = (TestSRS('GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]',\n proj='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ',\n epsg=4326, projected=False, geographic=True, local=False,\n lin_name='unknown', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199,\n auth={'GEOGCS' : ('EPSG', '4326'), 'spheroid' : ('EPSG', '7030')},\n attr=(('DATUM', 'WGS_1984'), (('SPHEROID', 1), '6378137'),('primem|authority', 'EPSG'),),\n ),\n TestSRS('PROJCS[\"NAD83 / Texas South Central\",GEOGCS[\"NAD83\",DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"6269\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4269\"]],PROJECTION[\"Lambert_Conformal_Conic_2SP\"],PARAMETER[\"standard_parallel_1\",30.28333333333333],PARAMETER[\"standard_parallel_2\",28.38333333333333],PARAMETER[\"latitude_of_origin\",27.83333333333333],PARAMETER[\"central_meridian\",-99],PARAMETER[\"false_easting\",600000],PARAMETER[\"false_northing\",4000000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AUTHORITY[\"EPSG\",\"32140\"]]',\n proj=None, epsg=32140, projected=True, geographic=False, local=False,\n lin_name='metre', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199,\n auth={'PROJCS' : ('EPSG', '32140'), 'spheroid' : ('EPSG', '7019'), 'unit' : ('EPSG', '9001'),},\n attr=(('DATUM', 'North_American_Datum_1983'),(('SPHEROID', 2), '298.257222101'),('PROJECTION','Lambert_Conformal_Conic_2SP'),),\n ),\n TestSRS('PROJCS[\"NAD_1983_StatePlane_Texas_South_Central_FIPS_4204_Feet\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Lambert_Conformal_Conic_2SP\"],PARAMETER[\"False_Easting\",1968500.0],PARAMETER[\"False_Northing\",13123333.33333333],PARAMETER[\"Central_Meridian\",-99.0],PARAMETER[\"Standard_Parallel_1\",28.38333333333333],PARAMETER[\"Standard_Parallel_2\",30.28333333333334],PARAMETER[\"Latitude_Of_Origin\",27.83333333333333],UNIT[\"Foot_US\",0.3048006096012192]]',\n proj=None, epsg=None, projected=True, geographic=False, local=False,\n lin_name='Foot_US', ang_name='Degree', lin_units=0.3048006096012192, ang_units=0.0174532925199,\n auth={'PROJCS' : (None, None),},\n attr=(('PROJCS|GeOgCs|spheroid', 'GRS_1980'),(('projcs', 9), 'UNIT'), (('projcs', 11), None),),\n ),\n # This is really ESRI format, not WKT -- but the import should work the same\n TestSRS('LOCAL_CS[\"Non-Earth (Meter)\",LOCAL_DATUM[\"Local Datum\",0],UNIT[\"Meter\",1.0],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]',\n esri=True, proj=None, epsg=None, projected=False, geographic=False, local=True,\n lin_name='Meter', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199,\n attr=(('LOCAL_DATUM', 'Local Datum'), ('unit', 'Meter')),\n ),\n )\n\n# Well-Known Names\nwell_known = (TestSRS('GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]', wk='WGS84', name='WGS 84', attrs=(('GEOGCS|AUTHORITY', 1, '4326'), ('SPHEROID', 'WGS 84'))),\n TestSRS('GEOGCS[\"WGS 72\",DATUM[\"WGS_1972\",SPHEROID[\"WGS 72\",6378135,298.26,AUTHORITY[\"EPSG\",\"7043\"]],AUTHORITY[\"EPSG\",\"6322\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4322\"]]', wk='WGS72', name='WGS 72', attrs=(('GEOGCS|AUTHORITY', 1, '4322'), ('SPHEROID', 'WGS 72'))),\n TestSRS('GEOGCS[\"NAD27\",DATUM[\"North_American_Datum_1927\",SPHEROID[\"Clarke 1866\",6378206.4,294.9786982138982,AUTHORITY[\"EPSG\",\"7008\"]],AUTHORITY[\"EPSG\",\"6267\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4267\"]]', wk='NAD27', name='NAD27', attrs=(('GEOGCS|AUTHORITY', 1, '4267'), ('SPHEROID', 'Clarke 1866'))),\n TestSRS('GEOGCS[\"NAD83\",DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"6269\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4269\"]]', wk='NAD83', name='NAD83', attrs=(('GEOGCS|AUTHORITY', 1, '4269'), ('SPHEROID', 'GRS 1980'))),\n TestSRS('PROJCS[\"NZGD49 / Karamea Circuit\",GEOGCS[\"NZGD49\",DATUM[\"New_Zealand_Geodetic_Datum_1949\",SPHEROID[\"International 1924\",6378388,297,AUTHORITY[\"EPSG\",\"7022\"]],TOWGS84[59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993],AUTHORITY[\"EPSG\",\"6272\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4272\"]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",-41.28991152777778],PARAMETER[\"central_meridian\",172.1090281944444],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",300000],PARAMETER[\"false_northing\",700000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AUTHORITY[\"EPSG\",\"27216\"]]', wk='EPSG:27216', name='NZGD49 / Karamea Circuit', attrs=(('PROJECTION','Transverse_Mercator'), ('SPHEROID', 'International 1924'))),\n )\n\nbad_srlist = ('Foobar', 'OOJCS[\"NAD83 / Texas South Central\",GEOGCS[\"NAD83\",DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"6269\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4269\"]],PROJECTION[\"Lambert_Conformal_Conic_2SP\"],PARAMETER[\"standard_parallel_1\",30.28333333333333],PARAMETER[\"standard_parallel_2\",28.38333333333333],PARAMETER[\"latitude_of_origin\",27.83333333333333],PARAMETER[\"central_meridian\",-99],PARAMETER[\"false_easting\",600000],PARAMETER[\"false_northing\",4000000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AUTHORITY[\"EPSG\",\"32140\"]]',)\n\nclass SpatialRefTest(unittest.TestCase):\n\n def test01_wkt(self):\n \"Testing initialization on valid OGC WKT.\"\n for s in srlist:\n srs = SpatialReference(s.wkt)\n\n def test02_bad_wkt(self):\n \"Testing initialization on invalid WKT.\"\n for bad in bad_srlist:\n try:\n srs = SpatialReference(bad)\n srs.validate()\n except (SRSException, OGRException):\n pass\n else:\n self.fail('Should not have initialized on bad WKT \"%s\"!')\n\n def test03_get_wkt(self):\n \"Testing getting the WKT.\"\n for s in srlist:\n srs = SpatialReference(s.wkt)\n self.assertEqual(s.wkt, srs.wkt)\n\n def test04_proj(self):\n \"Test PROJ.4 import and export.\"\n for s in srlist:\n if s.proj:\n srs1 = SpatialReference(s.wkt)\n srs2 = SpatialReference(s.proj)\n self.assertEqual(srs1.proj, srs2.proj)\n\n def test05_epsg(self):\n \"Test EPSG import.\"\n for s in srlist:\n if s.epsg:\n srs1 = SpatialReference(s.wkt)\n srs2 = SpatialReference(s.epsg)\n srs3 = SpatialReference(str(s.epsg))\n srs4 = SpatialReference('EPSG:%d' % s.epsg)\n for srs in (srs1, srs2, srs3, srs4):\n for attr, expected in s.attr:\n self.assertEqual(expected, srs[attr])\n\n def test07_boolean_props(self):\n \"Testing the boolean properties.\"\n for s in srlist:\n srs = SpatialReference(s.wkt)\n self.assertEqual(s.projected, srs.projected)\n self.assertEqual(s.geographic, srs.geographic)\n\n def test08_angular_linear(self):\n \"Testing the linear and angular units routines.\"\n for s in srlist:\n srs = SpatialReference(s.wkt)\n self.assertEqual(s.ang_name, srs.angular_name)\n self.assertEqual(s.lin_name, srs.linear_name)\n self.assertAlmostEqual(s.ang_units, srs.angular_units, 9)\n self.assertAlmostEqual(s.lin_units, srs.linear_units, 9)\n\n def test09_authority(self):\n \"Testing the authority name & code routines.\"\n for s in srlist:\n if hasattr(s, 'auth'):\n srs = SpatialReference(s.wkt)\n for target, tup in s.auth.items():\n self.assertEqual(tup[0], srs.auth_name(target))\n self.assertEqual(tup[1], srs.auth_code(target))\n\n def test10_attributes(self):\n \"Testing the attribute retrieval routines.\"\n for s in srlist:\n srs = SpatialReference(s.wkt)\n for tup in s.attr:\n att = tup[0] # Attribute to test\n exp = tup[1] # Expected result\n self.assertEqual(exp, srs[att])\n\n def test11_wellknown(self):\n \"Testing Well Known Names of Spatial References.\"\n for s in well_known:\n srs = SpatialReference(s.wk)\n self.assertEqual(s.name, srs.name)\n for tup in s.attrs:\n if len(tup) == 2:\n key = tup[0]\n exp = tup[1]\n elif len(tup) == 3:\n key = tup[:2]\n exp = tup[2]\n self.assertEqual(srs[key], exp)\n\n def test12_coordtransform(self):\n \"Testing initialization of a CoordTransform.\"\n target = SpatialReference('WGS84')\n for s in srlist:\n if s.proj:\n ct = CoordTransform(SpatialReference(s.wkt), target)\n\n def test13_attr_value(self):\n \"Testing the attr_value() method.\"\n s1 = SpatialReference('WGS84')\n self.assertRaises(TypeError, s1.__getitem__, 0)\n self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo'))\n self.assertEqual('WGS 84', s1['GEOGCS'])\n self.assertEqual('WGS_1984', s1['DATUM'])\n self.assertEqual('EPSG', s1['AUTHORITY'])\n self.assertEqual(4326, int(s1['AUTHORITY', 1]))\n self.assertEqual(None, s1['FOOBAR'])\n\ndef suite():\n s = unittest.TestSuite()\n s.addTest(unittest.makeSuite(SpatialRefTest))\n return s\n\ndef run(verbosity=2):\n unittest.TextTestRunner(verbosity=verbosity).run(suite())\n"}}},{"rowIdx":281924,"cells":{"repo_name":{"kind":"string","value":"eahneahn/free"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"lib/python2.7/site-packages/pygments/scanner.py"},"copies":{"kind":"string","value":"365"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"\n pygments.scanner\n ~~~~~~~~~~~~~~~~\n\n This library implements a regex based scanner. Some languages\n like Pascal are easy to parse but have some keywords that\n depend on the context. Because of this it's impossible to lex\n that just by using a regular expression lexer like the\n `RegexLexer`.\n\n Have a look at the `DelphiLexer` to get an idea of how to use\n this scanner.\n\n :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\nimport re\n\n\nclass EndOfText(RuntimeError):\n \"\"\"\n Raise if end of text is reached and the user\n tried to call a match function.\n \"\"\"\n\n\nclass Scanner(object):\n \"\"\"\n Simple scanner\n\n All method patterns are regular expression strings (not\n compiled expressions!)\n \"\"\"\n\n def __init__(self, text, flags=0):\n \"\"\"\n :param text: The text which should be scanned\n :param flags: default regular expression flags\n \"\"\"\n self.data = text\n self.data_length = len(text)\n self.start_pos = 0\n self.pos = 0\n self.flags = flags\n self.last = None\n self.match = None\n self._re_cache = {}\n\n def eos(self):\n \"\"\"`True` if the scanner reached the end of text.\"\"\"\n return self.pos >= self.data_length\n eos = property(eos, eos.__doc__)\n\n def check(self, pattern):\n \"\"\"\n Apply `pattern` on the current position and return\n the match object. (Doesn't touch pos). Use this for\n lookahead.\n \"\"\"\n if self.eos:\n raise EndOfText()\n if pattern not in self._re_cache:\n self._re_cache[pattern] = re.compile(pattern, self.flags)\n return self._re_cache[pattern].match(self.data, self.pos)\n\n def test(self, pattern):\n \"\"\"Apply a pattern on the current position and check\n if it patches. Doesn't touch pos.\"\"\"\n return self.check(pattern) is not None\n\n def scan(self, pattern):\n \"\"\"\n Scan the text for the given pattern and update pos/match\n and related fields. The return value is a boolen that\n indicates if the pattern matched. The matched value is\n stored on the instance as ``match``, the last value is\n stored as ``last``. ``start_pos`` is the position of the\n pointer before the pattern was matched, ``pos`` is the\n end position.\n \"\"\"\n if self.eos:\n raise EndOfText()\n if pattern not in self._re_cache:\n self._re_cache[pattern] = re.compile(pattern, self.flags)\n self.last = self.match\n m = self._re_cache[pattern].match(self.data, self.pos)\n if m is None:\n return False\n self.start_pos = m.start()\n self.pos = m.end()\n self.match = m.group()\n return True\n\n def get_char(self):\n \"\"\"Scan exactly one char.\"\"\"\n self.scan('.')\n\n def __repr__(self):\n return '<%s %d/%d>' % (\n self.__class__.__name__,\n self.pos,\n self.data_length\n )\n"}}},{"rowIdx":281925,"cells":{"repo_name":{"kind":"string","value":"Philippe12/external_chromium_org"},"ref":{"kind":"string","value":"refs/heads/kitkat"},"path":{"kind":"string","value":"third_party/protobuf/__init__.py"},"copies":{"kind":"string","value":"45382"},"content":{"kind":"string","value":"\n\n"}}},{"rowIdx":281926,"cells":{"repo_name":{"kind":"string","value":"Hikari-no-Tenshi/android_external_skia"},"ref":{"kind":"string","value":"refs/heads/10.0"},"path":{"kind":"string","value":"infra/bots/assets/opencl_ocl_icd_linux/download.py"},"copies":{"kind":"string","value":"264"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#\n# Copyright 2017 Google Inc.\n#\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\n\"\"\"Download the current version of the asset.\"\"\"\n\n\nimport common\n\n\nif __name__ == '__main__':\n common.run('download')\n"}}},{"rowIdx":281927,"cells":{"repo_name":{"kind":"string","value":"jacquev6/LowVoltage"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"LowVoltage/compounds/tests/__init__.py"},"copies":{"kind":"string","value":"2"},"content":{"kind":"string","value":"# coding: utf8\n\n# Copyright 2014-2015 Vincent Jacques \n"}}},{"rowIdx":281928,"cells":{"repo_name":{"kind":"string","value":"HSU-MilitaryLogisticsClub/pysatcatcher"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"antenna.py"},"copies":{"kind":"string","value":"2"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\nimport unittest\nimport serial\nimport threading\nimport time\n\nclass RAC805:\n def __init__(self):\n #self._ser = serial.serial('/dev/tty',9600)\n pass\n def connect(self,port):\n self._ser = serial.Serial(port, 9600, timeout=0)\n\n def moveazel(self,az,el):\n if(el>=0.0):\n command = \"AZ\"+str(az)+\" EL\"+str(el)+\"\\r\"\n self._ser.write(command)\n return True\n\n def stop(self):\n command = \"\\r\"\n self._ser.write(command+\"\\r\")\n return True\n\n def recieve(self):\n result=\"\"\n while not((\">>\" in result) or (\"\" == result)):\n #while(False):\n print('recieve')\n time.sleep(0.0001)\n result=self._ser.readline()\n print(result)\n return True\n\n def close(self):\n self._ser.close()\n return True\n\nclass Antenna(object):\n def __init__(self,rotatormodel):\n if rotatormodel == \"RAC805\":\n self._radio = RAC805()\n def connect(self,port):\n self._radio.connect(port)\n def moveazel(self,az,el):\n return self._radio.moveazel(az,el)\n def stop(self):\n return self._radio.stop()\n \n def recieve(self):\n self._radio.recieve()\n #t=threading.Thread(target=self._radio.recieve())\n #t.setDaemon(True)\n #t.start()\n #print \"threadstart\"\n def close(self):\n return self._radio.close()\n\n"}}},{"rowIdx":281929,"cells":{"repo_name":{"kind":"string","value":"johnbren85/GrowChinook"},"ref":{"kind":"string","value":"refs/heads/master"},"path":{"kind":"string","value":"fisheries/TestSens.py"},"copies":{"kind":"string","value":"2"},"content":{"kind":"string","value":"#!/usr/bin/python\n\nimport os\nimport glob\nimport cgi\nimport PrintPages as pt\n\naddress = cgi.escape(os.environ[\"REMOTE_ADDR\"])\nscript = \"Sensitivity Form\"\npt.write_log_entry(script, address)\npt.print_header('GrowChinook', 'Sens')\npt.print_full_form(None, None, 'Sens_in', 'RunModelSens.py')\nextension = 'csv'\nos.chdir('uploads')\nresult = [i for i in glob.glob('*.csv')]\n\nprint('''\n{}\n\n\n'''.format(result))\nprint ('