15 values
1 class
""" 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))
# -*- 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=""][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(, 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) 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('form input[type="submit"]') self.wait_until_text_present('Email Sent') self.assertEqual(len(mail.outbox), 1)
#!/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:, 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" ) # # 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()
#!/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 += 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( 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 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: 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)
#!/usr/bin/env python """ A small library that uses wiriping pi access to raspbery pi GPIO ports,aimed at providing a simple notification interface""" __author__ = "" __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(, [(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(, ["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 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."""[-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 = 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 ="/dev/i2c-"+str(bus), "rb", buffering=0) write_ch ="/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, 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("hostname -I")) elif args.test: if args.test == "all":"This is important")"This worked")"This you should know") readf, writef = pb.i2c_open_file(0x04, 1) # read two bytes using the direct file descriptor print "|RAW ADC|>", repr( # read a 2byte uint8_t variable print "|DEC ADC|>", pb.i2c_read_as(04, ">H", 2)[0] pb.i2c_close(0x04)"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( # 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":"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()
#!/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("","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 -")
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <> # # 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 <>. # ############################################################################## import base64 from openerp.addons.mail.tests.common import TestMail from 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.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.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 = 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, with attachments group_model_id = self.registry('ir.model').search(cr, uid, [('model', '=', '')])[0] email_template = self.registry('email.template') email_template_id = email_template.create(cr, uid, { 'model_id': group_model_id, 'name': 'Pigs Template', 'subject': '${}', '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': '', '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': ''}) # Test: email_template subject, body_html, model last_template_id =, uid, [('model', '=', ''), ('subject', '=', 'Forget me subject')], limit=1)[0] self.assertTrue(last_template_id, 'email_template not found for model, 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': '', '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', '', 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 = [ for partner in compose.partner_ids] partner_ids =, 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.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': '', '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', '', 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 = [ for partner in compose.partner_ids] partner_ids = [p_a_id] self.assertEqual(compose.subject, '${}', '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 = [ for partner in message_pigs.notified_partner_ids] # message_bird_pids = [ for partner in message_bird.notified_partner_ids] # partner_ids =, 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 =, uid, [('email', '=', 'b@b.b')])[0] p_c_id =, uid, [('email', '=', 'c@c.c')])[0] p_d_id =, 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': '${}, 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.uid, {} # create the email.template on model group_model_id = self.registry('ir.model').search(cr, uid, [('model', '=', '')])[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 <>', 'subject': '${}', 'body_html': '${object.description}', 'user_signature': True, 'email_to': 'b@b.b, c@c.c', 'email_cc': 'd@d.d', 'partner_to': '${},%s,%s,-1' % (, }) # 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([ for partner in mail.recipient_ids]), set((self.partner_admin_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 <>'], ['Raoul Grosbedon <>'], ['Bert Tartignole <>']] 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')
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH ( # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <> # # The licence is in the file # ############################################################################## 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':, }) 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', }
# ---------------------------------------------------------------------- # 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 # # # ---------------------------------------------------------------------- import numpy from import FieldMetaType from 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/ 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)] = 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 """ 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 """ # 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 """ # 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, else: fieldName = return ({fieldName: (outRanges, desc)}, [fieldName]) def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in 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 """ 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 """ # 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 """ 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 = encoder.width = proto.width encoder.description = [(, 0)] = 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.verbosity = self.verbosity self.encoder.write(proto.encoder)
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( def __str__(self): return "%s (%s, %s)" % (self.title,, 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) = 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)
# mysql/ # 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: """ .. dialect:: mysql+pyodbc :name: PyODBC :dbapi: pyodbc :connectstring: mysql+pyodbc://<username>:<password>@<dsnname> :url: Limitations ----------- The mysql-pyodbc dialect is subject to unresolved character encoding issues which exist within the current ODBC drivers available. (see 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 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 = if c: return int(c) else: return None dialect = MySQLDialect_pyodbc
# -*- 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 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 = 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[''].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 = 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 ="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: 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( 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 = + 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/