repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringlengths
1
5
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
ColOfAbRiX/ansible
lib/ansible/modules/database/vertica/vertica_facts.py
28
9387
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = """ --- module: vertica_facts version_added: '2.0' short_description: Gathers Vertica database facts. description: - Gathers Vertica database facts. options: cluster: description: - Name of the cluster running the schema. required: false default: localhost port: description: Database port to connect to. required: false default: 5433 db: description: - Name of the database running the schema. required: false default: null login_user: description: - The username used to authenticate with. required: false default: dbadmin login_password: description: - The password used to authenticate with. required: false default: null notes: - The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host. - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed on the host and properly configured. - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica) section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini). requirements: [ 'unixODBC', 'pyodbc' ] author: "Dariusz Owczarek (@dareko)" """ EXAMPLES = """ - name: gathering vertica facts vertica_facts: db=db_name """ try: import pyodbc except ImportError: pyodbc_found = False else: pyodbc_found = True from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception class NotSupportedError(Exception): pass # module specific functions def get_schema_facts(cursor, schema=''): facts = {} cursor.execute(""" select schema_name, schema_owner, create_time from schemata where not is_system_schema and schema_name not in ('public') and (? = '' or schema_name ilike ?) """, schema, schema) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.schema_name.lower()] = { 'name': row.schema_name, 'owner': row.schema_owner, 'create_time': str(row.create_time), 'usage_roles': [], 'create_roles': []} cursor.execute(""" select g.object_name as schema_name, r.name as role_name, lower(g.privileges_description) privileges_description from roles r join grants g on g.grantee = r.name and g.object_type='SCHEMA' and g.privileges_description like '%USAGE%' and g.grantee not in ('public', 'dbadmin') and (? = '' or g.object_name ilike ?) """, schema, schema) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: schema_key = row.schema_name.lower() if 'create' in row.privileges_description: facts[schema_key]['create_roles'].append(row.role_name) else: facts[schema_key]['usage_roles'].append(row.role_name) return facts def get_user_facts(cursor, user=''): facts = {} cursor.execute(""" select u.user_name, u.is_locked, u.lock_time, p.password, p.acctexpired as is_expired, u.profile_name, u.resource_pool, u.all_roles, u.default_roles from users u join password_auditor p on p.user_id = u.user_id where not u.is_super_user and (? = '' or u.user_name ilike ?) """, user, user) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: user_key = row.user_name.lower() facts[user_key] = { 'name': row.user_name, 'locked': str(row.is_locked), 'password': row.password, 'expired': str(row.is_expired), 'profile': row.profile_name, 'resource_pool': row.resource_pool, 'roles': [], 'default_roles': []} if row.is_locked: facts[user_key]['locked_time'] = str(row.lock_time) if row.all_roles: facts[user_key]['roles'] = row.all_roles.replace(' ', '').split(',') if row.default_roles: facts[user_key]['default_roles'] = row.default_roles.replace(' ', '').split(',') return facts def get_role_facts(cursor, role=''): facts = {} cursor.execute(""" select r.name, r.assigned_roles from roles r where (? = '' or r.name ilike ?) """, role, role) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: role_key = row.name.lower() facts[role_key] = { 'name': row.name, 'assigned_roles': []} if row.assigned_roles: facts[role_key]['assigned_roles'] = row.assigned_roles.replace(' ', '').split(',') return facts def get_configuration_facts(cursor, parameter=''): facts = {} cursor.execute(""" select c.parameter_name, c.current_value, c.default_value from configuration_parameters c where c.node_name = 'ALL' and (? = '' or c.parameter_name ilike ?) """, parameter, parameter) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.parameter_name.lower()] = { 'parameter_name': row.parameter_name, 'current_value': row.current_value, 'default_value': row.default_value} return facts def get_node_facts(cursor, schema=''): facts = {} cursor.execute(""" select node_name, node_address, export_address, node_state, node_type, catalog_path from nodes """) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.node_address] = { 'node_name': row.node_name, 'export_address': row.export_address, 'node_state': row.node_state, 'node_type': row.node_type, 'catalog_path': row.catalog_path} return facts # module logic def main(): module = AnsibleModule( argument_spec=dict( cluster=dict(default='localhost'), port=dict(default='5433'), db=dict(default=None), login_user=dict(default='dbadmin'), login_password=dict(default=None), ), supports_check_mode = True) if not pyodbc_found: module.fail_json(msg="The python pyodbc module is required.") db = '' if module.params['db']: db = module.params['db'] try: dsn = ( "Driver=Vertica;" "Server=%s;" "Port=%s;" "Database=%s;" "User=%s;" "Password=%s;" "ConnectionLoadBalance=%s" ) % (module.params['cluster'], module.params['port'], db, module.params['login_user'], module.params['login_password'], 'true') db_conn = pyodbc.connect(dsn, autocommit=True) cursor = db_conn.cursor() except Exception: e = get_exception() module.fail_json(msg="Unable to connect to database: %s." % str(e)) try: schema_facts = get_schema_facts(cursor) user_facts = get_user_facts(cursor) role_facts = get_role_facts(cursor) configuration_facts = get_configuration_facts(cursor) node_facts = get_node_facts(cursor) module.exit_json(changed=False, ansible_facts={'vertica_schemas': schema_facts, 'vertica_users': user_facts, 'vertica_roles': role_facts, 'vertica_configuration': configuration_facts, 'vertica_nodes': node_facts}) except NotSupportedError: e = get_exception() module.fail_json(msg=str(e)) except SystemExit: # avoid catching this on python 2.4 raise except Exception: e = get_exception() module.fail_json(msg=e) if __name__ == '__main__': main()
gpl-3.0
suninsky/ReceiptOCR
Python/server/lib/python2.7/site-packages/markupsafe/__init__.py
144
10697
# -*- coding: utf-8 -*- """ markupsafe ~~~~~~~~~~ Implements a Markup string. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import re import string from collections import Mapping from markupsafe._compat import text_type, string_types, int_types, \ unichr, iteritems, PY2 __version__ = "1.0" __all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent'] _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)') _entity_re = re.compile(r'&([^& ;]+);') class Markup(text_type): r"""Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the `__html__` interface a couple of frameworks and web applications use. :class:`Markup` is a direct subclass of `unicode` and provides all the methods of `unicode` just that it escapes arguments passed and always returns `Markup`. The `escape` function returns markup objects so that double escaping can't happen. The constructor of the :class:`Markup` class can be used for three different things: When passed an unicode object it's assumed to be safe, when passed an object with an HTML representation (has an `__html__` method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe: >>> Markup("Hello <em>World</em>!") Markup(u'Hello <em>World</em>!') >>> class Foo(object): ... def __html__(self): ... return '<a href="#">foo</a>' ... >>> Markup(Foo()) Markup(u'<a href="#">foo</a>') If you want object passed being always treated as unsafe you can use the :meth:`escape` classmethod to create a :class:`Markup` object: >>> Markup.escape("Hello <em>World</em>!") Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!') Operations on a markup string are markup aware which means that all arguments are passed through the :func:`escape` function: >>> em = Markup("<em>%s</em>") >>> em % "foo & bar" Markup(u'<em>foo &amp; bar</em>') >>> strong = Markup("<strong>%(text)s</strong>") >>> strong % {'text': '<blink>hacker here</blink>'} Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup(u'<em>Hello</em> &lt;foo&gt;') """ __slots__ = () def __new__(cls, base=u'', encoding=None, errors='strict'): if hasattr(base, '__html__'): base = base.__html__() if encoding is None: return text_type.__new__(cls, base) return text_type.__new__(cls, base, encoding, errors) def __html__(self): return self def __add__(self, other): if isinstance(other, string_types) or hasattr(other, '__html__'): return self.__class__(super(Markup, self).__add__(self.escape(other))) return NotImplemented def __radd__(self, other): if hasattr(other, '__html__') or isinstance(other, string_types): return self.escape(other).__add__(self) return NotImplemented def __mul__(self, num): if isinstance(num, int_types): return self.__class__(text_type.__mul__(self, num)) return NotImplemented __rmul__ = __mul__ def __mod__(self, arg): if isinstance(arg, tuple): arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg) else: arg = _MarkupEscapeHelper(arg, self.escape) return self.__class__(text_type.__mod__(self, arg)) def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, text_type.__repr__(self) ) def join(self, seq): return self.__class__(text_type.join(self, map(self.escape, seq))) join.__doc__ = text_type.join.__doc__ def split(self, *args, **kwargs): return list(map(self.__class__, text_type.split(self, *args, **kwargs))) split.__doc__ = text_type.split.__doc__ def rsplit(self, *args, **kwargs): return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs))) rsplit.__doc__ = text_type.rsplit.__doc__ def splitlines(self, *args, **kwargs): return list(map(self.__class__, text_type.splitlines( self, *args, **kwargs))) splitlines.__doc__ = text_type.splitlines.__doc__ def unescape(self): r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if name in HTML_ENTITIES: return unichr(HTML_ENTITIES[name]) try: if name[:2] in ('#x', '#X'): return unichr(int(name[2:], 16)) elif name.startswith('#'): return unichr(int(name[1:])) except ValueError: pass # Don't modify unexpected input. return m.group() return _entity_re.sub(handle_match, text_type(self)) def striptags(self): r"""Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '.join(_striptags_re.sub('', self).split()) return Markup(stripped).unescape() @classmethod def escape(cls, s): """Escape the string. Works like :func:`escape` with the difference that for subclasses of :class:`Markup` this function would return the correct subclass. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv def make_simple_escaping_wrapper(name): orig = getattr(text_type, name) def func(self, *args, **kwargs): args = _escape_argspec(list(args), enumerate(args), self.escape) _escape_argspec(kwargs, iteritems(kwargs), self.escape) return self.__class__(orig(self, *args, **kwargs)) func.__name__ = orig.__name__ func.__doc__ = orig.__doc__ return func for method in '__getitem__', 'capitalize', \ 'title', 'lower', 'upper', 'replace', 'ljust', \ 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \ 'translate', 'expandtabs', 'swapcase', 'zfill': locals()[method] = make_simple_escaping_wrapper(method) # new in python 2.5 if hasattr(text_type, 'partition'): def partition(self, sep): return tuple(map(self.__class__, text_type.partition(self, self.escape(sep)))) def rpartition(self, sep): return tuple(map(self.__class__, text_type.rpartition(self, self.escape(sep)))) # new in python 2.6 if hasattr(text_type, 'format'): def format(*args, **kwargs): self, args = args[0], args[1:] formatter = EscapeFormatter(self.escape) kwargs = _MagicFormatMapping(args, kwargs) return self.__class__(formatter.vformat(self, args, kwargs)) def __html_format__(self, format_spec): if format_spec: raise ValueError('Unsupported format specification ' 'for Markup.') return self # not in python 3 if hasattr(text_type, '__getslice__'): __getslice__ = make_simple_escaping_wrapper('__getslice__') del method, make_simple_escaping_wrapper class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args self._kwargs = kwargs self._last_index = 0 def __getitem__(self, key): if key == '': idx = self._last_index self._last_index += 1 try: return self._args[idx] except LookupError: pass key = str(idx) return self._kwargs[key] def __iter__(self): return iter(self._kwargs) def __len__(self): return len(self._kwargs) if hasattr(text_type, 'format'): class EscapeFormatter(string.Formatter): def __init__(self, escape): self.escape = escape def format_field(self, value, format_spec): if hasattr(value, '__html_format__'): rv = value.__html_format__(format_spec) elif hasattr(value, '__html__'): if format_spec: raise ValueError('No format specification allowed ' 'when formatting an object with ' 'its __html__ method.') rv = value.__html__() else: # We need to make sure the format spec is unicode here as # otherwise the wrong callback methods are invoked. For # instance a byte string there would invoke __str__ and # not __unicode__. rv = string.Formatter.format_field( self, value, text_type(format_spec)) return text_type(self.escape(rv)) def _escape_argspec(obj, iterable, escape): """Helper for various string-wrapped functions.""" for key, value in iterable: if hasattr(value, '__html__') or isinstance(value, string_types): obj[key] = escape(value) return obj class _MarkupEscapeHelper(object): """Helper for Markup.__mod__""" def __init__(self, obj, escape): self.obj = obj self.escape = escape __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape) __unicode__ = __str__ = lambda s: text_type(s.escape(s.obj)) __repr__ = lambda s: str(s.escape(repr(s.obj))) __int__ = lambda s: int(s.obj) __float__ = lambda s: float(s.obj) # we have to import it down here as the speedups and native # modules imports the markup type which is define above. try: from markupsafe._speedups import escape, escape_silent, soft_unicode except ImportError: from markupsafe._native import escape, escape_silent, soft_unicode if not PY2: soft_str = soft_unicode __all__.append('soft_str')
mit
ahmadio/edx-platform
lms/djangoapps/mobile_api/social_facebook/groups/views.py
86
4938
""" Views for groups info API """ from rest_framework import generics, status, mixins from rest_framework.response import Response from django.conf import settings import facebook from ...utils import mobile_view from . import serializers @mobile_view() class Groups(generics.CreateAPIView, mixins.DestroyModelMixin): """ **Use Case** An API to Create or Delete course groups. Note: The Delete is not invoked from the current version of the app and is used only for testing with facebook dependencies. **Creation Example request**: POST /api/mobile/v0.5/social/facebook/groups/ Parameters: name : string, description : string, privacy : open/closed **Creation Response Values** {"id": group_id} **Deletion Example request**: DELETE /api/mobile/v0.5/social/facebook/groups/<group_id> **Deletion Response Values** {"success" : "true"} """ serializer_class = serializers.GroupSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA, files=request.FILES) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) try: app_groups_response = facebook_graph_api().request( settings.FACEBOOK_API_VERSION + '/' + settings.FACEBOOK_APP_ID + "/groups", post_args=request.POST.dict() ) return Response(app_groups_response) except facebook.GraphAPIError, ex: return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Deletes the course group. """ try: return Response( facebook_graph_api().request( settings.FACEBOOK_API_VERSION + '/' + settings.FACEBOOK_APP_ID + "/groups/" + kwargs['group_id'], post_args={'method': 'delete'} ) ) except facebook.GraphAPIError, ex: return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST) @mobile_view() class GroupsMembers(generics.CreateAPIView, mixins.DestroyModelMixin): """ **Use Case** An API to Invite and Remove members to a group Note: The Remove is not invoked from the current version of the app and is used only for testing with facebook dependencies. **Invite Example request**: POST /api/mobile/v0.5/social/facebook/groups/<group_id>/member/ Parameters: members : int,int,int... **Invite Response Values** {"member_id" : success/error_message} A response with each member_id and whether or not the member was added successfully. If the member was not added successfully the Facebook error message is provided. **Remove Example request**: DELETE /api/mobile/v0.5/social/facebook/groups/<group_id>/member/<member_id> **Remove Response Values** {"success" : "true"} """ serializer_class = serializers.GroupsMembersSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA, files=request.FILES) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) graph = facebook_graph_api() url = settings.FACEBOOK_API_VERSION + '/' + kwargs['group_id'] + "/members" member_ids = serializer.object['member_ids'].split(',') response = {} for member_id in member_ids: try: if 'success' in graph.request(url, post_args={'member': member_id}): response[member_id] = 'success' except facebook.GraphAPIError, ex: response[member_id] = ex.result['error']['message'] return Response(response, status=status.HTTP_200_OK) def delete(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Deletes the member from the course group. """ try: return Response( facebook_graph_api().request( settings.FACEBOOK_API_VERSION + '/' + kwargs['group_id'] + "/members", post_args={'method': 'delete', 'member': kwargs['member_id']} ) ) except facebook.GraphAPIError, ex: return Response({'error': ex.result['error']['message']}, status=status.HTTP_400_BAD_REQUEST) def facebook_graph_api(): """ Returns the result from calling Facebook's Graph API with the app's access token. """ return facebook.GraphAPI(facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET))
agpl-3.0
johnsonc/OTM2
opentreemap/treemap/tests/ui/uitest_registration_views.py
12
2858
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from time import sleep from django.core.urlresolvers import reverse from django.core import mail from registration.models import RegistrationProfile from treemap.tests.ui import UITestCase from treemap.tests import make_user, create_mock_system_user class LoginLogoutTest(UITestCase): def setUp(self): create_mock_system_user() super(LoginLogoutTest, self).setUp() self.user = make_user(username='username', password='password') self.profile = RegistrationProfile.objects.create_profile(self.user) def test_invalid_login(self): self.browse_to_url(reverse('auth_login')) login_url = self.driver.current_url self.process_login_form( self.user.username, 'passwordinvalid') # There should be an error list with at least one element self.wait_until_present('.errorlist li') # We should be on the same page self.assertEqual(login_url, self.driver.current_url) def test_valid_login(self): self.browse_to_url(reverse('auth_login')) login_url = self.driver.current_url self.process_login_form(self.user.username, 'password') email_element = self.wait_until_present( '[data-field="user.email"][data-class="display"]') # We should not be on the same page self.assertNotEqual(login_url, self.driver.current_url) # We should expect our username in the url self.assertIn(self.user.username, self.driver.current_url) value = email_element.get_attribute('data-value') self.assertEqual(self.user.email, value) sleep(1) # prevent hang class ForgotUsernameTest(UITestCase): def setUp(self): create_mock_system_user() super(ForgotUsernameTest, self).setUp() self.user = make_user(username='username', password='password') def tearDown(self): mail.outbox = [] super(ForgotUsernameTest, self).tearDown() def test_can_get_to_page(self): self.browse_to_url(reverse('auth_login')) forgot_username_url = reverse('forgot_username') link = self.find_anchor_by_url(forgot_username_url) link.click() self.wait_until_present('input[name="email"]') self.assertEqual(self.live_server_url + forgot_username_url, self.driver.current_url) def test_can_retrieve_username(self): self.browse_to_url(reverse('forgot_username')) email_elem = self.driver.find_element_by_name('email') email_elem.send_keys(self.user.email) self.click('form input[type="submit"]') self.wait_until_text_present('Email Sent') self.assertEqual(len(mail.outbox), 1)
gpl-3.0
catb0t/simpleforth
forth.py
1
7114
#!/usr/bin/env python3 import builtins from pmlr import pmlr debug_write = pmlr.util.debug_write ERR_DATA = { ZeroDivisionError: {"IS_FATAL": False, "TYPE": "DEBUG"}, LookupError: {"IS_FATAL": False, "TYPE": "RANGE"}, IndexError: {"IS_FATAL": False, "TYPE": "RANGE"}, TypeError: {"IS_FATAL": True, "TYPE": "ERROR"}, NameError: {"IS_FATAL": True, "TYPE": "FATAL"}, ValueError: {"IS_FATAL": True, "TYPE": "FATAL"}, AssertionError: {"IS_FATAL": True, "TYPE": "FATAL"}, } def is_none(*args): return None in args def cmp_all(val, *tests): return builtins.all([val == test for test in tests]) def all(*args): return builtins.all(args) def any(*args): return builtins.any(args) class Forth(object): def __init__(self): (self._stk, self._lopstk, self._retstk, self._sftstk) = [Stack() for i in range(4)] self.dict = { "": () } self.funcdict = { "": () } def run(self, prog, sandbox=False): pass def define(self, name, defn): defn = " ".join(defn).strip() try: self.run(defn, sandbox=True) except MalformedExpressionException as err: debug_write(err.msg, level=err.level) return None # {"name": "None", "desc": "debug"} class OpCore(): """bare stack operator mixin""" def peek(self, from_idx=0, to_idx=-1): return self._stk[:] def pop(self, count=1, idx=-1): """( x -- ) take something and return it""" if count > len(self._stk): pmlr.util.debug_write( "popping more items than exist on stack!\n", level="WARN" ) # http://stackoverflow.com/a/34633242/4532996 # from testing it seems that pop(x) is slower than pop() # pop(-1) doesn't seem to be optimised to pop(), # so avoid it if possible x = [] if -1 == idx: for i in range(count): try: x.append(self._stk.pop()) except LookupError as err: self.err(err, errtype="RANGE") break else: for i in range(count): try: x.append(self._stk.pop(idx)) except LookupError as err: self.err(err, errtype="RANGE") break return x[0] if len(x) == 1 else list(reversed(x)) def push(self, *args, idx=-1): """( -- x ... ) put somethings at idx""" if idx == -1: self._stk.extend(args) else: if idx < 0: for arg in args: self._stk.insert(idx, arg) idx -= 1 else: for arg in args: self._stk.insert(idx, arg) idx += 1 def clear(self): """( z y x -- ) clear the stack completely""" y = self._stk.copy() self._stk.clear() return y def pick(self, idx=-3, drop=False): """( x -- x ) pick somethings from a range of indicies""" s = self._stk[idx] if drop: self._stk[idx] = [] return s def drop(self, count=1, idx=-1): """( x -- ) drop items without returning (cheaper pop)""" [self.pop(idx=idx) for i in range(count)] def dup(self, count=1, from_idx=-1): """( y -- y y ) duplicate something and push""" try: y = self._stk[from_idx] * count except LookupError as err: self.err(err, errtype="RANGE") self.push(*y, idx=idx) def dupn(self, count=2, idx=-1): """( x y -- x y x y ) dup count items from an idx""" y = [] for i in range(count): try: y.append(self._stk[idx - i]) except LookupError as err: if idx == 1: continue else: self.err(err, errtype="RANGE") return None self.push(*y, idx=idx) def swap(self, idx=-1): """( x y -- y x ) swap two things at an index""" self.push(*reversed([self.pop(idx=idx) for i in range(2)]), idx=idx) def rot(self, idx=-1, count=3): """( w x y z -- x y z w ) rotate things left, at an index""" l = [self.pop(idx=idx) for i in range(count)] l.insert(0, l.pop()) self.push(*l, idx=idx) def urot(self, idx=-1, count=3): """( w x y z -- z w x y ) rotate things right, at an index""" l = [self.pop(idx=idx) for i in range(count)] l.append(l.pop(0)) self.push(*l, idx=idx) class OpLogik(): pass class OpString(): pass class Stack(OpCore, OpLogik, OpString): "the mixin mixer of the above mixins" def __init__(self): self._stk = [] def err(self, err, errtype=None, framelevel=3): if errtype is None: errtype = ERR_DATA.get(err.__class__, {"TYPE": "FATAL"})["TYPE"] errtype = errtype.upper() debug_write(*err.args, "\n", level=errtype, framelevel=framelevel) if ERR_DATA.get(err.__class__, {"IS_FATAL": True})["IS_FATAL"]: raise err.__class__( pmlr.util.debug_fmt( errtype, framelevel=framelevel ) + " " + "".join([str(i) for i in err.args]) ) def __repr__(self): return "<{}> {}".format(len(self._stk), _fmt_collection(self._stk)) is_collection = lambda c: any(issubclass(c.__class__, (list, tuple, dict, set)), isinstance(c, (list, tuple, dict, set))) def _fmt_collection(col): "format a collection literal" t_super = col.__class__ try: t_mro = t_super.mro() t_meta = t_mro[1] if cmp_all(type(t_meta), object, type, type(object), type(type)): raise TypeError except (NameError, TypeError, IndexError, AttributeError) as err: if cmp_all(err.__class__, NameError, AttributeError) and not hasattr(t_super, "mro"): raise else: raise TypeError("need object instance but found {} (class constructor, type or object object)".format(type(col))) is_iter = hasattr(col, "__iter__") is_meta_iter = hasattr(col.__class__, "__iter__") if not any(is_iter, is_meta_iter): raise TypeError("({}) {} object is not iterable".format(col, col.__class__)) orderedary = (list, tuple, set) if any(isinstance(col, orderedary), issubclass(col.__class__, orderedary)): return "[ {} ]".format(" ".join(repr(i) if not is_collection(i) else _fmt_collection(i) for i in col)) elif any(isinstance(col, dict), issubclass(col, dict)): return " ".join("{}:{}".format(str(key), str(value)) for key, value in col.items()) else: raise TypeError("don't know how to format that container") return locals() if __name__ == "__main__": from tests import main as test_main test_main()
gpl-3.0
skidzen/grit-i18n
grit/tool/build.py
2
19603
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''The 'grit build' tool along with integration for this tool with the SCons build system. ''' import filecmp import getopt import os import shutil import sys from grit import grd_reader from grit import util from grit.tool import interface from grit import shortcuts # It would be cleaner to have each module register itself, but that would # require importing all of them on every run of GRIT. '''Map from <output> node types to modules under grit.format.''' _format_modules = { 'android': 'android_xml', 'c_format': 'c_format', 'chrome_messages_json': 'chrome_messages_json', 'data_package': 'data_pack', 'js_map_format': 'js_map_format', 'rc_all': 'rc', 'rc_translateable': 'rc', 'rc_nontranslateable': 'rc', 'rc_header': 'rc_header', 'resource_map_header': 'resource_map', 'resource_map_source': 'resource_map', 'resource_file_map_source': 'resource_map', } _format_modules.update( (type, 'policy_templates.template_formatter') for type in [ 'adm', 'admx', 'adml', 'reg', 'doc', 'json', 'plist', 'plist_strings', 'ios_plist', 'android_policy' ]) def GetFormatter(type): modulename = 'grit.format.' + _format_modules[type] __import__(modulename) module = sys.modules[modulename] try: return module.Format except AttributeError: return module.GetFormatter(type) class RcBuilder(interface.Tool): '''A tool that builds RC files and resource header files for compilation. Usage: grit build [-o OUTPUTDIR] [-D NAME[=VAL]]* All output options for this tool are specified in the input file (see 'grit help' for details on how to specify the input file - it is a global option). Options: -a FILE Assert that the given file is an output. There can be multiple "-a" flags listed for multiple outputs. If a "-a" or "--assert-file-list" argument is present, then the list of asserted files must match the output files or the tool will fail. The use-case is for the build system to maintain separate lists of output files and to catch errors if the build system's list and the grit list are out-of-sync. --assert-file-list Provide a file listing multiple asserted output files. There is one file name per line. This acts like specifying each file with "-a" on the command line, but without the possibility of running into OS line-length limits for very long lists. -o OUTPUTDIR Specify what directory output paths are relative to. Defaults to the current directory. -D NAME[=VAL] Specify a C-preprocessor-like define NAME with optional value VAL (defaults to 1) which will be used to control conditional inclusion of resources. -E NAME=VALUE Set environment variable NAME to VALUE (within grit). -f FIRSTIDSFILE Path to a python file that specifies the first id of value to use for resources. A non-empty value here will override the value specified in the <grit> node's first_ids_file. -w WHITELISTFILE Path to a file containing the string names of the resources to include. Anything not listed is dropped. -t PLATFORM Specifies the platform the build is targeting; defaults to the value of sys.platform. The value provided via this flag should match what sys.platform would report for your target platform; see grit.node.base.EvaluateCondition. -h HEADERFORMAT Custom format string to use for generating rc header files. The string should have two placeholders: {textual_id} and {numeric_id}. E.g. "#define {textual_id} {numeric_id}" Otherwise it will use the default "#define SYMBOL 1234" --output-all-resource-defines --no-output-all-resource-defines If specified, overrides the value of the output_all_resource_defines attribute of the root <grit> element of the input .grd file. --write-only-new flag If flag is non-0, write output files to a temporary file first, and copy it to the real output only if the new file is different from the old file. This allows some build systems to realize that dependent build steps might be unnecessary, at the cost of comparing the output data at grit time. --depend-on-stamp If specified along with --depfile and --depdir, the depfile generated will depend on a stampfile instead of the first output in the input .grd file. Conditional inclusion of resources only affects the output of files which control which resources get linked into a binary, e.g. it affects .rc files meant for compilation but it does not affect resource header files (that define IDs). This helps ensure that values of IDs stay the same, that all messages are exported to translation interchange files (e.g. XMB files), etc. ''' def ShortDescription(self): return 'A tool that builds RC files for compilation.' def Run(self, opts, args): self.output_directory = '.' first_ids_file = None whitelist_filenames = [] assert_output_files = [] target_platform = None depfile = None depdir = None rc_header_format = None output_all_resource_defines = None write_only_new = False depend_on_stamp = False (own_opts, args) = getopt.getopt(args, 'a:o:D:E:f:w:t:h:', ('depdir=','depfile=','assert-file-list=', 'output-all-resource-defines', 'no-output-all-resource-defines', 'depend-on-stamp', 'write-only-new=')) for (key, val) in own_opts: if key == '-a': assert_output_files.append(val) elif key == '--assert-file-list': with open(val) as f: assert_output_files += f.read().splitlines() elif key == '-o': self.output_directory = val elif key == '-D': name, val = util.ParseDefine(val) self.defines[name] = val elif key == '-E': (env_name, env_value) = val.split('=', 1) os.environ[env_name] = env_value elif key == '-f': # TODO(joi@chromium.org): Remove this override once change # lands in WebKit.grd to specify the first_ids_file in the # .grd itself. first_ids_file = val elif key == '-w': whitelist_filenames.append(val) elif key == '--output-all-resource-defines': output_all_resource_defines = True elif key == '--no-output-all-resource-defines': output_all_resource_defines = False elif key == '-t': target_platform = val elif key == '-h': rc_header_format = val elif key == '--depdir': depdir = val elif key == '--depfile': depfile = val elif key == '--write-only-new': write_only_new = val != '0' elif key == '--depend-on-stamp': depend_on_stamp = True if len(args): print 'This tool takes no tool-specific arguments.' return 2 self.SetOptions(opts) if self.scons_targets: self.VerboseOut('Using SCons targets to identify files to output.\n') else: self.VerboseOut('Output directory: %s (absolute path: %s)\n' % (self.output_directory, os.path.abspath(self.output_directory))) if whitelist_filenames: self.whitelist_names = set() for whitelist_filename in whitelist_filenames: self.VerboseOut('Using whitelist: %s\n' % whitelist_filename); whitelist_contents = util.ReadFile(whitelist_filename, util.RAW_TEXT) self.whitelist_names.update(whitelist_contents.strip().split('\n')) self.write_only_new = write_only_new self.res = grd_reader.Parse(opts.input, debug=opts.extra_verbose, first_ids_file=first_ids_file, defines=self.defines, target_platform=target_platform) # If the output_all_resource_defines option is specified, override the value # found in the grd file. if output_all_resource_defines is not None: self.res.SetShouldOutputAllResourceDefines(output_all_resource_defines) # Set an output context so that conditionals can use defines during the # gathering stage; we use a dummy language here since we are not outputting # a specific language. self.res.SetOutputLanguage('en') if rc_header_format: self.res.AssignRcHeaderFormat(rc_header_format) self.res.RunGatherers() self.Process() if assert_output_files: if not self.CheckAssertedOutputFiles(assert_output_files): return 2 if depfile and depdir: self.GenerateDepfile(depfile, depdir, first_ids_file, depend_on_stamp) return 0 def __init__(self, defines=None): # Default file-creation function is built-in open(). Only done to allow # overriding by unit test. self.fo_create = open # key/value pairs of C-preprocessor like defines that are used for # conditional output of resources self.defines = defines or {} # self.res is a fully-populated resource tree if Run() # has been called, otherwise None. self.res = None # Set to a list of filenames for the output nodes that are relative # to the current working directory. They are in the same order as the # output nodes in the file. self.scons_targets = None # The set of names that are whitelisted to actually be included in the # output. self.whitelist_names = None # Whether to compare outputs to their old contents before writing. self.write_only_new = False @staticmethod def AddWhitelistTags(start_node, whitelist_names): # Walk the tree of nodes added attributes for the nodes that shouldn't # be written into the target files (skip markers). from grit.node import include from grit.node import message from grit.node import structure for node in start_node: # Same trick data_pack.py uses to see what nodes actually result in # real items. if (isinstance(node, include.IncludeNode) or isinstance(node, message.MessageNode) or isinstance(node, structure.StructureNode)): text_ids = node.GetTextualIds() # Mark the item to be skipped if it wasn't in the whitelist. if text_ids and text_ids[0] not in whitelist_names: node.SetWhitelistMarkedAsSkip(True) @staticmethod def ProcessNode(node, output_node, outfile): '''Processes a node in-order, calling its formatter before and after recursing to its children. Args: node: grit.node.base.Node subclass output_node: grit.node.io.OutputNode outfile: open filehandle ''' base_dir = util.dirname(output_node.GetOutputFilename()) formatter = GetFormatter(output_node.GetType()) formatted = formatter(node, output_node.GetLanguage(), output_dir=base_dir) outfile.writelines(formatted) def Process(self): # Update filenames with those provided by SCons if we're being invoked # from SCons. The list of SCons targets also includes all <structure> # node outputs, but it starts with our output files, in the order they # occur in the .grd if self.scons_targets: assert len(self.scons_targets) >= len(self.res.GetOutputFiles()) outfiles = self.res.GetOutputFiles() for ix in range(len(outfiles)): outfiles[ix].output_filename = os.path.abspath( self.scons_targets[ix]) else: for output in self.res.GetOutputFiles(): output.output_filename = os.path.abspath(os.path.join( self.output_directory, output.GetFilename())) # If there are whitelisted names, tag the tree once up front, this way # while looping through the actual output, it is just an attribute check. if self.whitelist_names: self.AddWhitelistTags(self.res, self.whitelist_names) for output in self.res.GetOutputFiles(): self.VerboseOut('Creating %s...' % output.GetFilename()) # Microsoft's RC compiler can only deal with single-byte or double-byte # files (no UTF-8), so we make all RC files UTF-16 to support all # character sets. if output.GetType() in ('rc_header', 'resource_map_header', 'resource_map_source', 'resource_file_map_source'): encoding = 'cp1252' elif output.GetType() in ('android', 'c_format', 'js_map_format', 'plist', 'plist_strings', 'doc', 'json', 'android_policy'): encoding = 'utf_8' elif output.GetType() in ('chrome_messages_json'): # Chrome Web Store currently expects BOM for UTF-8 files :-( encoding = 'utf-8-sig' else: # TODO(gfeher) modify here to set utf-8 encoding for admx/adml encoding = 'utf_16' # Set the context, for conditional inclusion of resources self.res.SetOutputLanguage(output.GetLanguage()) self.res.SetOutputContext(output.GetContext()) self.res.SetFallbackToDefaultLayout(output.GetFallbackToDefaultLayout()) self.res.SetDefines(self.defines) # Make the output directory if it doesn't exist. self.MakeDirectoriesTo(output.GetOutputFilename()) # Write the results to a temporary file and only overwrite the original # if the file changed. This avoids unnecessary rebuilds. outfile = self.fo_create(output.GetOutputFilename() + '.tmp', 'wb') if output.GetType() != 'data_package': outfile = util.WrapOutputStream(outfile, encoding) # Iterate in-order through entire resource tree, calling formatters on # the entry into a node and on exit out of it. with outfile: self.ProcessNode(self.res, output, outfile) # Now copy from the temp file back to the real output, but on Windows, # only if the real output doesn't exist or the contents of the file # changed. This prevents identical headers from being written and .cc # files from recompiling (which is painful on Windows). if not os.path.exists(output.GetOutputFilename()): os.rename(output.GetOutputFilename() + '.tmp', output.GetOutputFilename()) else: # CHROMIUM SPECIFIC CHANGE. # This clashes with gyp + vstudio, which expect the output timestamp # to change on a rebuild, even if nothing has changed, so only do # it when opted in. if not self.write_only_new: write_file = True else: files_match = filecmp.cmp(output.GetOutputFilename(), output.GetOutputFilename() + '.tmp') write_file = not files_match if write_file: shutil.copy2(output.GetOutputFilename() + '.tmp', output.GetOutputFilename()) os.remove(output.GetOutputFilename() + '.tmp') self.VerboseOut(' done.\n') # Print warnings if there are any duplicate shortcuts. warnings = shortcuts.GenerateDuplicateShortcutsWarnings( self.res.UberClique(), self.res.GetTcProject()) if warnings: print '\n'.join(warnings) # Print out any fallback warnings, and missing translation errors, and # exit with an error code if there are missing translations in a non-pseudo # and non-official build. warnings = (self.res.UberClique().MissingTranslationsReport(). encode('ascii', 'replace')) if warnings: self.VerboseOut(warnings) if self.res.UberClique().HasMissingTranslations(): print self.res.UberClique().missing_translations_ sys.exit(-1) def CheckAssertedOutputFiles(self, assert_output_files): '''Checks that the asserted output files are specified in the given list. Returns true if the asserted files are present. If they are not, returns False and prints the failure. ''' # Compare the absolute path names, sorted. asserted = sorted([os.path.abspath(i) for i in assert_output_files]) actual = sorted([ os.path.abspath(os.path.join(self.output_directory, i.GetFilename())) for i in self.res.GetOutputFiles()]) if asserted != actual: missing = list(set(actual) - set(asserted)) extra = list(set(asserted) - set(actual)) error = '''Asserted file list does not match. Expected output files: %s Actual output files: %s Missing output files: %s Extra output files: %s ''' print error % ('\n'.join(asserted), '\n'.join(actual), '\n'.join(missing), '\n'.join(extra)) return False return True def GenerateDepfile(self, depfile, depdir, first_ids_file, depend_on_stamp): '''Generate a depfile that contains the imlicit dependencies of the input grd. The depfile will be in the same format as a makefile, and will contain references to files relative to |depdir|. It will be put in |depfile|. For example, supposing we have three files in a directory src/ src/ blah.grd <- depends on input{1,2}.xtb input1.xtb input2.xtb and we run grit -i blah.grd -o ../out/gen --depdir ../out --depfile ../out/gen/blah.rd.d from the directory src/ we will generate a depfile ../out/gen/blah.grd.d that has the contents gen/blah.h: ../src/input1.xtb ../src/input2.xtb Where "gen/blah.h" is the first output (Ninja expects the .d file to list the first output in cases where there is more than one). If the flag --depend-on-stamp is specified, "gen/blah.rd.d.stamp" will be used that is 'touched' whenever a new depfile is generated. Note that all paths in the depfile are relative to ../out, the depdir. ''' depfile = os.path.abspath(depfile) depdir = os.path.abspath(depdir) infiles = self.res.GetInputFiles() # We want to trigger a rebuild if the first ids change. if first_ids_file is not None: infiles.append(first_ids_file) if (depend_on_stamp): output_file = depfile + ".stamp" # Touch the stamp file before generating the depfile. with open(output_file, 'a'): os.utime(output_file, None) else: # Get the first output file relative to the depdir. outputs = self.res.GetOutputFiles() output_file = os.path.join(self.output_directory, outputs[0].GetFilename()) output_file = os.path.relpath(output_file, depdir) # The path prefix to prepend to dependencies in the depfile. prefix = os.path.relpath(os.getcwd(), depdir) deps_text = ' '.join([os.path.join(prefix, i) for i in infiles]) depfile_contents = output_file + ': ' + deps_text self.MakeDirectoriesTo(depfile) outfile = self.fo_create(depfile, 'wb') outfile.writelines(depfile_contents) @staticmethod def MakeDirectoriesTo(file): '''Creates directories necessary to contain |file|.''' dir = os.path.split(file)[0] if not os.path.exists(dir): os.makedirs(dir)
bsd-2-clause
minosg/piblinker
piblinker.py
1
14790
#!/usr/bin/env python """blinky.py: A small library that uses wiriping pi access to raspbery pi GPIO ports,aimed at providing a simple notification interface""" __author__ = "minos197@gmail.com" __license__ = "LGPL" __version__ = "0.0.1" __email__ = "Minos Galanakis" __project__ = "smartpi" __date__ = "01-06-2015" import io import time import fcntl import serial import struct from subprocess import Popen, PIPE from colorlogger import CLogger from functools import wraps from pidaemon import start_daemon, kill_daemon, normal_start def blinker(color, period=0.2, times=3): """ Decorator that allows modular output formating for PiLogger """ def blinker_decorator(func): @wraps(func) def func_wrapper(class_obj, message): # Blinke the LED before printing sdout class_obj.blink(color, times, period) return func(class_obj, color, message) return func_wrapper return blinker_decorator class PiBlinkerError(Exception): __module__ = 'exceptions' class PiBlinker(): def __init__(self): raise ValueError('PiBlinker is not meant to be instantiated') @classmethod def setup(self, log_level="ver_debug", log_label="PiBlinker", log_path=None, log_colors=None): """ Module Init.""" # Map a color to GPIO.BCM PIN self.LEDS = {"RED": [17], "GREEN": [18], "BLUE": [27], "PURPLE": [17, 27], "YELLOW": [17, 18], "CYAN": [18, 27], "WHITE": [17, 18, 27]} self.last_mode = 0 # Configure the GPIO ports in hardware map(self.run, [(x % v) for n in self.LEDS.values() for v in n for x in ["gpio export %d out", "gpio -g mode %d out"]]) self.i2c_devices = {} # Assosiate log levels with colors if not log_colors: log_colors = {"base_color": "CYAN", "info": "HBLUE", "warning": "YELLOW", "error": "RED", "debug": "GREEN", "ver_debug": "GREEN"} # Initalise the logging module CLogger.setup(log_label, log_level, log_path, log_colors) return self @staticmethod def run(cmd): """ Execute shell command in detached mdoe.""" proc = Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True) ret, err = proc.communicate() if err: # ignore warnings in error stream if "Warning" in err: CLogger.warning(err.strip()) return err raise PiBlinkerError(err) else: return ret @classmethod def set_led(self, led, mode): """ Set an LED to one of the supported states.""" if led not in self.LEDS.keys(): return mlist = {"ON": 1, "OFF": 0, "Toggle": -1} # convert input to a numerical mode try: md = mode if mode not in mlist\ else {k: v for k, v in mlist.iteritems()}[mode] except KeyError: raise PiBlinkerError("Mode %s is not reognised" % mode) # Toggle the led if required led_state = md if md >= 0 else (self.last_mode + 1) % 2 # Toggle the GPIO map(self.run, ["gpio -g write %d %d" % (led_no, led_state) for led_no in self.LEDS[led]]) self.last_mode = led_state @classmethod def blink(self, led, times, delay=1): """ Blink an LED n number of times.""" # Make sure led is uppercase led = led.upper() if led not in self.LEDS.keys(): return mode = 0 count = 1 while (count <= times * 2): self.set_led(led, mode) time.sleep(delay) mode = (mode + 1) % 2 count += 1 self.set_led(led, mode) @classmethod def led_print(self, color, text): """ Print a debug message and notify the user with the LED.""" eval("self.%s" % color.lower())(text) @classmethod def led_bcast(self, data): """ Broadcast a number through led brings """ import re # separate the numbers in the string ie 192.168.3.1 will become array data = map(int, filter(lambda x: x, re.split(r'\D', data))) # Separate the digits to a three color tuple data = map(lambda x: (x/100, (x % 100)/10, (x % 10)), data) for red_cnt, green_cnt, blue_cnt in data: self.blink("GREEN", 1, 1) time.sleep(0.5) self.blink("RED", red_cnt, 0.2) time.sleep(0.5) self.blink("GREEN", green_cnt, 0.2) time.sleep(0.5) self.blink("BLUE", blue_cnt, 0.2) time.sleep(0.5) self.blink("RED", 1, 1) @classmethod @blinker("RED") def red(self, *args): """ Print a debug message and notify the user with the LED.""" color, message = args print"|%s|> %s" % (color, message) @classmethod @blinker("GREEN") def green(self, *args): """ Print a debug message and notify the user with the LED.""" color, message = args print"|%s|> %s" % (color, message) @classmethod @blinker("BLUE") def blue(self, *args): """ Print a debug message and notify the user with the LED.""" color, message = args print"|%s|> %s" % (color, message) @classmethod @blinker("RED") def error(self, *args): """ Print a debug message and notify the user with the LED.""" CLogger.error(args[-1]) @classmethod @blinker("BLUE") def info(self, *args): """ Print a debug message and notify the user with the LED.""" CLogger.info(args[-1]) @classmethod @blinker("RED") def warning(self, *args): """ Print a debug message and notify the user with the LED.""" CLogger.warning(args[-1]) @classmethod @blinker("GREEN") def debug(self, *args): """ Print a debug message and notify the user with the LED.""" CLogger.debug(args[-1]) @classmethod def uart_open(self, port="/dev/ttyAMA0", baud=9600, time_out=None): """Open the Serial Channel""" try: self.uart = serial.Serial(port, baud, timeout=time_out) except serial.SerialException: print "** Failed to initialize serial, check your port.** " raise ValueError @classmethod def uart_activate(self): """ Spam UART port untill it receives an ACK """ self.uart_open() countr = 0 # Test with a not supported command t_char = "O" while True: self.uart.write(t_char) if self.uart.inWaiting(): repl = self.uart.read(2) if repl == "OK": print "UART Activated" else: print "UART was already enabled" break elif countr == 99: # Test with a supported command to see if activated t_char = "2" elif countr > 100: break time.sleep(0.05) countr += 1 @classmethod def uart_read(self, target="ADC"): """Read the register through uart""" cmd = {"ADC": "2", "PIN": "1"} if target in cmd.keys(): self.uart.write(cmd[target]) return self.uart.readline()[:-1] @classmethod def uart_close(self): """Close the serial channel""" self.uart.close() @classmethod def i2c_open_file(self, slave_id, bus=1): """Open the I2C channel for raw byte comms""" if slave_id in self.i2c_devices.keys(): print "Device %d already open" % slave_id return # Open the file descriptors read_ch = io.open("/dev/i2c-"+str(bus), "rb", buffering=0) write_ch = io.open("/dev/i2c-"+str(bus), "wb", buffering=0) # Set the register fcntl.ioctl(read_ch, 0x0703, slave_id) fcntl.ioctl(write_ch, 0x0703, slave_id) # store it to an internal dict self.i2c_devices[slave_id] = (read_ch, write_ch) # return the file descriptors if the user wants to manually drive them return (read_ch, write_ch) @classmethod def i2c_write_as(self, slave_id, format, data): """Write the data formatted using struct pack, Format needs to be specified""" try: wb_file = self.i2c_devices[slave_id][1] wb_file.write(struct.pack(format, data)) except KeyError: print "Device %d does not exist" % slave_id except struct.error: print "Pack Error make sure the data fits the format structure" except: raise IOError @classmethod def i2c_read_as(self, slave_id, format, byte_no): try: rb_file = self.i2c_devices[slave_id][0] return struct.unpack(format, rb_file.read(byte_no)) except KeyError: print "Device %d does not exit" % slave_id except struct.error: print "Pack Error make sure the data fits the format structure" except: raise IOError @classmethod def i2c_close(self, slave_id): """Close the file descriptors associated to the slave channel""" try: self.i2c_devices.pop(slave_id) except KeyError: print "Device %d does not exit" % slave_id @classmethod def demux(self, data): """ For efficiency purposes 10Bit ADC are muxed GPIO state.""" adc_val = data & 0x3FF pin_val = (data >> 15) return (adc_val, pin_val) @classmethod def i2c_read_adc(self, slave_id): """Reads data as returned from a 10Bit ADC sampling operation""" return self.demux(self.i2c_read_as(slave_id, '>H', 2)[0])[0] @classmethod def i2c_read_pin(self, slave_id): """Reads data as returned from a 10Bit ADC sampling operation""" return self.demux(self.i2c_read_as(slave_id, '>H', 2)[0])[1] @classmethod def test_hardware(self): """ Detect hardware shield's presense """ detected = False try: self.uart_open(time_out=2) reading = self.uart_read("ADC") if len(reading): detected = True except: pass try: readf, writef = self.i2c_open_file(0x04, 1) self.i2c_read_as(04, ">H", 2) self.i2c_close(0x04) detected = True except: pass return detected if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-t", "--test", help="Test Hardware, select from [all,\ i2c, led, log, poll, uart]", dest='test') parser.add_argument("-a", "--activate", help="Activate UART mode\ after a reset", action="store_true") parser.add_argument("-d", "--daemon", help="Start a button monitor daemon", action="store_true") parser.add_argument("-nd", "--nodaemon", help="Start monitor without\ daemon context used in conjuction with wrappers", action="store_true") parser.add_argument("-b1", "--button1", help="Bind script to button1", dest='button1') parser.add_argument("-b2", "--button2", help="Bind script to button2", dest='button2') parser.add_argument("-u", "--user", help="Select different user\ to run script as") parser.add_argument("-s", "--sudopass", help="Set optional sudo password\ for elevated priviledges") parser.add_argument("-k", "--kill", help="increase output verbosity", action="store_true") parser.add_argument("-i", "--blinkip", help="increase output verbosity", action="store_true") args = parser.parse_args() mode = 0 pb = PiBlinker.setup() if args.daemon or args.nodaemon: arguments = [args.button1, args.button2, args.user, args.sudopass] if args.nodaemon: normal_start(*arguments) else: start_daemon(*arguments) elif args.kill: kill_daemon() elif args.activate: pb.uart_activate() elif args.blinkip: pb.led_bcast(pb.run("hostname -I")) elif args.test: if args.test == "all": pb.red("This is important") pb.green("This worked") pb.blue("This you should know") readf, writef = pb.i2c_open_file(0x04, 1) # read two bytes using the direct file descriptor print "|RAW ADC|>", repr(readf.read(2)) # read a 2byte uint8_t variable print "|DEC ADC|>", pb.i2c_read_as(04, ">H", 2)[0] pb.i2c_close(0x04) pb.info("This is an info") pb.warning("This is a warning") pb.error("This is an error") pb.debug("This is debug") elif args.test == "i2c": readf, writef = pb.i2c_open_file(0x04, 1) # read two bytes using the direct file descriptor print "|RAW ADC|>", repr(readf.read(2)) # read a 2byte uint8_t variable print "|DEC ADC|>", pb.i2c_read_as(04, ">H", 2)[0] pb.i2c_close(0x04) elif args.test == "poll": readf, writef = pb.i2c_open_file(0x04, 1) try: while True: # Read using read ADC print "| ADC:", pb.i2c_read_adc(0x04), "| PIN: ",\ pb.i2c_read_pin(0x04), "|" time.sleep(0.2) except KeyboardInterrupt: pass pb.i2c_close(0x04) elif args.test == "uart": pb.uart_open() print "ADC:", pb.uart_read("ADC") print "PIN:", pb.uart_read("PIN") pb.uart_close() elif args.test == "led": pb.led_print("RED", "This is RED") pb.led_print("GREEN", "This is GREEN") pb.led_print("BLUE", "This is BLUE") elif args.test == "log": pb.info("This is an info") pb.warning("This is a warning") pb.error("This is an error") pb.debug("This is debug") else: parser.print_help()
lgpl-2.1
jonwright/ImageD11
scripts/plotImageD11map.py
1
1829
#!/usr/bin/env python from __future__ import print_function from ImageD11.grain import read_grain_file import sys, os gf = read_grain_file(sys.argv[1]) mapfile=open(sys.argv[2],"w") def dodot(xyz,k): mapfile.write("%f %f %f %d\n"%(xyz[0],xyz[1],xyz[2],k)) def getmedian(s): items=s.split() j = -1 for i in range(len(items)): if items[i] == "median": j = i if j == -1: return 0 return abs(float(items[j+2])) try: outersf = float(sys.argv[3]) except: outersf = 1.0 print("Scale factor is",outersf) for g in gf: #print g.translation, g.ubi mapfile.write("\n\n") o = g.translation try: sf = pow(getmedian(g.intensity_info),0.3333)*outersf except: sf = outersf try: k = int(g.npks) except: k = 1 for u in g.ubi: dodot(o,k) dodot(o+u*sf,int(g.npks)) for u in g.ubi: dodot(o,k) dodot(o-u*sf,int(g.npks)) # dodot(o,k) # dodot(o+sf*(-g.ubi[0]-g.ubi[1]),k) # dodot(o,k) # dodot(o+sf*(g.ubi[0]+g.ubi[1]),k) mapfile.close() term = " " if "linux" in sys.platform: term = "set term x11" if "win32" in sys.platform: term = "set term windows" open("gnuplot.in","w").write(""" %s set ticslevel 0 set title "Color proportional to number of peaks" set palette model RGB set palette defined ( 0 "violet", 1 "blue", 2 "green", 3 "yellow", 4 "orange", 5 "red" ) set view equal xyz set view 75,0,1,1 #set terminal gif animate delay 10 loop 1 optimize size 1024,768 set nokey set hidden3d #set output "ImageD11map.gif" splot "%s" u 1:2:3:4 w l lw 2 lc pal z """%(term, sys.argv[2]) # "".join(["set view 75,%d\n replot\n"%(i) for i in range(1,360,1)]) ) os.system("gnuplot -background white gnuplot.in -")
gpl-2.0
inspyration/odoo
addons/email_template/tests/test_mail.py
124
14318
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import base64 from openerp.addons.mail.tests.common import TestMail from openerp.tools import mute_logger class test_message_compose(TestMail): def setUp(self): super(test_message_compose, self).setUp() # create a 'pigs' and 'bird' groups that will be used through the various tests self.group_bird_id = self.mail_group.create(self.cr, self.uid, {'name': 'Bird', 'description': 'I am angry !'}) def test_00_message_compose_wizard(self): """ Tests designed for the mail.compose.message wizard updated by email_template. """ cr, uid = self.cr, self.uid mail_compose = self.registry('mail.compose.message') self.res_users.write(cr, uid, [uid], {'signature': 'Admin', 'email': 'a@a.a'}) user_admin = self.res_users.browse(cr, uid, uid) p_a_id = user_admin.partner_id.id group_pigs = self.mail_group.browse(cr, uid, self.group_pigs_id) group_bird = self.mail_group.browse(cr, uid, self.group_bird_id) # Mail data _subject1 = 'Pigs' _subject2 = 'Bird' _body_html1 = 'Fans of Pigs, unite !' _body_html2 = 'I am angry !' _attachments = [ {'name': 'First', 'datas_fname': 'first.txt', 'datas': base64.b64encode('My first attachment'), 'res_model': 'res.partner', 'res_id': self.partner_admin_id}, {'name': 'Second', 'datas_fname': 'second.txt', 'datas': base64.b64encode('My second attachment'), 'res_model': 'res.partner', 'res_id': self.partner_admin_id}, ] _attachments_test = [('first.txt', 'My first attachment'), ('second.txt', 'My second attachment')] # Create template on mail.group, with attachments group_model_id = self.registry('ir.model').search(cr, uid, [('model', '=', 'mail.group')])[0] email_template = self.registry('email.template') email_template_id = email_template.create(cr, uid, { 'model_id': group_model_id, 'name': 'Pigs Template', 'subject': '${object.name}', 'body_html': '${object.description}', 'user_signature': False, 'attachment_ids': [(0, 0, _attachments[0]), (0, 0, _attachments[1])], 'email_to': 'b@b.b, c@c.c', 'email_cc': 'd@d.d' }) # ---------------------------------------- # CASE1: comment and save as template # ---------------------------------------- # 1. Comment on pigs compose_id = mail_compose.create(cr, uid, {'subject': 'Forget me subject', 'body': '<p>Dummy body</p>'}, {'default_composition_mode': 'comment', 'default_model': 'mail.group', 'default_res_id': self.group_pigs_id, 'active_ids': [self.group_pigs_id, self.group_bird_id]}) compose = mail_compose.browse(cr, uid, compose_id) # 2. Save current composition form as a template mail_compose.save_as_template(cr, uid, [compose_id], context={'default_model': 'mail.group'}) # Test: email_template subject, body_html, model last_template_id = email_template.search(cr, uid, [('model', '=', 'mail.group'), ('subject', '=', 'Forget me subject')], limit=1)[0] self.assertTrue(last_template_id, 'email_template not found for model mail.group, subject Forget me subject') last_template = email_template.browse(cr, uid, last_template_id) self.assertEqual(last_template.body_html, '<p>Dummy body</p>', 'email_template incorrect body_html') # ---------------------------------------- # CASE2: comment with template, save as template # ---------------------------------------- # 1. Comment on pigs context = { 'default_composition_mode': 'comment', 'default_model': 'mail.group', 'default_res_id': self.group_pigs_id, 'default_use_template': False, 'default_template_id': email_template_id, 'active_ids': [self.group_pigs_id, self.group_bird_id] } compose_id = mail_compose.create(cr, uid, {'subject': 'Forget me subject', 'body': 'Dummy body'}, context) compose = mail_compose.browse(cr, uid, compose_id, context) onchange_res = compose.onchange_template_id(email_template_id, 'comment', 'mail.group', self.group_pigs_id)['value'] onchange_res['partner_ids'] = [(4, partner_id) for partner_id in onchange_res.pop('partner_ids', [])] onchange_res['attachment_ids'] = [(4, attachment_id) for attachment_id in onchange_res.pop('attachment_ids', [])] compose.write(onchange_res) compose.refresh() message_pids = [partner.id for partner in compose.partner_ids] partner_ids = self.res_partner.search(cr, uid, [('email', 'in', ['b@b.b', 'c@c.c', 'd@d.d'])]) # Test: mail.compose.message: subject, body, partner_ids self.assertEqual(compose.subject, _subject1, 'mail.compose.message subject incorrect') self.assertIn(_body_html1, compose.body, 'mail.compose.message body incorrect') self.assertEqual(set(message_pids), set(partner_ids), 'mail.compose.message partner_ids incorrect') # Test: mail.compose.message: attachments (owner has not been modified) for attach in compose.attachment_ids: self.assertEqual(attach.res_model, 'res.partner', 'mail.compose.message attachment res_model through templat was overriden') self.assertEqual(attach.res_id, self.partner_admin_id, 'mail.compose.message attachment res_id incorrect') self.assertIn((attach.datas_fname, base64.b64decode(attach.datas)), _attachments_test, 'mail.message attachment name / data incorrect') # Test: mail.message: attachments mail_compose.send_mail(cr, uid, [compose_id]) group_pigs.refresh() message_pigs = group_pigs.message_ids[0] for attach in message_pigs.attachment_ids: self.assertEqual(attach.res_model, 'mail.group', 'mail.compose.message attachment res_model through templat was overriden') self.assertEqual(attach.res_id, self.group_pigs_id, 'mail.compose.message attachment res_id incorrect') self.assertIn((attach.datas_fname, base64.b64decode(attach.datas)), _attachments_test, 'mail.message attachment name / data incorrect') # ---------------------------------------- # CASE3: mass_mail with template # ---------------------------------------- # 1. Mass_mail on pigs and bird, with a default_partner_ids set to check he is correctly added context = { 'default_composition_mode': 'mass_mail', 'default_notify': True, 'default_model': 'mail.group', 'default_res_id': self.group_pigs_id, 'default_template_id': email_template_id, 'default_partner_ids': [p_a_id], 'active_ids': [self.group_pigs_id, self.group_bird_id] } compose_id = mail_compose.create(cr, uid, {'subject': 'Forget me subject', 'body': 'Dummy body'}, context) compose = mail_compose.browse(cr, uid, compose_id, context) onchange_res = compose.onchange_template_id(email_template_id, 'mass_mail', 'mail.group', self.group_pigs_id)['value'] onchange_res['partner_ids'] = [(4, partner_id) for partner_id in onchange_res.pop('partner_ids', [])] onchange_res['attachment_ids'] = [(4, attachment_id) for attachment_id in onchange_res.pop('attachment_ids', [])] compose.write(onchange_res) compose.refresh() message_pids = [partner.id for partner in compose.partner_ids] partner_ids = [p_a_id] self.assertEqual(compose.subject, '${object.name}', 'mail.compose.message subject incorrect') self.assertEqual(compose.body, '<p>${object.description}</p>', 'mail.compose.message body incorrect') # todo: check signature self.assertEqual(set(message_pids), set(partner_ids), 'mail.compose.message partner_ids incorrect') # 2. Post the comment, get created message mail_compose.send_mail(cr, uid, [compose_id], {'default_res_id': -1, 'active_ids': [self.group_pigs_id, self.group_bird_id]}) group_pigs.refresh() group_bird.refresh() message_pigs = group_pigs.message_ids[0] message_bird = group_bird.message_ids[0] # Test: subject, body self.assertEqual(message_pigs.subject, _subject1, 'mail.message subject on Pigs incorrect') self.assertEqual(message_bird.subject, _subject2, 'mail.message subject on Bird incorrect') self.assertIn(_body_html1, message_pigs.body, 'mail.message body on Pigs incorrect') self.assertIn(_body_html2, message_bird.body, 'mail.message body on Bird incorrect') # Test: partner_ids: p_a_id (default) + 3 newly created partners # message_pigs_pids = [partner.id for partner in message_pigs.notified_partner_ids] # message_bird_pids = [partner.id for partner in message_bird.notified_partner_ids] # partner_ids = self.res_partner.search(cr, uid, [('email', 'in', ['b@b.b', 'c@c.c', 'd@d.d'])]) # partner_ids.append(p_a_id) # self.assertEqual(set(message_pigs_pids), set(partner_ids), 'mail.message on pigs incorrect number of notified_partner_ids') # self.assertEqual(set(message_bird_pids), set(partner_ids), 'mail.message on bird notified_partner_ids incorrect') # ---------------------------------------- # CASE4: test newly introduced partner_to field # ---------------------------------------- # get already-created partners back p_b_id = self.res_partner.search(cr, uid, [('email', '=', 'b@b.b')])[0] p_c_id = self.res_partner.search(cr, uid, [('email', '=', 'c@c.c')])[0] p_d_id = self.res_partner.search(cr, uid, [('email', '=', 'd@d.d')])[0] # modify template: use partner_to, use template and email address in email_to to test all features together user_model_id = self.registry('ir.model').search(cr, uid, [('model', '=', 'res.users')])[0] email_template.write(cr, uid, [email_template_id], { 'model_id': user_model_id, 'body_html': '${object.login}', 'email_to': '${object.email}, c@c', 'partner_to': '%i,%i' % (p_b_id, p_c_id), 'email_cc': 'd@d', }) # patner by email + partner by id (no double) send_to = [p_a_id, p_b_id, p_c_id, p_d_id] # Generate messsage with default email and partner on template mail_value = mail_compose.generate_email_for_composer(cr, uid, email_template_id, uid) self.assertEqual(set(mail_value['partner_ids']), set(send_to), 'mail.message partner_ids list created by template is incorrect') @mute_logger('openerp.models') def test_10_email_templating(self): """ Tests designed for the mail.compose.message wizard updated by email_template. """ cr, uid, context = self.cr, self.uid, {} # create the email.template on mail.group model group_model_id = self.registry('ir.model').search(cr, uid, [('model', '=', 'mail.group')])[0] email_template = self.registry('email.template') email_template_id = email_template.create(cr, uid, { 'model_id': group_model_id, 'name': 'Pigs Template', 'email_from': 'Raoul Grosbedon <raoul@example.com>', 'subject': '${object.name}', 'body_html': '${object.description}', 'user_signature': True, 'email_to': 'b@b.b, c@c.c', 'email_cc': 'd@d.d', 'partner_to': '${user.partner_id.id},%s,%s,-1' % (self.user_raoul.partner_id.id, self.user_bert.partner_id.id) }) # not force send: email_recipients is not taken into account msg_id = email_template.send_mail(cr, uid, email_template_id, self.group_pigs_id, context=context) mail = self.mail_mail.browse(cr, uid, msg_id, context=context) self.assertEqual(mail.subject, 'Pigs', 'email_template: send_mail: wrong subject') self.assertEqual(mail.email_to, 'b@b.b, c@c.c', 'email_template: send_mail: wrong email_to') self.assertEqual(mail.email_cc, 'd@d.d', 'email_template: send_mail: wrong email_cc') self.assertEqual( set([partner.id for partner in mail.recipient_ids]), set((self.partner_admin_id, self.user_raoul.partner_id.id, self.user_bert.partner_id.id)), 'email_template: send_mail: wrong management of partner_to') # force send: take email_recipients into account email_template.send_mail(cr, uid, email_template_id, self.group_pigs_id, force_send=True, context=context) sent_emails = self._build_email_kwargs_list email_to_lst = [ ['b@b.b', 'c@c.c'], ['Administrator <admin@yourcompany.example.com>'], ['Raoul Grosbedon <raoul@raoul.fr>'], ['Bert Tartignole <bert@bert.fr>']] self.assertEqual(len(sent_emails), 4, 'email_template: send_mail: 3 valid email recipients + email_to -> should send 4 emails') for email in sent_emails: self.assertIn(email['email_to'], email_to_lst, 'email_template: send_mail: wrong email_recipients')
agpl-3.0
eicher31/compassion-modules
child_compassion/mappings/household_mapping.py
3
3536
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo.addons.message_center_compassion.mappings.base_mapping import \ OnrampMapping class HouseHoldMapping(OnrampMapping): ODOO_MODEL = 'compassion.household' CONNECT_MAPPING = { "BeneficiaryHouseholdMemberList": ('member_ids', 'compassion.household.member'), "BeneficiaryHouseholdMemberDetails": ('member_ids', 'compassion.household.member'), "FemaleGuardianEmploymentStatus": 'female_guardian_job_type', "FemaleGuardianOccupation": 'female_guardian_job', "Household_ID": "household_id", "Household_Name": "name", "IsNaturalFatherLivingWithChild": 'father_living_with_child', "IsNaturalMotherLivingWithChild": 'mother_living_with_child', "MaleGuardianEmploymentStatus": 'male_guardian_job_type', "MaleGuardianOccupation": "male_guardian_job", "NaturalFatherAlive": "father_alive", "NaturalMotherAlive": "mother_alive", "NumberOfSiblingBeneficiaries": "number_beneficiaries", "ParentsMaritalStatus": "marital_status", "ParentsTogether": "parents_together", 'RevisedValues': 'revised_value_ids', # Not define "SourceKitName": None, } def _process_odoo_data(self, odoo_data): # Unlink old revised values and create new ones if isinstance(odoo_data.get('revised_value_ids'), list): household = self.env[self.ODOO_MODEL].search( [('household_id', '=', odoo_data['household_id'])]) household.revised_value_ids.unlink() for value in odoo_data['revised_value_ids']: self.env['compassion.major.revision'].create({ 'name': value, 'household_id': household.id, }) del odoo_data['revised_value_ids'] # Replace dict by a tuple for the ORM update/create if 'member_ids' in odoo_data: # Remove all members household = self.env[self.ODOO_MODEL].search( [('household_id', '=', odoo_data['household_id'])]) household.member_ids.unlink() member_list = list() for member in odoo_data['member_ids']: orm_tuple = (0, 0, member) member_list.append(orm_tuple) odoo_data['member_ids'] = member_list or False for key in odoo_data.iterkeys(): val = odoo_data[key] if isinstance(val, basestring) and val.lower() in ( 'null', 'false', 'none', 'other', 'unknown'): odoo_data[key] = False class HouseholdMemberMapping(OnrampMapping): ODOO_MODEL = 'compassion.household.member' CONNECT_MAPPING = { "Beneficiary_GlobalID": ('child_id.global_id', 'compassion.child'), "Beneficiary_LocalID": 'beneficiary_local_id', "FullName": None, "HouseholdMemberRole": 'role', "HouseholdMember_Name": 'name', "IsCaregiver": 'is_caregiver', "IsPrimaryCaregiver": 'is_primary_caregiver', }
agpl-3.0
go-bears/nupic
src/nupic/encoders/category.py
39
7798
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import numpy from nupic.data.fieldmeta import FieldMetaType from nupic.data import SENTINEL_VALUE_FOR_MISSING_DATA from nupic.encoders.base import Encoder, EncoderResult from nupic.encoders.scalar import ScalarEncoder UNKNOWN = "<UNKNOWN>" class CategoryEncoder(Encoder): """Encodes a list of discrete categories (described by strings), that aren't related to each other, so we never emit a mixture of categories. The value of zero is reserved for "unknown category" Internally we use a ScalarEncoder with a radius of 1, but since we only encode integers, we never get mixture outputs. The SDRCategoryEncoder uses a different method to encode categories""" def __init__(self, w, categoryList, name="category", verbosity=0, forced=False): """params: forced (default False) : if True, skip checks for parameters' settings; see encoders/scalar.py for details """ self.encoders = None self.verbosity = verbosity # number of categories includes "unknown" self.ncategories = len(categoryList) + 1 self.categoryToIndex = dict() self.indexToCategory = dict() self.indexToCategory[0] = UNKNOWN for i in xrange(len(categoryList)): self.categoryToIndex[categoryList[i]] = i+1 self.indexToCategory[i+1] = categoryList[i] self.encoder = ScalarEncoder(w, minval=0, maxval=self.ncategories - 1, radius=1, periodic=False, forced=forced) self.width = w * self.ncategories assert self.encoder.getWidth() == self.width self.description = [(name, 0)] self.name = name # These are used to support the topDownCompute method self._topDownMappingM = None # This gets filled in by getBucketValues self._bucketValues = None def getDecoderOutputFieldTypes(self): """ [Encoder class virtual method override] """ # TODO: change back to string meta-type after the decoding logic is fixed # to output strings instead of internal index values. #return (FieldMetaType.string,) return (FieldMetaType.integer,) def getWidth(self): return self.width def getDescription(self): return self.description def getScalars(self, input): """ See method description in base.py """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return numpy.array([None]) else: return numpy.array([self.categoryToIndex.get(input, 0)]) def getBucketIndices(self, input): """ See method description in base.py """ # Get the bucket index from the underlying scalar encoder if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: return self.encoder.getBucketIndices(self.categoryToIndex.get(input, 0)) def encodeIntoArray(self, input, output): # if not found, we encode category 0 if input == SENTINEL_VALUE_FOR_MISSING_DATA: output[0:] = 0 val = "<missing>" else: val = self.categoryToIndex.get(input, 0) self.encoder.encodeIntoArray(val, output) if self.verbosity >= 2: print "input:", input, "va:", val, "output:", output print "decoded:", self.decodedToStr(self.decode(output)) def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ # Get the scalar values from the underlying scalar encoder (fieldsDict, fieldNames) = self.encoder.decode(encoded) if len(fieldsDict) == 0: return (fieldsDict, fieldNames) # Expect only 1 field assert(len(fieldsDict) == 1) # Get the list of categories the scalar values correspond to and # generate the description from the category name(s). (inRanges, inDesc) = fieldsDict.values()[0] outRanges = [] desc = "" for (minV, maxV) in inRanges: minV = int(round(minV)) maxV = int(round(maxV)) outRanges.append((minV, maxV)) while minV <= maxV: if len(desc) > 0: desc += ", " desc += self.indexToCategory[minV] minV += 1 # Return result if parentFieldName != '': fieldName = "%s.%s" % (parentFieldName, self.name) else: fieldName = self.name return ({fieldName: (outRanges, desc)}, [fieldName]) def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder """ expValue = expValues[0] actValue = actValues[0] if expValue == actValue: closeness = 1.0 else: closeness = 0.0 if not fractional: closeness = 1.0 - closeness return numpy.array([closeness]) def getBucketValues(self): """ See the function description in base.py """ if self._bucketValues is None: numBuckets = len(self.encoder.getBucketValues()) self._bucketValues = [] for bucketIndex in range(numBuckets): self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value) return self._bucketValues def getBucketInfo(self, buckets): """ See the function description in base.py """ # For the category encoder, the bucket index is the category index bucketInfo = self.encoder.getBucketInfo(buckets)[0] categoryIndex = int(round(bucketInfo.value)) category = self.indexToCategory[categoryIndex] return [EncoderResult(value=category, scalar=categoryIndex, encoding=bucketInfo.encoding)] def topDownCompute(self, encoded): """ See the function description in base.py """ encoderResult = self.encoder.topDownCompute(encoded)[0] value = encoderResult.value categoryIndex = int(round(value)) category = self.indexToCategory[categoryIndex] return EncoderResult(value=category, scalar=categoryIndex, encoding=encoderResult.encoding) @classmethod def read(cls, proto): encoder = object.__new__(cls) encoder.verbosity = proto.verbosity encoder.encoder = ScalarEncoder.read(proto.encoder) encoder.width = proto.width encoder.description = [(proto.name, 0)] encoder.name = proto.name encoder.indexToCategory = {x.index: x.category for x in proto.indexToCategory} encoder.categoryToIndex = {category: index for index, category in encoder.indexToCategory.items() if category != UNKNOWN} encoder._topDownMappingM = None encoder._bucketValues = None return encoder def write(self, proto): proto.width = self.width proto.indexToCategory = [ {"index": index, "category": category} for index, category in self.indexToCategory.items() ] proto.name = self.name proto.verbosity = self.verbosity self.encoder.write(proto.encoder)
agpl-3.0
dvliman/jaikuengine
.google_appengine/lib/django-1.5/tests/regressiontests/extra_regress/models.py
114
1365
from __future__ import unicode_literals import copy import datetime from django.contrib.auth.models import User from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class RevisionableModel(models.Model): base = models.ForeignKey('self', null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return "%s (%s, %s)" % (self.title, self.id, self.base.id) def save(self, *args, **kwargs): super(RevisionableModel, self).save(*args, **kwargs) if not self.base: self.base = self kwargs.pop('force_insert', None) kwargs.pop('force_update', None) super(RevisionableModel, self).save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision class Order(models.Model): created_by = models.ForeignKey(User) text = models.TextField() @python_2_unicode_compatible class TestObject(models.Model): first = models.CharField(max_length=20) second = models.CharField(max_length=20) third = models.CharField(max_length=20) def __str__(self): return 'TestObject: %s,%s,%s' % (self.first,self.second,self.third)
apache-2.0
goFrendiAsgard/kokoropy
kokoropy/packages/sqlalchemy/dialects/mysql/pyodbc.py
32
2640
# mysql/pyodbc.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+pyodbc :name: PyODBC :dbapi: pyodbc :connectstring: mysql+pyodbc://<username>:<password>@<dsnname> :url: http://pypi.python.org/pypi/pyodbc/ Limitations ----------- The mysql-pyodbc dialect is subject to unresolved character encoding issues which exist within the current ODBC drivers available. (see http://code.google.com/p/pyodbc/issues/detail?id=25). Consider usage of OurSQL, MySQLdb, or MySQL-connector/Python. """ from .base import MySQLDialect, MySQLExecutionContext from ...connectors.pyodbc import PyODBCConnector from ... import util import re class MySQLExecutionContext_pyodbc(MySQLExecutionContext): def get_lastrowid(self): cursor = self.create_cursor() cursor.execute("SELECT LAST_INSERT_ID()") lastrowid = cursor.fetchone()[0] cursor.close() return lastrowid class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect): supports_unicode_statements = False execution_ctx_cls = MySQLExecutionContext_pyodbc pyodbc_driver_name = "MySQL" def __init__(self, **kw): # deal with http://code.google.com/p/pyodbc/issues/detail?id=25 kw.setdefault('convert_unicode', True) super(MySQLDialect_pyodbc, self).__init__(**kw) def _detect_charset(self, connection): """Sniff out the character set in use for connection results.""" # Prefer 'character_set_results' for the current connection over the # value in the driver. SET NAMES or individual variable SETs will # change the charset without updating the driver's view of the world. # # If it's decided that issuing that sort of SQL leaves you SOL, then # this can prefer the driver value. rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'") opts = dict([(row[0], row[1]) for row in self._compat_fetchall(rs)]) for key in ('character_set_connection', 'character_set'): if opts.get(key, None): return opts[key] util.warn("Could not detect the connection character set. " "Assuming latin1.") return 'latin1' def _extract_error_code(self, exception): m = re.compile(r"\((\d+)\)").search(str(exception.args)) c = m.group(1) if c: return int(c) else: return None dialect = MySQLDialect_pyodbc
mit
chienlieu2017/it_management
odoo/addons/website_event/controllers/main.py
7
11571
# -*- coding: utf-8 -*- import babel.dates import re import werkzeug from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from odoo import fields, http, _ from odoo.addons.website.models.website import slug from odoo.http import request class WebsiteEventController(http.Controller): @http.route(['/event', '/event/page/<int:page>', '/events', '/events/page/<int:page>'], type='http', auth="public", website=True) def events(self, page=1, **searches): Event = request.env['event.event'] EventType = request.env['event.type'] searches.setdefault('date', 'all') searches.setdefault('type', 'all') searches.setdefault('country', 'all') domain_search = {} def sdn(date): return fields.Datetime.to_string(date.replace(hour=23, minute=59, second=59)) def sd(date): return fields.Datetime.to_string(date) today = datetime.today() dates = [ ['all', _('Next Events'), [("date_end", ">", sd(today))], 0], ['today', _('Today'), [ ("date_end", ">", sd(today)), ("date_begin", "<", sdn(today))], 0], ['week', _('This Week'), [ ("date_end", ">=", sd(today + relativedelta(days=-today.weekday()))), ("date_begin", "<", sdn(today + relativedelta(days=6-today.weekday())))], 0], ['nextweek', _('Next Week'), [ ("date_end", ">=", sd(today + relativedelta(days=7-today.weekday()))), ("date_begin", "<", sdn(today + relativedelta(days=13-today.weekday())))], 0], ['month', _('This month'), [ ("date_end", ">=", sd(today.replace(day=1))), ("date_begin", "<", (today.replace(day=1) + relativedelta(months=1)).strftime('%Y-%m-%d 00:00:00'))], 0], ['nextmonth', _('Next month'), [ ("date_end", ">=", sd(today.replace(day=1) + relativedelta(months=1))), ("date_begin", "<", (today.replace(day=1) + relativedelta(months=2)).strftime('%Y-%m-%d 00:00:00'))], 0], ['old', _('Old Events'), [ ("date_end", "<", today.strftime('%Y-%m-%d 00:00:00'))], 0], ] # search domains # TDE note: WTF ??? current_date = None current_type = None current_country = None for date in dates: if searches["date"] == date[0]: domain_search["date"] = date[2] if date[0] != 'all': current_date = date[1] if searches["type"] != 'all': current_type = EventType.browse(int(searches['type'])) domain_search["type"] = [("event_type_id", "=", int(searches["type"]))] if searches["country"] != 'all' and searches["country"] != 'online': current_country = request.env['res.country'].browse(int(searches['country'])) domain_search["country"] = ['|', ("country_id", "=", int(searches["country"])), ("country_id", "=", False)] elif searches["country"] == 'online': domain_search["country"] = [("country_id", "=", False)] def dom_without(without): domain = [('state', "in", ['draft', 'confirm', 'done'])] for key, search in domain_search.items(): if key != without: domain += search return domain # count by domains without self search for date in dates: if date[0] != 'old': date[3] = Event.search_count(dom_without('date') + date[2]) domain = dom_without('type') types = Event.read_group(domain, ["id", "event_type_id"], groupby=["event_type_id"], orderby="event_type_id") types.insert(0, { 'event_type_id_count': sum([int(type['event_type_id_count']) for type in types]), 'event_type_id': ("all", _("All Categories")) }) domain = dom_without('country') countries = Event.read_group(domain, ["id", "country_id"], groupby="country_id", orderby="country_id") countries.insert(0, { 'country_id_count': sum([int(country['country_id_count']) for country in countries]), 'country_id': ("all", _("All Countries")) }) step = 10 # Number of events per page event_count = Event.search_count(dom_without("none")) pager = request.website.pager( url="/event", url_args={'date': searches.get('date'), 'type': searches.get('type'), 'country': searches.get('country')}, total=event_count, page=page, step=step, scope=5) order = 'website_published desc, date_begin' if searches.get('date', 'all') == 'old': order = 'website_published desc, date_begin desc' events = Event.search(dom_without("none"), limit=step, offset=pager['offset'], order=order) values = { 'current_date': current_date, 'current_country': current_country, 'current_type': current_type, 'event_ids': events, # event_ids used in website_event_track so we keep name as it is 'dates': dates, 'types': types, 'countries': countries, 'pager': pager, 'searches': searches, 'search_path': "?%s" % werkzeug.url_encode(searches), } return request.render("website_event.index", values) @http.route(['/event/<model("event.event"):event>/page/<path:page>'], type='http', auth="public", website=True) def event_page(self, event, page, **post): values = { 'event': event, 'main_object': event } if '.' not in page: page = 'website_event.%s' % page try: request.website.get_template(page) except ValueError: # page not found values['path'] = re.sub(r"^website_event\.", '', page) values['from_template'] = 'website_event.default_page' # .strip('website_event.') page = 'website.page_404' return request.render(page, values) @http.route(['/event/<model("event.event"):event>'], type='http', auth="public", website=True) def event(self, event, **post): if event.menu_id and event.menu_id.child_id: target_url = event.menu_id.child_id[0].url else: target_url = '/event/%s/register' % str(event.id) if post.get('enable_editor') == '1': target_url += '?enable_editor=1' return request.redirect(target_url) @http.route(['/event/<model("event.event"):event>/register'], type='http', auth="public", website=True) def event_register(self, event, **post): values = { 'event': event, 'main_object': event, 'range': range, } return request.render("website_event.event_description_full", values) @http.route('/event/add_event', type='http', auth="user", methods=['POST'], website=True) def add_event(self, event_name="New Event", **kwargs): event = self._add_event(event_name, request.context) return request.redirect("/event/%s/register?enable_editor=1" % slug(event)) def _add_event(self, event_name=None, context=None, **kwargs): if not event_name: event_name = _("New Event") date_begin = datetime.today() + timedelta(days=(14)) vals = { 'name': event_name, 'date_begin': fields.Date.to_string(date_begin), 'date_end': fields.Date.to_string((date_begin + timedelta(days=(1)))), 'seats_available': 1000, } return request.env['event.event'].with_context(context or {}).create(vals) def get_formated_date(self, event): start_date = fields.Datetime.from_string(event.date_begin).date() end_date = fields.Datetime.from_string(event.date_end).date() month = babel.dates.get_month_names('abbreviated', locale=event.env.context.get('lang', 'en_US'))[start_date.month] return ('%s %s%s') % (month, start_date.strftime("%e"), (end_date != start_date and ("-" + end_date.strftime("%e")) or "")) @http.route('/event/get_country_event_list', type='http', auth='public', website=True) def get_country_events(self, **post): Event = request.env['event.event'] country_code = request.session['geoip'].get('country_code') result = {'events': [], 'country': False} events = None if country_code: country = request.env['res.country'].search([('code', '=', country_code)], limit=1) events = Event.search(['|', ('address_id', '=', None), ('country_id.code', '=', country_code), ('date_begin', '>=', '%s 00:00:00' % fields.Date.today()), ('state', '=', 'confirm')], order="date_begin") if not events: events = Event.search([('date_begin', '>=', '%s 00:00:00' % fields.Date.today()), ('state', '=', 'confirm')], order="date_begin") for event in events: if country_code and event.country_id.code == country_code: result['country'] = country result['events'].append({ "date": self.get_formated_date(event), "event": event, "url": event.website_url}) return request.render("website_event.country_events_list", result) def _process_tickets_details(self, data): nb_register = int(data.get('nb_register-0', 0)) if nb_register: return [{'id': 0, 'name': 'Registration', 'quantity': nb_register, 'price': 0}] return [] @http.route(['/event/<model("event.event"):event>/registration/new'], type='json', auth="public", methods=['POST'], website=True) def registration_new(self, event, **post): tickets = self._process_tickets_details(post) if not tickets: return request.redirect("/event/%s" % slug(event)) return request.env['ir.ui.view'].render_template("website_event.registration_attendee_details", {'tickets': tickets, 'event': event}) def _process_registration_details(self, details): ''' Process data posted from the attendee details form. ''' registrations = {} global_values = {} for key, value in details.iteritems(): counter, field_name = key.split('-', 1) if counter == '0': global_values[field_name] = value else: registrations.setdefault(counter, dict())[field_name] = value for key, value in global_values.iteritems(): for registration in registrations.values(): registration[key] = value return registrations.values() @http.route(['/event/<model("event.event"):event>/registration/confirm'], type='http', auth="public", methods=['POST'], website=True) def registration_confirm(self, event, **post): Attendees = request.env['event.registration'] registrations = self._process_registration_details(post) for registration in registrations: registration['event_id'] = event Attendees += Attendees.sudo().create( Attendees._prepare_attendee_values(registration)) return request.render("website_event.registration_complete", { 'attendees': Attendees, 'event': event, })
gpl-3.0
derekjchow/models
research/deeplab/core/nas_cell.py
1
8432
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # 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. # ============================================================================== """Cell structure used by NAS.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from deeplab.core.utils import resize_bilinear from deeplab.core.utils import scale_dimension arg_scope = tf.contrib.framework.arg_scope slim = tf.contrib.slim class NASBaseCell(object): """NASNet Cell class that is used as a 'layer' in image architectures. See https://arxiv.org/abs/1707.07012 and https://arxiv.org/abs/1712.00559. Args: num_conv_filters: The number of filters for each convolution operation. operations: List of operations that are performed in the NASNet Cell in order. used_hiddenstates: Binary array that signals if the hiddenstate was used within the cell. This is used to determine what outputs of the cell should be concatenated together. hiddenstate_indices: Determines what hiddenstates should be combined together with the specified operations to create the NASNet cell. """ def __init__(self, num_conv_filters, operations, used_hiddenstates, hiddenstate_indices, drop_path_keep_prob, total_num_cells, total_training_steps): if len(hiddenstate_indices) != len(operations): raise ValueError( 'Number of hiddenstate_indices and operations should be the same.') if len(operations) % 2: raise ValueError('Number of operations should be even.') self._num_conv_filters = num_conv_filters self._operations = operations self._used_hiddenstates = used_hiddenstates self._hiddenstate_indices = hiddenstate_indices self._drop_path_keep_prob = drop_path_keep_prob self._total_num_cells = total_num_cells self._total_training_steps = total_training_steps def __call__(self, net, scope, filter_scaling, stride, prev_layer, cell_num): """Runs the conv cell.""" self._cell_num = cell_num self._filter_scaling = filter_scaling self._filter_size = int(self._num_conv_filters * filter_scaling) with tf.variable_scope(scope): net = self._cell_base(net, prev_layer) for i in range(len(self._operations) // 2): with tf.variable_scope('comb_iter_{}'.format(i)): h1 = net[self._hiddenstate_indices[i * 2]] h2 = net[self._hiddenstate_indices[i * 2 + 1]] with tf.variable_scope('left'): h1 = self._apply_conv_operation( h1, self._operations[i * 2], stride, self._hiddenstate_indices[i * 2] < 2) with tf.variable_scope('right'): h2 = self._apply_conv_operation( h2, self._operations[i * 2 + 1], stride, self._hiddenstate_indices[i * 2 + 1] < 2) with tf.variable_scope('combine'): h = h1 + h2 net.append(h) with tf.variable_scope('cell_output'): net = self._combine_unused_states(net) return net def _cell_base(self, net, prev_layer): """Runs the beginning of the conv cell before the chosen ops are run.""" filter_size = self._filter_size if prev_layer is None: prev_layer = net else: if net.shape[2] != prev_layer.shape[2]: prev_layer = resize_bilinear( prev_layer, tf.shape(net)[1:3], prev_layer.dtype) if filter_size != prev_layer.shape[3]: prev_layer = tf.nn.relu(prev_layer) prev_layer = slim.conv2d(prev_layer, filter_size, 1, scope='prev_1x1') prev_layer = slim.batch_norm(prev_layer, scope='prev_bn') net = tf.nn.relu(net) net = slim.conv2d(net, filter_size, 1, scope='1x1') net = slim.batch_norm(net, scope='beginning_bn') net = tf.split(axis=3, num_or_size_splits=1, value=net) net.append(prev_layer) return net def _apply_conv_operation(self, net, operation, stride, is_from_original_input): """Applies the predicted conv operation to net.""" if stride > 1 and not is_from_original_input: stride = 1 input_filters = net.shape[3] filter_size = self._filter_size if 'separable' in operation: num_layers = int(operation.split('_')[-1]) kernel_size = int(operation.split('x')[0][-1]) for layer_num in range(num_layers): net = tf.nn.relu(net) net = slim.separable_conv2d( net, filter_size, kernel_size, depth_multiplier=1, scope='separable_{0}x{0}_{1}'.format(kernel_size, layer_num + 1), stride=stride) net = slim.batch_norm( net, scope='bn_sep_{0}x{0}_{1}'.format(kernel_size, layer_num + 1)) stride = 1 elif 'atrous' in operation: kernel_size = int(operation.split('x')[0][-1]) net = tf.nn.relu(net) if stride == 2: scaled_height = scale_dimension(tf.shape(net)[1], 0.5) scaled_width = scale_dimension(tf.shape(net)[2], 0.5) net = resize_bilinear(net, [scaled_height, scaled_width], net.dtype) net = slim.conv2d(net, filter_size, kernel_size, rate=1, scope='atrous_{0}x{0}'.format(kernel_size)) else: net = slim.conv2d(net, filter_size, kernel_size, rate=2, scope='atrous_{0}x{0}'.format(kernel_size)) net = slim.batch_norm(net, scope='bn_atr_{0}x{0}'.format(kernel_size)) elif operation in ['none']: if stride > 1 or (input_filters != filter_size): net = tf.nn.relu(net) net = slim.conv2d(net, filter_size, 1, stride=stride, scope='1x1') net = slim.batch_norm(net, scope='bn_1') elif 'pool' in operation: pooling_type = operation.split('_')[0] pooling_shape = int(operation.split('_')[-1].split('x')[0]) if pooling_type == 'avg': net = slim.avg_pool2d(net, pooling_shape, stride=stride, padding='SAME') elif pooling_type == 'max': net = slim.max_pool2d(net, pooling_shape, stride=stride, padding='SAME') else: raise ValueError('Unimplemented pooling type: ', pooling_type) if input_filters != filter_size: net = slim.conv2d(net, filter_size, 1, stride=1, scope='1x1') net = slim.batch_norm(net, scope='bn_1') else: raise ValueError('Unimplemented operation', operation) if operation != 'none': net = self._apply_drop_path(net) return net def _combine_unused_states(self, net): """Concatenates the unused hidden states of the cell.""" used_hiddenstates = self._used_hiddenstates states_to_combine = ([ h for h, is_used in zip(net, used_hiddenstates) if not is_used]) net = tf.concat(values=states_to_combine, axis=3) return net @tf.contrib.framework.add_arg_scope def _apply_drop_path(self, net): """Apply drop_path regularization.""" drop_path_keep_prob = self._drop_path_keep_prob if drop_path_keep_prob < 1.0: # Scale keep prob by layer number. assert self._cell_num != -1 layer_ratio = (self._cell_num + 1) / float(self._total_num_cells) drop_path_keep_prob = 1 - layer_ratio * (1 - drop_path_keep_prob) # Decrease keep prob over time. current_step = tf.cast(tf.train.get_or_create_global_step(), tf.float32) current_ratio = tf.minimum(1.0, current_step / self._total_training_steps) drop_path_keep_prob = (1 - current_ratio * (1 - drop_path_keep_prob)) # Drop path. noise_shape = [tf.shape(net)[0], 1, 1, 1] random_tensor = drop_path_keep_prob random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32) binary_tensor = tf.cast(tf.floor(random_tensor), net.dtype) keep_prob_inv = tf.cast(1.0 / drop_path_keep_prob, net.dtype) net = net * keep_prob_inv * binary_tensor return net
apache-2.0
lancezlin/ml_template_py
lib/python2.7/site-packages/sklearn/metrics/tests/test_score_objects.py
15
17443
import pickle import tempfile import shutil import os import numbers import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import assert_warns_message from sklearn.base import BaseEstimator from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, log_loss, precision_score, recall_score) from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.scorer import (check_scoring, _PredictScorer, _passthrough_scorer) from sklearn.metrics import make_scorer, get_scorer, SCORERS from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.cluster import KMeans from sklearn.dummy import DummyRegressor from sklearn.linear_model import Ridge, LogisticRegression from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.datasets import make_blobs from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split, cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsRestClassifier from sklearn.externals import joblib REGRESSION_SCORERS = ['r2', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_median_absolute_error', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error'] CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', 'neg_log_loss', 'log_loss', 'adjusted_rand_score' # not really, but works ] MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] def _make_estimators(X_train, y_train, y_ml_train): # Make estimators that make sense to test various scoring methods sensible_regr = DummyRegressor(strategy='median') sensible_regr.fit(X_train, y_train) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) return dict( [(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS] ) X_mm, y_mm, y_ml_mm = None, None, None ESTIMATORS = None TEMP_FOLDER = None def setup_module(): # Create some memory mapped data global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS TEMP_FOLDER = tempfile.mkdtemp(prefix='sklearn_test_score_objects_') X, y = make_classification(n_samples=30, n_features=5, random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) filename = os.path.join(TEMP_FOLDER, 'test_data.pkl') joblib.dump((X, y, y_ml), filename) X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode='r') ESTIMATORS = _make_estimators(X_mm, y_mm, y_ml_mm) def teardown_module(): global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS # GC closes the mmap file descriptors X_mm, y_mm, y_ml_mm, ESTIMATORS = None, None, None, None shutil.rmtree(TEMP_FOLDER) class EstimatorWithoutFit(object): """Dummy estimator to test check_scoring""" pass class EstimatorWithFit(BaseEstimator): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self class EstimatorWithFitAndScore(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self def score(self, X, y): return 1.0 class EstimatorWithFitAndPredict(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): self.y = y return self def predict(self, X): return self.y class DummyScorer(object): """Dummy scorer that always returns 1.""" def __call__(self, est, X, y): return 1 def test_all_scorers_repr(): # Test that all scorers have a working repr for name, scorer in SCORERS.items(): repr(scorer) def test_check_scoring(): # Test all branches of check_scoring estimator = EstimatorWithoutFit() pattern = (r"estimator should be an estimator implementing 'fit' method," r" .* was passed") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert_true(scorer is _passthrough_scorer) assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = (r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\.") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) scorer = check_scoring(estimator, "accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, "accuracy") assert_true(isinstance(scorer, _PredictScorer)) estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert_true(scorer is None) def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test. grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) scorer = check_scoring(grid, "f1") assert_true(isinstance(scorer, _PredictScorer)) pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, "f1") assert_true(isinstance(scorer, _PredictScorer)) # check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): # Sanity check on the make_scorer factory function. f = lambda *args: 0 assert_raises(ValueError, make_scorer, f, needs_threshold=True, needs_proba=True) def test_classification_scores(): # Test classification scorers. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train) for prefix, metric in [('f1', f1_score), ('precision', precision_score), ('recall', recall_score)]: score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='weighted') assert_almost_equal(score1, score2) score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='macro') assert_almost_equal(score1, score2) score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='micro') assert_almost_equal(score1, score2) score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=1) assert_almost_equal(score1, score2) # test fbeta score that takes an argument scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) assert_almost_equal(score1, score2) # test that custom scorer can be pickled unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score3 = unpickled_scorer(clf, X_test, y_test) assert_almost_equal(score1, score3) # smoke test the repr: repr(fbeta_score) def test_regression_scorers(): # Test regression scorers. diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer('r2')(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2) def test_thresholded_scorers(): # Test scorers that take thresholds. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3) logscore = get_scorer('neg_log_loss')(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss) # same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) # test with a regressor (no decision_function) reg = DecisionTreeRegressor() reg.fit(X_train, y_train) score1 = get_scorer('roc_auc')(reg, X_test, y_test) score2 = roc_auc_score(y_test, reg.predict(X_test)) assert_almost_equal(score1, score2) # Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) def test_thresholded_scorers_multilabel_indicator_data(): # Test that the scorer work with multilabel-indicator format # for multilabel and multi-output multi-class classifier X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) assert_almost_equal(score1, score2) # Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] y_proba = clf.decision_function(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) assert_almost_equal(score1, score2) # Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2) # Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2) def test_unsupervised_scorers(): # Test clustering scorers against gold standard labeling. # We don't have any real unsupervised Scorers yet. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3) km.fit(X_train) score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) score2 = adjusted_rand_score(y_test, km.predict(X_test)) assert_almost_equal(score1, score2) @ignore_warnings def test_raises_on_score_list(): # Test that when a list of scores is returned, we raise proper errors. X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() assert_raises(ValueError, cross_val_score, clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, param_grid={'max_depth': [1, 2]}) assert_raises(ValueError, grid_search.fit, X, y) @ignore_warnings def test_scorer_sample_weight(): # Test that scorers support sample_weight or raise sensible errors # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split sample_weight = np.ones_like(y_test) sample_weight[:10] = 0 # get sensible estimators for each metric estimator = _make_estimators(X_train, y_train, y_ml_train) for name, scorer in SCORERS.items(): if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert_not_equal(weighted, unweighted, msg="scorer {0} behaves identically when " "called with sample weights: {1} vs " "{2}".format(name, weighted, unweighted)) assert_almost_equal(weighted, ignored, err_msg="scorer {0} behaves differently when " "ignoring samples and setting sample_weight to" " 0: {1} vs {2}".format(name, weighted, ignored)) except TypeError as e: assert_true("sample_weight" in str(e), "scorer {0} raises unhelpful exception when called " "with sample weights: {1}".format(name, str(e))) @ignore_warnings # UndefinedMetricWarning for P / R scores def check_scorer_memmap(scorer_name): scorer, estimator = SCORERS[scorer_name], ESTIMATORS[scorer_name] if scorer_name in MULTILABEL_ONLY_SCORERS: score = scorer(estimator, X_mm, y_ml_mm) else: score = scorer(estimator, X_mm, y_mm) assert isinstance(score, numbers.Number), scorer_name def test_scorer_memmap_input(): # Non-regression test for #6147: some score functions would # return singleton memmap when computed on memmap data instead of scalar # float values. for name in SCORERS.keys(): yield check_scorer_memmap, name def test_deprecated_names(): X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) for name in ('mean_absolute_error', 'mean_squared_error', 'median_absolute_error', 'log_loss'): warning_msg = "Scoring method %s was renamed to" % name for scorer in (get_scorer(name), SCORERS[name]): assert_warns_message(DeprecationWarning, warning_msg, scorer, clf, X, y) assert_warns_message(DeprecationWarning, warning_msg, cross_val_score, clf, X, y, scoring=name) def test_scoring_is_not_metric(): assert_raises_regexp(ValueError, 'make_scorer', check_scoring, LogisticRegression(), f1_score) assert_raises_regexp(ValueError, 'make_scorer', check_scoring, LogisticRegression(), roc_auc_score) assert_raises_regexp(ValueError, 'make_scorer', check_scoring, Ridge(), r2_score) assert_raises_regexp(ValueError, 'make_scorer', check_scoring, KMeans(), adjusted_rand_score)
mit
14thibea/megamix
megamix/batch/DPGMM.py
1
20644
# -*- coding: utf-8 -*- # #Created on Fri Apr 14 15:21:17 2017 # #author: Elina Thibeau-Sutre # from .initializations import initialize_log_assignements,initialize_mcw from .base import _full_covariance_matrices from .base import _log_normal_matrix from .base import BaseMixture from .base import _log_B import numpy as np from scipy.special import psi,betaln from scipy.misc import logsumexp class DPVariationalGaussianMixture(BaseMixture): """ Variational Bayesian Estimation of a Gaussian Mixture with Dirichlet Process This class allows to infer an approximate posterior distribution over the parameters of a Gaussian mixture distribution. The weights distribution follows a Dirichlet Process with attribute alpha. Parameters ---------- n_components : int, defaults to 1. Number of clusters used. init : str, defaults to 'kmeans'. Method used in order to perform the initialization, must be in ['random', 'plus', 'AF_KMC', 'kmeans', 'GMM', 'VBGMM']. reg_covar : float, defaults to 1e-6 In order to avoid null covariances this float is added to the diagonal of covariance matrices. type_init : str, defaults to 'resp'. The algorithm is initialized using this data (responsibilities if 'resp' or means, covariances and weights if 'mcw'). Other parameters ---------------- alpha_0 : float, Optional | defaults to None. The prior parameter on the weight distribution (Beta). A high value of alpha_0 will lead to equal weights, while a low value will allow some clusters to shrink and disappear. Must be greater than 0. If None, the value is set to 1/n_components beta_0 : float, Optional | defaults to None. The precision prior on the mean distribution (Gaussian). Must be greater than 0. If None, the value is set to 1.0 nu_0 : float, Optional | defaults to None. The prior of the number of degrees of freedom on the covariance distributions (Wishart). Must be greater or equal to dim. If None, the value is set to dim means_prior : array (dim,), Optional | defaults to None The prior value to compute the value of the means. If None, the value is set to the mean of points_data cov_wishart_prior : type depends on covariance_type, Optional | defaults to None If covariance_type is 'full' type must be array (dim,dim) If covariance_type is 'spherical' type must be float The prior value to compute the value of the precisions. pypcoeff : float | defaults to 0 If 0 the weights are generated according to a Dirichlet Process If >0 and <=1 the weights are generated according to a Pitman-Yor Process. Attributes ---------- name : str The name of the method : 'VBGMM' alpha : array of floats (n_components,2) Contains the parameters of the weight distribution (Beta) beta : array of floats (n_components,) Contains coefficients which are multipied with the precision matrices to form the precision matrix on the Gaussian distribution of the means. nu : array of floats (n_components,) Contains the number of degrees of freedom on the distribution of covariance matrices. _inv_prec : array of floats (n_components,dim,dim) Contains the equivalent of the matrix W described in Bishop's book. It is proportional to cov. _log_det_inv_prec : array of floats (n_components,) Contains the logarithm of the determinant of W matrices. cov : array of floats (n_components,dim,dim) Contains the computed covariance matrices of the mixture. means : array of floats (n_components,dim) Contains the computed means of the mixture. log_weights : array of floats (n_components,) Contains the logarithm of weights of each cluster. iter : int The number of iterations computed with the method fit() convergence_criterion_data : array of floats (iter,) Stores the value of the convergence criterion computed with data on which the model is fitted. convergence_criterion_test : array of floats (iter,) | if _early_stopping only Stores the value of the convergence criterion computed with test data if it exists. _is_initialized : bool Ensures that the method _initialize() has been used before using other methods such as score() or predict_log_assignements(). Raises ------ ValueError : if the parameters are inconsistent, for example if the cluster number is negative, init_type is not in ['resp','mcw']... References ---------- 'Variational Inference for Dirichlet Process Mixtures', D. Blei and M. Jordan """ def __init__(self, n_components=1,init="kmeans",alpha_0=None,beta_0=None, nu_0=None,means_prior=None,cov_wishart_prior=None, reg_covar=1e-6,type_init='resp',n_jobs=1,pypcoeff=0, boost=None): super(DPVariationalGaussianMixture, self).__init__() self.n_components = n_components self.covariance_type = "full" self.init = init self.type_init = type_init self.reg_covar = reg_covar self.boost = boost self.alpha_0 = alpha_0 self.beta_0 = beta_0 self.nu_0 = nu_0 self.pypcoeff = pypcoeff self._means_prior = means_prior self._inv_prec_prior = cov_wishart_prior self.n_jobs = n_jobs self._is_initialized = False self.iter = 0 self.convergence_criterion_data = [] self.convergence_criterion_test = [] self._check_common_parameters() self._check_parameters() if pypcoeff==0: self.name = 'DPGMM' else: self.name = 'PYPGMM' def _check_parameters(self): """ Check the value of the init parameter """ if self.init not in ['random', 'random_sk', 'plus', 'kmeans', 'AF_KMC', 'GMM', 'VBGMM']: raise ValueError("Invalid value for 'init': %s " "'init' should be in " "['random','plus','kmeans','AF_KMC','GMM','VBGMM']" % self.init) if self.pypcoeff < 0 or self.pypcoeff > 1: raise ValueError("Invalid value for 'pypcoeff': %s " "'pypcoeff' should be between 0 and 1" % self.init) if self.boost is not None : if self.boost < 0: raise ValueError("Invalid value for 'boost': %s " "'boost' should be positive" % self.init) if self.init == 'random_sk' and self.type_init=='mcw': raise ValueError("random_sk is only compatible with" "type_init = resp") def _initialize(self,points_data,points_test=None): """ This method initializes the Variational Gaussian Mixture by setting the values of the means, the covariances and other specific parameters (alpha, beta, nu) Parameters ---------- points_data : an array (n_points,dim) Data on which the model is fitted. points_test: an array (n_points,dim) | Optional Data used to do early stopping (avoid overfitting) """ n_points,dim = points_data.shape self._check_prior_parameters(points_data) if self.type_init == 'resp': log_assignements = initialize_log_assignements(self.init,self.n_components,points_data, points_test) self._inv_prec = np.empty((self.n_components,dim,dim)) self._log_det_inv_prec = np.empty(self.n_components) self.cov = np.empty((self.n_components,dim,dim)) self.alpha = np.empty((self.n_components,2)) self.log_weights = np.empty(self.n_components) self._step_M(points_data,log_assignements) # Boosting covariance matrices if self.boost is not None: self.cov *= self.boost self._inv_prec *= self.boost self._log_det_inv_prec += dim * np.log(self.boost) elif self.type_init == 'mcw': #Means, covariances and weights means,cov,log_weights = initialize_mcw(self.init,self.n_components,points_data, points_test) self.cov = cov self.means = means self.log_weights = log_weights # Hyper parameters N = np.exp(log_weights) * n_points self.alpha = np.asarray([1 + N, self.alpha_0 + np.hstack((np.cumsum(N[::-1])[-2::-1], 0))]).T self.alpha += np.asarray([-self.pypcoeff * np.ones(self.n_components), self.pypcoeff * np.arange(self.n_components)]).T self.beta = self.beta_0 + N self.nu = self.nu_0 + N # Matrix W self._inv_prec = cov * self.nu[:,np.newaxis,np.newaxis] self._log_det_inv_prec = np.log(np.linalg.det(self._inv_prec)) elif self.init == 'user': if self.type_init=='kmeans': self._initialize_cov(points_data) # Hyper parameters N = np.exp(self.log_weights) * n_points self.alpha = np.asarray([1 + N, self.alpha_0 + np.hstack((np.cumsum(N[::-1])[-2::-1], 0)) ]).T self.alpha += np.asarray([-self.pypcoeff * np.ones(self.n_components), self.pypcoeff * np.arange(self.n_components)]).T self.beta = self.beta_0 + N self.nu = self.nu_0 + N # Matrix W self._inv_prec = self.cov * self.nu[:,np.newaxis,np.newaxis] self._log_det_inv_prec = np.log(np.linalg.det(self._inv_prec)) self._is_initialized = True def _step_E(self, points): """ In this step the algorithm evaluates the responsibilities of each points in each cluster Parameters ---------- points : an array (n_points,dim) Returns ------- log_resp: an array (n_points,n_components) an array containing the logarithm of the responsibilities. log_prob_norm : an array (n_points,) logarithm of the probability of each sample in points """ n_points,dim = points.shape log_gaussian = _log_normal_matrix(points,self.means,self.cov,'full',self.n_jobs) log_gaussian -= 0.5 * dim * np.log(self.nu) digamma_sum = np.sum(psi(.5 * (self.nu - np.arange(0, dim)[:,np.newaxis])),0) log_lambda = digamma_sum + dim * np.log(2) log_prob = self.log_weights + log_gaussian + 0.5 * (log_lambda - dim / self.beta) log_prob_norm = logsumexp(log_prob, axis=1) log_resp = log_prob - log_prob_norm[:,np.newaxis] return log_prob_norm,log_resp def _step_M(self,points,log_resp): """ In this step the algorithm updates the values of the parameters (means, covariances, alpha, beta, nu). Parameters ---------- points : an array (n_points,dim) log_resp: an array (n_points,n_components) an array containing the logarithm of the responsibilities. """ n_points,dim = points.shape resp = np.exp(log_resp) # Convenient statistics N = np.sum(resp,axis=0) + 10*np.finfo(resp.dtype).eps #Array (n_components,) X_barre = 1/N[:,np.newaxis] * np.dot(resp.T,points) #Array (n_components,dim) S = _full_covariance_matrices(points,X_barre,N,resp,self.reg_covar,self.n_jobs) #Parameters update self.alpha = np.asarray([1.0 + N, self.alpha_0 + np.hstack((np.cumsum(N[::-1])[-2::-1], 0))]).T self.alpha += np.asarray([-self.pypcoeff * np.ones(self.n_components), self.pypcoeff * np.arange(self.n_components)]).T self.beta = self.beta_0 + N self.nu = self.nu_0 + N # Weights update for i in range(self.n_components): if i==0: self.log_weights[i] = psi(self.alpha[i][0]) - psi(np.sum(self.alpha[i])) else: self.log_weights[i] = psi(self.alpha[i][0]) - psi(np.sum(self.alpha[i])) self.log_weights[i] += self.log_weights[i-1] + psi(self.alpha[i-1][1]) - psi(self.alpha[i-1][0]) # Means update means = self.beta_0 * self._means_prior + N[:,np.newaxis] * X_barre self.means = means * np.reciprocal(self.beta)[:,np.newaxis] self.means_estimated = self.means # Covariance update for i in range(self.n_components): diff = X_barre[i] - self._means_prior product = self.beta_0 * N[i]/self.beta[i] * np.outer(diff,diff) self._inv_prec[i] = self._inv_prec_prior + N[i] * S[i] + product det_inv_prec = np.linalg.det(self._inv_prec[i]) self._log_det_inv_prec[i] = np.log(det_inv_prec) self.cov[i] = self._inv_prec[i] / self.nu[i] def _convergence_criterion_simplified(self,points,log_resp,log_prob_norm): """ Compute the lower bound of the likelihood using the simplified Blei and Jordan formula. Can only be used with data which fits the model. Parameters ---------- points : an array (n_points,dim) log_resp: an array (n_points,n_components) an array containing the logarithm of the responsibilities. log_prob_norm : an array (n_points,) logarithm of the probability of each sample in points Returns ------- result : float the lower bound of the likelihood """ resp = np.exp(log_resp) n_points,dim = points.shape prec = np.linalg.inv(self._inv_prec) prec_prior = np.linalg.inv(self._inv_prec_prior) lower_bound = np.zeros(self.n_components) for i in range(self.n_components): lower_bound[i] = _log_B(prec_prior,self.nu_0) - _log_B(prec[i],self.nu[i]) resp_i = resp[:,i:i+1] log_resp_i = log_resp[:,i:i+1] lower_bound[i] -= np.sum(resp_i*log_resp_i) lower_bound[i] += dim*0.5*(np.log(self.beta_0) - np.log(self.beta[i])) result = np.sum(lower_bound) result -= self.n_components * betaln(1,self.alpha_0) result += np.sum(betaln(self.alpha.T[0],self.alpha.T[1])) result -= n_points * dim * 0.5 * np.log(2*np.pi) return result def _convergence_criterion(self,points,log_resp,log_prob_norm): """ Compute the lower bound of the likelihood using the Blei and Jordan formula. The formula cannot be simplified (as it is done in scikit-learn) as we also use it to calculate the lower bound of test points, in this case no simplification can be done. Parameters ---------- points : an array (n_points,dim) log_resp: an array (n_points,n_components) an array containing the logarithm of the responsibilities. log_prob_norm : an array (n_points,) logarithm of the probability of each sample in points Returns ------- result : float the lower bound of the likelihood """ resp = np.exp(log_resp) n_points,dim = points.shape # Convenient statistics N = np.sum(resp,axis=0) + 10*np.finfo(resp.dtype).eps #Array (n_components,) X_barre = 1/N[:,np.newaxis] * np.dot(resp.T,points) #Array (n_components,dim) S = _full_covariance_matrices(points,X_barre,N,resp,self.reg_covar,self.n_jobs) prec = np.linalg.inv(self._inv_prec) prec_prior = np.linalg.inv(self._inv_prec_prior) lower_bound = np.zeros(self.n_components) for i in range(self.n_components): digamma_sum = np.sum(psi(.5 * (self.nu[i] - np.arange(0, dim)[:,np.newaxis])),0) log_det_prec_i = digamma_sum + dim * np.log(2) - self._log_det_inv_prec[i] #/!\ Inverse #First line lower_bound[i] = log_det_prec_i - dim/self.beta[i] - self.nu[i]*np.trace(np.dot(S[i],prec[i])) diff = X_barre[i] - self.means[i] lower_bound[i] += -self.nu[i]*np.dot(diff,np.dot(prec[i],diff.T)) lower_bound[i] *= 0.5 * N[i] #Second line lower_bound[i] += _log_B(prec_prior,self.nu_0) - _log_B(prec[i],self.nu[i]) resp_i = resp[:,i:i+1] log_resp_i = log_resp[:,i:i+1] lower_bound[i] -= np.sum(resp_i*log_resp_i) lower_bound[i] += 0.5 * (self.nu_0 - self.nu[i]) * log_det_prec_i lower_bound[i] += dim*0.5*(np.log(self.beta_0) - np.log(self.beta[i])) lower_bound[i] += dim*0.5*(1 - self.beta_0/self.beta[i] + self.nu[i]) #Third line without the last term which is not summed diff = self.means[i] - self._means_prior lower_bound[i] += -0.5*self.beta_0*self.nu[i]*np.dot(diff,np.dot(prec[i],diff.T)) lower_bound[i] += -0.5*self.nu[i]*np.trace(np.dot(self._inv_prec_prior,prec[i])) #Terms with alpha lower_bound[i] += (N[i] + 1.0 - self.alpha[i,0]) * (psi(self.alpha[i,0]) - psi(np.sum(self.alpha[i]))) lower_bound[i] += (np.sum(N[i+1::]) + self.alpha_0 - self.alpha[i,1]) * (psi(self.alpha[i,1]) - psi(np.sum(self.alpha[i]))) result = np.sum(lower_bound) result -= self.n_components * betaln(1,self.alpha_0) result += np.sum(betaln(self.alpha.T[0],self.alpha.T[1])) result -= n_points * dim * 0.5 * np.log(2*np.pi) return result def _get_parameters(self): return (self.log_weights, self.means, self.cov, self.alpha, self.beta, self.nu) def _set_parameters(self, params,verbose=True): (self.log_weights, self.means, self.cov, self.alpha, self.beta, self.nu )= params # Matrix W self._inv_prec = self.cov * self.nu[:,np.newaxis,np.newaxis] self._log_det_inv_prec = np.log(np.linalg.det(self._inv_prec)) if self.n_components != len(self.means) and verbose: print('The number of components changed') self.n_components = len(self.means) def _limiting_model(self,points): n_points,dim = points.shape log_resp = self.predict_log_resp(points) _,n_components = log_resp.shape exist = np.zeros(n_components) for i in range(n_points): for j in range(n_components): if np.argmax(log_resp[i])==j: exist[j] = 1 idx_existing = np.where(exist==1) log_weights = self.log_weights[idx_existing] means = self.means[idx_existing] cov = self.cov[idx_existing] alpha = self.alpha[idx_existing] beta = self.beta[idx_existing] nu = self.nu[idx_existing] params = (log_weights, means, cov, alpha, beta, nu) return params
apache-2.0
sgarrity/bedrock
lib/l10n_utils/management/commands/fluent.py
8
3597
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from pathlib import Path import textwrap from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Convert a template to use Fluent for l10n' requires_system_checks = False def add_arguments(self, parser): subparsers = parser.add_subparsers( title='subcommand', dest='subcommand' ) subparsers.add_parser('help') recipe_parser = subparsers.add_parser( 'recipe', description='Create migration recipe from template' ) recipe_parser.add_argument('template', type=Path) ftl_parser = subparsers.add_parser( 'ftl', description='Create Fluent file with existing recipe' ) ftl_parser.add_argument( 'recipe_or_template', type=Path, help='Path to the recipe or the template from which the recipe was generated' ) ftl_parser.add_argument( 'locales', nargs='*', default=['en'], metavar='ab-CD', help='Locale codes to create ftl files for' ) template_parser = subparsers.add_parser( 'template', description='Create template_ftl.html file with existing recipe' ) template_parser.add_argument('template', type=Path) activation_parser = subparsers.add_parser( 'activation', description='Port activation data from .lang for a recipe/template' ) activation_parser.add_argument( 'recipe_or_template', type=Path, help='Path to the recipe or the template from which the recipe was generated' ) def handle(self, subcommand, **kwargs): if subcommand == 'recipe': return self.create_recipe(**kwargs) if subcommand == 'ftl': return self.create_ftl(**kwargs) if subcommand == 'template': return self.create_template(**kwargs) if subcommand == 'activation': return self.activation(**kwargs) return self.handle_help(**kwargs) def handle_help(self, **kwargs): self.stdout.write(textwrap.dedent('''\ To migrate a template from .lang to Fluent, use the subcommands like so ./manage.py fluent recipe bedrock/app/templates/app/some.html # edit IDs in lib/fluent_migrations/app/some.py ./manage.py fluent template bedrock/app/templates/app/some.html ./manage.py fluent ftl bedrock/app/templates/app/some.html More documentation on https://bedrock.readthedocs.io/en/latest/fluent-conversion.html. ''')) def create_recipe(self, template, **kwargs): from ._fluent_recipe import Recipe recipe = Recipe(self) recipe.handle(template) def create_template(self, template, **kwargs): from ._fluent_templater import Templater templater = Templater(self) templater.handle(template) def create_ftl(self, recipe_or_template, locales, **kwargs): from ._fluent_ftl import FTLCreator ftl_creator = FTLCreator(self) for locale in locales: ftl_creator.handle(recipe_or_template, locale) def activation(self, recipe_or_template, **kwargs): from ._fluent_activation import Activation activation = Activation(self) activation.handle(recipe_or_template)
mpl-2.0
kevinmel2000/brython
www/src/Lib/test/unittests/test_cgitb.py
113
2551
from test.support import run_unittest from test.script_helper import assert_python_failure, temp_dir import unittest import sys import cgitb class TestCgitb(unittest.TestCase): def test_fonts(self): text = "Hello Robbie!" self.assertEqual(cgitb.small(text), "<small>{}</small>".format(text)) self.assertEqual(cgitb.strong(text), "<strong>{}</strong>".format(text)) self.assertEqual(cgitb.grey(text), '<font color="#909090">{}</font>'.format(text)) def test_blanks(self): self.assertEqual(cgitb.small(""), "") self.assertEqual(cgitb.strong(""), "") self.assertEqual(cgitb.grey(""), "") def test_html(self): try: raise ValueError("Hello World") except ValueError as err: # If the html was templated we could do a bit more here. # At least check that we get details on what we just raised. html = cgitb.html(sys.exc_info()) self.assertIn("ValueError", html) self.assertIn(str(err), html) def test_text(self): try: raise ValueError("Hello World") except ValueError as err: text = cgitb.text(sys.exc_info()) self.assertIn("ValueError", text) self.assertIn("Hello World", text) def test_syshook_no_logdir_default_format(self): with temp_dir() as tracedir: rc, out, err = assert_python_failure( '-c', ('import cgitb; cgitb.enable(logdir=%s); ' 'raise ValueError("Hello World")') % repr(tracedir)) out = out.decode(sys.getfilesystemencoding()) self.assertIn("ValueError", out) self.assertIn("Hello World", out) # By default we emit HTML markup. self.assertIn('<p>', out) self.assertIn('</p>', out) def test_syshook_no_logdir_text_format(self): # Issue 12890: we were emitting the <p> tag in text mode. with temp_dir() as tracedir: rc, out, err = assert_python_failure( '-c', ('import cgitb; cgitb.enable(format="text", logdir=%s); ' 'raise ValueError("Hello World")') % repr(tracedir)) out = out.decode(sys.getfilesystemencoding()) self.assertIn("ValueError", out) self.assertIn("Hello World", out) self.assertNotIn('<p>', out) self.assertNotIn('</p>', out) def test_main(): run_unittest(TestCgitb) if __name__ == "__main__": test_main()
bsd-3-clause
rhololkeolke/apo-website-devin
src/application/facebook/facebook.py
2
8731
""" This module contains helper classes and methods for the facebook integration module .. module:: application.facebook.facebook .. moduleauthor:: Devin Schwab <dts34@case.edu> """ import facebooksdk as fb import models from flask import flash class AlbumList(object): def __init__(self, token): """ Given an an access token this class will get all albums for the object associated with the token (i.e. a page or a user) It will lazily construct an Album instance for each of the album ids returned """ self.graph = fb.GraphAPI(token.access_token) albums_data = self.graph.get_connections('me', 'albums')['data'] self.album_ids = {} self.album_names = {} for data in albums_data: self.album_ids[data['id']] = data self.album_names[data['name']] = data def get_albums_by_name(self, names): """ Given a list of names this method will return album objects for each matching name. If a name is not found then it is silently ignored. This method returns a dictionary mapping name to Album object. """ albums = {} for name in names: if name in self.album_names: if isinstance(self.album_names[name], Album): albums[name] = self.album_names[name] else: self.album_names[name] = Album(graph=self.graph, album_data=self.album_names[name]) self.album_ids[self.album_names[name].me] = self.album_names[name] albums[name] = self.album_names[name] return albums def get_albums_by_id(self, ids): """ Given a list of ids this method will return album objects for each matching id. If an id is not found then it is silently ignored. This method returns a dictionary mapping id to Album object """ albums = {} for album_id in ids: if album_id in self.album_ids: if isinstance(self.album_ids[album_id], Album): albums[album_id] = self.album_ids[album_id] else: self.album_ids[album_id] = Album(graph=self.graph, album_data=self.album_ids[album_id]) self.album_names[self.album_ids[album_id].name] = self.album_ids[album_id] albums[album_id] = self.album_ids[album_id] return albums def get_all_albums_by_id(self): """ This method returns a dictionary of all albums with album ids as the keys """ for album_id in self.album_ids: if not isinstance(self.album_ids[album_id], Album): self.album_ids[album_id] = Album(graph=self.graph, album_data=self.album_ids[album_id]) self.album_names[self.album_ids[album_id].name] = self.album_ids[album_id] return self.album_ids def get_all_albums_by_name(self): """ This method returns a dictionary of all albums with album names as the keys """ for name in self.album_names: if not isinstance(self.album_names[name], Album): self.album_names[name] = Album(graph=self.graph, album_data=self.album_names[name]) self.album_ids[self.album_names[name].me] = self.album_names[name] return self.album_names class Album(object): def __init__(self, graph=None, token=None, album_id=None, album_data=None): """ Initializes a new Album object. If graph is provided then the graph object is saved to this instance. If the token is provided then the graph object for this token is created and saved to this instance. If both are none then an error is raised. If album_id is provided then the graph object is queried for the id and the album object populates itself with this data If album_data is provided then the graph object is populated with the data in the json derived object If both are None then an error is raised """ if graph is None and token is None: raise TypeError("Either a graph object must be provided or a token must be provided") if graph is not None: self.graph = graph query = models.AccessTokenModel.all() query.filter('access_token =', graph.access_token) try: self.token = query.fetch(1)[0] except IndexError: raise TypeError('The token object provided was not an AccessTokenModel instance') else: self.graph = fb.GraphAPI(token.access_token) self.token = token if album_id is None and album_data is None: raise TypeError("Either an album id or a album data must be provided") if album_id is not None: album_data = self.graph.get_object(album_id) self.me = album_data['id'] self.name = album_data['name'] self.desc = album_data.get('description', None) self.count = album_data.get('count', 0) if 'cover_photo' in album_data: self.cover_photo = Photo(self.me, graph=self.graph, photo_id=album_data['cover_photo']).thumbnail else: self.cover_photo = None def get_model(self): query = models.AlbumModel.all() query.filter('me =', self.me) try: return query.fetch(1)[0] except IndexError: cover_thumb = None if self.cover_photo is not None: cover_thumb = self.cover_photo entity = models.AlbumModel(me=self.me, token=self.token, name=self.name, desc=self.desc, cover_photo=cover_thumb) entity.put() return entity def get_photos(self): """ Get a list of Photo objects """ photos_data = self.graph.get_connections(self.me, 'photos')['data'] photos = [] for photo_data in photos_data: query = models.PhotoModel.all() query.filter('me =', photo_data['id']) try: photos.append(query.fetch(1)[0]) except IndexError: name = None if 'name' in photo_data: name = photo_data['name'] orig = photo_data['images'][0]['source'] entity = models.PhotoModel(me=photo_data['id'], album_id=self.me, name=name, thumbnail=photo_data['picture'], original=orig) entity.put() photos.append(entity) return photos class Photo(object): def __init__(self, album_id, graph=None, token=None, photo_id=None, photo_data=None): if graph is None and token is None: raise TypeError("Either a graph object must be provided or a token must be provided") if graph is not None: self.graph = graph else: self.graph = fb.GraphAPI(token.access_token) if photo_id is None and photo_data is None: raise TypeError("Either an album id or a album data must be provided") if photo_id is not None: photo_data = self.graph.get_object(photo_id) self.me = photo_data['id'] self.name = photo_data.get('name', None) self.thumbnail = photo_data['picture'] self.original = photo_data['images'][0]['source'] self.album_id = album_id def get_model(self): query = models.PhotoModel.all() query.filter('me =', self.me) try: return query.fetch(1)[0] except IndexError: entity = models.PhotoModel(me=self.me, album_id=self.album_id, name=self.name, thumbnail=self.thumbnail, original=self.original) entity.put() return entity
bsd-3-clause
korotkyn/ibis
ibis/expr/tests/test_temporal.py
9
5955
# Copyright 2014 Cloudera 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. from ibis.common import IbisError import ibis.expr.operations as ops import ibis.expr.types as ir import ibis.expr.temporal as T from ibis.expr.tests.mocks import MockConnection from ibis.compat import unittest class TestFixedOffsets(unittest.TestCase): def setUp(self): self.con = MockConnection() self.table = self.con.table('alltypes') def test_upconvert(self): cases = [ (T.day(14), 'w', T.week(2)), (T.hour(72), 'd', T.day(3)), (T.minute(240), 'h', T.hour(4)), (T.second(360), 'm', T.minute(6)), (T.second(3 * 86400), 'd', T.day(3)), (T.millisecond(5000), 's', T.second(5)), (T.microsecond(5000000), 's', T.second(5)), (T.nanosecond(5000000000), 's', T.second(5)), ] for offset, unit, expected in cases: result = offset.to_unit(unit) assert result.equals(expected) def test_multiply(self): offset = T.day(2) assert (offset * 2).equals(T.day(4)) assert (offset * (-2)).equals(T.day(-4)) assert (3 * offset).equals(T.day(6)) assert ((-3) * offset).equals(T.day(-6)) def test_repr(self): assert repr(T.day()) == '<Timedelta: 1 day>' assert repr(T.day(2)) == '<Timedelta: 2 days>' assert repr(T.year()) == '<Timedelta: 1 year>' assert repr(T.month(2)) == '<Timedelta: 2 months>' assert repr(T.second(40)) == '<Timedelta: 40 seconds>' def test_cannot_upconvert(self): cases = [ (T.day(), 'w'), (T.hour(), 'd'), (T.minute(), 'h'), (T.second(), 'm'), (T.second(), 'd'), (T.millisecond(), 's'), (T.microsecond(), 's'), (T.nanosecond(), 's'), ] for delta, target in cases: self.assertRaises(IbisError, delta.to_unit, target) def test_downconvert_second_parts(self): K = 2 sec = T.second(K) milli = T.millisecond(K) micro = T.microsecond(K) nano = T.nanosecond(K) cases = [ (sec.to_unit('s'), T.second(K)), (sec.to_unit('ms'), T.millisecond(K * 1000)), (sec.to_unit('us'), T.microsecond(K * 1000000)), (sec.to_unit('ns'), T.nanosecond(K * 1000000000)), (milli.to_unit('ms'), T.millisecond(K)), (milli.to_unit('us'), T.microsecond(K * 1000)), (milli.to_unit('ns'), T.nanosecond(K * 1000000)), (micro.to_unit('us'), T.microsecond(K)), (micro.to_unit('ns'), T.nanosecond(K * 1000)), (nano.to_unit('ns'), T.nanosecond(K)) ] self._check_cases(cases) def test_downconvert_hours(self): K = 2 offset = T.hour(K) cases = [ (offset.to_unit('h'), T.hour(K)), (offset.to_unit('m'), T.minute(K * 60)), (offset.to_unit('s'), T.second(K * 3600)), (offset.to_unit('ms'), T.millisecond(K * 3600000)), (offset.to_unit('us'), T.microsecond(K * 3600000000)), (offset.to_unit('ns'), T.nanosecond(K * 3600000000000)) ] self._check_cases(cases) def test_downconvert_day(self): K = 2 week = T.week(K) day = T.day(K) cases = [ (week.to_unit('d'), T.day(K * 7)), (week.to_unit('h'), T.hour(K * 7 * 24)), (day.to_unit('d'), T.day(K)), (day.to_unit('h'), T.hour(K * 24)), (day.to_unit('m'), T.minute(K * 1440)), (day.to_unit('s'), T.second(K * 86400)), (day.to_unit('ms'), T.millisecond(K * 86400000)), (day.to_unit('us'), T.microsecond(K * 86400000000)), (day.to_unit('ns'), T.nanosecond(K * 86400000000000)) ] self._check_cases(cases) def test_combine_with_different_kinds(self): cases = [ (T.day() + T.minute(), T.minute(1441)), (T.second() + T.millisecond(10), T.millisecond(1010)), (T.hour() + T.minute(5) + T.second(10), T.second(3910)) ] self._check_cases(cases) def test_timedelta_generic_api(self): cases = [ (T.timedelta(weeks=2), T.week(2)), (T.timedelta(days=3), T.day(3)), (T.timedelta(hours=4), T.hour(4)), (T.timedelta(minutes=5), T.minute(5)), (T.timedelta(seconds=6), T.second(6)), (T.timedelta(milliseconds=7), T.millisecond(7)), (T.timedelta(microseconds=8), T.microsecond(8)), (T.timedelta(nanoseconds=9), T.nanosecond(9)), ] self._check_cases(cases) def _check_cases(self, cases): for x, y in cases: assert x.equals(y) def test_offset_timestamp_expr(self): c = self.table.i x = T.timedelta(days=1) expr = x + c assert isinstance(expr, ir.TimestampArray) assert isinstance(expr.op(), ops.TimestampDelta) # test radd expr = c + x assert isinstance(expr, ir.TimestampArray) assert isinstance(expr.op(), ops.TimestampDelta) class TestTimedelta(unittest.TestCase): def test_compound_offset(self): # These are not yet allowed (e.g. 1 month + 1 hour) pass def test_offset_months(self): pass
apache-2.0
hectord/lettuce
tests/integration/lib/Django-1.2.5/django/core/handlers/base.py
44
9926
import sys from django import http from django.core import signals from django.utils.encoding import force_unicode from django.utils.importlib import import_module class BaseHandler(object): # Changes that are always applied to a response (in this order). response_fixes = [ http.fix_location_header, http.conditional_content_removal, http.fix_IE_for_attach, http.fix_IE_for_vary, ] def __init__(self): self._request_middleware = self._view_middleware = self._response_middleware = self._exception_middleware = None def load_middleware(self): """ Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__). """ from django.conf import settings from django.core import exceptions self._view_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: try: dot = middleware_path.rindex('.') except ValueError: raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:] try: mod = import_module(mw_module) except ImportError, e: raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) try: mw_class = getattr(mod, mw_classname) except AttributeError: raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) try: mw_instance = mw_class() except exceptions.MiddlewareNotUsed: continue if hasattr(mw_instance, 'process_request'): request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._request_middleware = request_middleware def get_response(self, request): "Returns an HttpResponse object for the given HttpRequest" from django.core import exceptions, urlresolvers from django.conf import settings try: try: # Setup default url resolver for this thread. urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: return response if hasattr(request, "urlconf"): # Reset url resolver with a custom urlconf. urlconf = request.urlconf urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) callback, callback_args, callback_kwargs = resolver.resolve( request.path_info) # Apply view middleware for middleware_method in self._view_middleware: response = middleware_method(request, callback, callback_args, callback_kwargs) if response: return response try: response = callback(request, *callback_args, **callback_kwargs) except Exception, e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. for middleware_method in self._exception_middleware: response = middleware_method(request, e) if response: return response raise # Complain if the view returned None (a common error). if response is None: try: view_name = callback.func_name # If it's a function except AttributeError: view_name = callback.__class__.__name__ + '.__call__' # If it's a class raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) return response except http.Http404, e: if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) else: try: callback, param_dict = resolver.resolve404() return callback(request, **param_dict) except: try: return self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: receivers = signals.got_request_exception.send(sender=self.__class__, request=request) except exceptions.PermissionDenied: return http.HttpResponseForbidden('<h1>Permission denied</h1>') except SystemExit: # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise except: # Handle everything else, including SuspiciousOperation, etc. # Get the exception info now, in case another exception is thrown later. receivers = signals.got_request_exception.send(sender=self.__class__, request=request) return self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: # Reset URLconf for this thread on the way out for complete # isolation of request.urlconf urlresolvers.set_urlconf(None) def handle_uncaught_exception(self, request, resolver, exc_info): """ Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an error. """ from django.conf import settings from django.core.mail import mail_admins if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *exc_info) # When DEBUG is False, send an error message to the admins. subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr) mail_admins(subject, message, fail_silently=True) # If Http500 handler is not installed, re-raise last exception if resolver.urlconf_module is None: raise exc_info[1], None, exc_info[2] # Return an HttpResponse that displays a friendly error message. callback, param_dict = resolver.resolve500() return callback(request, **param_dict) def _get_traceback(self, exc_info=None): "Helper function to return the traceback as a string" import traceback return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info()))) def apply_response_fixes(self, request, response): """ Applies each of the functions in self.response_fixes to the request and response, modifying the response in the process. Returns the new response. """ for func in self.response_fixes: response = func(request, response) return response def get_script_name(environ): """ Returns the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless DJANGO_USE_POST_REWRITE is set (to anything). """ from django.conf import settings if settings.FORCE_SCRIPT_NAME is not None: return force_unicode(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = environ.get('SCRIPT_URL', u'') if not script_url: script_url = environ.get('REDIRECT_URL', u'') if script_url: return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) return force_unicode(environ.get('SCRIPT_NAME', u''))
gpl-3.0
KristFoundation/Programs
luaide/Documentation/networking/cxacru-cf.py
14668
1626
#!/usr/bin/env python # Copyright 2009 Simon Arlott # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Usage: cxacru-cf.py < cxacru-cf.bin # Output: values string suitable for the sysfs adsl_config attribute # # Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110 # contains mis-aligned values which will stop the modem from being able # to make a connection. If the first and last two bytes are removed then # the values become valid, but the modulation will be forced to ANSI # T1.413 only which may not be appropriate. # # The original binary format is a packed list of le32 values. import sys import struct i = 0 while True: buf = sys.stdin.read(4) if len(buf) == 0: break elif len(buf) != 4: sys.stdout.write("\n") sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf))) sys.exit(1) if i > 0: sys.stdout.write(" ") sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0])) i += 1 sys.stdout.write("\n")
mit
ARM-software/mbed-beetle
tools/host_tests/host_tests_plugins/module_copy_smart.py
2
4378
""" mbed SDK Copyright (c) 2011-2013 ARM Limited 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 os import sys from os.path import join, basename, exists, abspath, dirname from time import sleep from host_test_plugins import HostTestPluginBase sys.path.append(abspath(join(dirname(__file__), "../../../"))) from tools.test_api import get_autodetected_MUTS_list class HostTestPluginCopyMethod_Smart(HostTestPluginBase): # Plugin interface name = 'HostTestPluginCopyMethod_Smart' type = 'CopyMethod' stable = True capabilities = ['smart'] required_parameters = ['image_path', 'destination_disk', 'target_mcu'] def setup(self, *args, **kwargs): """ Configure plugin, this function should be called before plugin execute() method is used. """ return True def execute(self, capability, *args, **kwargs): """ Executes capability by name. Each capability may directly just call some command line program or execute building pythonic function """ result = False if self.check_parameters(capability, *args, **kwargs) is True: image_path = kwargs['image_path'] destination_disk = kwargs['destination_disk'] target_mcu = kwargs['target_mcu'] # Wait for mount point to be ready self.check_mount_point_ready(destination_disk) # Blocking # Prepare correct command line parameter values image_base_name = basename(image_path) destination_path = join(destination_disk, image_base_name) if capability == 'smart': if os.name == 'posix': cmd = ['cp', image_path, destination_path] result = self.run_command(cmd, shell=False) cmd = ['sync'] result = self.run_command(cmd, shell=False) elif os.name == 'nt': cmd = ['copy', image_path, destination_path] result = self.run_command(cmd, shell=True) # Give the OS and filesystem time to settle down sleep(3) platform_name_filter = [target_mcu] muts_list = {} remount_complete = False for i in range(0, 60): print('Looking for %s with MBEDLS' % target_mcu) muts_list = get_autodetected_MUTS_list(platform_name_filter=platform_name_filter) if 1 in muts_list: mut = muts_list[1] destination_disk = mut['disk'] destination_path = join(destination_disk, image_base_name) if mut['mcu'] == 'LPC1768' or mut['mcu'] == 'LPC11U24':