repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991 values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15 values |
|---|---|---|---|---|---|
andyzsf/edx | common/djangoapps/student/migrations/0023_add_test_center_registration.py | 183 | 19003 | # -*- 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 'TestCenterRegistration'
db.create_table('student_testcenterregistration', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('testcenter_user', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['student.TestCenterUser'])),
('course_id', self.gf('django.db.models.fields.CharField')(max_length=128, db_index=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('user_updated_at', self.gf('django.db.models.fields.DateTimeField')(db_index=True)),
('client_authorization_id', self.gf('django.db.models.fields.CharField')(unique=True, max_length=20, db_index=True)),
('exam_series_code', self.gf('django.db.models.fields.CharField')(max_length=15, db_index=True)),
('eligibility_appointment_date_first', self.gf('django.db.models.fields.DateField')(db_index=True)),
('eligibility_appointment_date_last', self.gf('django.db.models.fields.DateField')(db_index=True)),
('accommodation_code', self.gf('django.db.models.fields.CharField')(max_length=64, blank=True)),
('accommodation_request', self.gf('django.db.models.fields.CharField')(db_index=False, max_length=1024, blank=True)),
('uploaded_at', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
('processed_at', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
('upload_status', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=20, blank=True)),
('upload_error_message', self.gf('django.db.models.fields.CharField')(max_length=512, blank=True)),
('authorization_id', self.gf('django.db.models.fields.IntegerField')(null=True, db_index=True)),
('confirmed_at', self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True)),
))
db.send_create_signal('student', ['TestCenterRegistration'])
# Adding field 'TestCenterUser.uploaded_at'
db.add_column('student_testcenteruser', 'uploaded_at',
self.gf('django.db.models.fields.DateTimeField')(db_index=True, null=True, blank=True),
keep_default=False)
# Adding field 'TestCenterUser.processed_at'
db.add_column('student_testcenteruser', 'processed_at',
self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True),
keep_default=False)
# Adding field 'TestCenterUser.upload_status'
db.add_column('student_testcenteruser', 'upload_status',
self.gf('django.db.models.fields.CharField')(db_index=True, default='', max_length=20, blank=True),
keep_default=False)
# Adding field 'TestCenterUser.upload_error_message'
db.add_column('student_testcenteruser', 'upload_error_message',
self.gf('django.db.models.fields.CharField')(default='', max_length=512, blank=True),
keep_default=False)
# Adding field 'TestCenterUser.confirmed_at'
db.add_column('student_testcenteruser', 'confirmed_at',
self.gf('django.db.models.fields.DateTimeField')(null=True, db_index=True),
keep_default=False)
# Adding index on 'TestCenterUser', fields ['company_name']
db.create_index('student_testcenteruser', ['company_name'])
# Adding unique constraint on 'TestCenterUser', fields ['client_candidate_id']
db.create_unique('student_testcenteruser', ['client_candidate_id'])
def backwards(self, orm):
# Removing unique constraint on 'TestCenterUser', fields ['client_candidate_id']
db.delete_unique('student_testcenteruser', ['client_candidate_id'])
# Removing index on 'TestCenterUser', fields ['company_name']
db.delete_index('student_testcenteruser', ['company_name'])
# Deleting model 'TestCenterRegistration'
db.delete_table('student_testcenterregistration')
# Deleting field 'TestCenterUser.uploaded_at'
db.delete_column('student_testcenteruser', 'uploaded_at')
# Deleting field 'TestCenterUser.processed_at'
db.delete_column('student_testcenteruser', 'processed_at')
# Deleting field 'TestCenterUser.upload_status'
db.delete_column('student_testcenteruser', 'upload_status')
# Deleting field 'TestCenterUser.upload_error_message'
db.delete_column('student_testcenteruser', 'upload_error_message')
# Deleting field 'TestCenterUser.confirmed_at'
db.delete_column('student_testcenteruser', 'confirmed_at')
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'})
},
'student.courseenrollment': {
'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'CourseEnrollment'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'student.courseenrollmentallowed': {
'Meta': {'unique_together': "(('email', 'course_id'),)", 'object_name': 'CourseEnrollmentAllowed'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'student.pendingemailchange': {
'Meta': {'object_name': 'PendingEmailChange'},
'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'new_email': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'student.pendingnamechange': {
'Meta': {'object_name': 'PendingNameChange'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'new_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'rationale': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'student.registration': {
'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"},
'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'student.testcenterregistration': {
'Meta': {'object_name': 'TestCenterRegistration'},
'accommodation_code': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}),
'accommodation_request': ('django.db.models.fields.CharField', [], {'db_index': 'False', 'max_length': '1024', 'blank': 'True'}),
'authorization_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}),
'client_authorization_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'}),
'confirmed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'eligibility_appointment_date_first': ('django.db.models.fields.DateField', [], {'db_index': 'True'}),
'eligibility_appointment_date_last': ('django.db.models.fields.DateField', [], {'db_index': 'True'}),
'exam_series_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'processed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'testcenter_user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['student.TestCenterUser']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'upload_error_message': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
'upload_status': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'user_updated_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'})
},
'student.testcenteruser': {
'Meta': {'object_name': 'TestCenterUser'},
'address_1': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'address_2': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
'address_3': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
'candidate_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'client_candidate_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'company_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '50', 'blank': 'True'}),
'confirmed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'db_index': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'extension': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '8', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '35', 'blank': 'True'}),
'fax_country_code': ('django.db.models.fields.CharField', [], {'max_length': '3', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'middle_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '35'}),
'phone_country_code': ('django.db.models.fields.CharField', [], {'max_length': '3', 'db_index': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '16', 'blank': 'True'}),
'processed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'salutation': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'state': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}),
'suffix': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'upload_error_message': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
'upload_status': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'unique': 'True'}),
'user_updated_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'})
},
'student.userprofile': {
'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"},
'courseware': ('django.db.models.fields.CharField', [], {'default': "'course.xml'", 'max_length': '255', 'blank': 'True'}),
'gender': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}),
'goals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'level_of_education': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}),
'location': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'mailing_address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}),
'year_of_birth': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
},
'student.usertestgroup': {
'Meta': {'object_name': 'UserTestGroup'},
'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': '32', 'db_index': 'True'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'db_index': 'True', 'symmetrical': 'False'})
}
}
complete_apps = ['student']
| agpl-3.0 |
simongoffin/my_odoo_tutorial | addons/hr_evaluation/report/hr_evaluation_report.py | 44 | 4676 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 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/>.
#
##############################################################################
from openerp import tools
from openerp.osv import fields, osv
class hr_evaluation_report(osv.Model):
_name = "hr.evaluation.report"
_description = "Evaluations Statistics"
_auto = False
_columns = {
'create_date': fields.date('Create Date', readonly=True),
'delay_date': fields.float('Delay to Start', digits=(16, 2), readonly=True),
'overpass_delay': fields.float('Overpassed Deadline', digits=(16, 2), readonly=True),
'day': fields.char('Day', size=128, readonly=True),
'deadline': fields.date("Deadline", readonly=True),
'request_id': fields.many2one('survey.user_input', 'Request_id', readonly=True),
'closed': fields.date("closed", readonly=True),
'year': fields.char('Year', size=4, readonly=True),
'month': fields.selection([('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'),
('05', 'May'), ('06', 'June'), ('07', 'July'), ('08', 'August'), ('09', 'September'),
('10', 'October'), ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
'plan_id': fields.many2one('hr_evaluation.plan', 'Plan', readonly=True),
'employee_id': fields.many2one('hr.employee', "Employee", readonly=True),
'rating': fields.selection([
('0', 'Significantly bellow expectations'),
('1', 'Did not meet expectations'),
('2', 'Meet expectations'),
('3', 'Exceeds expectations'),
('4', 'Significantly exceeds expectations'),
], "Overall Rating", readonly=True),
'nbr': fields.integer('# of Requests', readonly=True),
'state': fields.selection([
('draft', 'Draft'),
('wait', 'Plan In Progress'),
('progress', 'Final Validation'),
('done', 'Done'),
('cancel', 'Cancelled'),
], 'Status', readonly=True),
}
_order = 'create_date desc'
def init(self, cr):
tools.drop_view_if_exists(cr, 'hr_evaluation_report')
cr.execute("""
create or replace view hr_evaluation_report as (
select
min(l.id) as id,
date_trunc('day',s.create_date) as create_date,
to_char(s.create_date, 'YYYY-MM-DD') as day,
s.employee_id,
l.request_id,
s.plan_id,
s.rating,
s.date as deadline,
s.date_close as closed,
to_char(s.create_date, 'YYYY') as year,
to_char(s.create_date, 'MM') as month,
count(l.*) as nbr,
s.state,
avg(extract('epoch' from age(s.create_date,CURRENT_DATE)))/(3600*24) as delay_date,
avg(extract('epoch' from age(s.date,CURRENT_DATE)))/(3600*24) as overpass_delay
from
hr_evaluation_interview l
LEFT JOIN
hr_evaluation_evaluation s on (s.id=l.evaluation_id)
GROUP BY
s.create_date,
date_trunc('day',s.create_date),
to_char(s.create_date, 'YYYY-MM-DD'),
to_char(s.create_date, 'YYYY'),
to_char(s.create_date, 'MM'),
s.state,
s.employee_id,
s.date,
s.date_close,
l.request_id,
s.rating,
s.plan_id
)
""")
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
calancha/DIRAC | Core/Utilities/test/TracedTests.py | 10 | 2744 | ########################################################################
# $HeadURL $
# File: TracedTests.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2012/08/08 15:21:32
########################################################################
""" :mod: TracedTests
=======================
.. module: TracedTests
:synopsis: Traced test cases
.. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com
Traced test cases
"""
__RCSID__ = "$Id $"
##
# @file TracedTests.py
# @author Krzysztof.Ciba@NOSPAMgmail.com
# @date 2012/08/08 15:21:44
# @brief Definition of TracedTests class.
## imports
import unittest
## SUT
from DIRAC.Core.Utilities.Traced import Traced, TracedDict, TracedList
########################################################################
class TracedTests(unittest.TestCase):
"""
.. class:: TracedTests
"""
def setUp( self ):
"""c'tor
:param self: self reference
"""
self.tracedDict = TracedDict( { 1 : 1 } )
self.tracedList = TracedList( [ 1 ] )
class TracedClass( object ):
__metaclass__ = Traced
classArg = None
def __init__( self ):
instanceArg = None
self.tracedClass = TracedClass()
def testTarcedDict( self ):
""" TracedDict tests """
self.assertEqual( self.tracedDict.updated(), [] )
## update, not changing value
self.tracedDict[1] = 1
self.assertEqual( self.tracedDict.updated(), [] )
## update, changing value
self.tracedDict[1] = 2
self.assertEqual( self.tracedDict.updated(), [1] )
## set new
self.tracedDict[2] = 2
self.assertEqual( self.tracedDict.updated(), [ 1, 2 ] )
## update from diff dict
self.tracedDict.update( { 3: 3 } )
self.assertEqual( self.tracedDict.updated(), [ 1, 2, 3 ] )
def testTracedList( self ):
""" traced list """
self.assertEqual( self.tracedList.updated(), [] )
## no value change
self.tracedList[0] = 1
self.assertEqual( self.tracedList.updated(), [] )
## value change
self.tracedList[0] = 2
self.assertEqual( self.tracedList.updated(), [0] )
## append
self.tracedList.append( 1 )
self.assertEqual( self.tracedList.updated(), [0, 1] )
def testTracedClass( self ):
""" traced class """
self.assertEqual( self.tracedClass.updated(), [] )
self.tracedClass.instanceArg = 1
self.assertEqual( self.tracedClass.updated(), [ "instanceArg" ] )
self.tracedClass.classArg = 1
self.assertEqual( self.tracedClass.updated(), [ "instanceArg" , "classArg" ] )
## test execution
if __name__ == "__main__":
TESTLOADER = unittest.TestLoader()
SUITE = TESTLOADER.loadTestsFromTestCase( TracedTests )
unittest.TextTestRunner(verbosity=3).run( SUITE )
| gpl-3.0 |
rareimagery/budhoundapp | sites/all/libraries/twilio/docs/_themes/flask_theme_support.py | 2228 | 4875 | # flasky extensions. flasky pygments style based on tango style
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
class FlaskyStyle(Style):
background_color = "#f8f8f8"
default_style = ""
styles = {
# No corresponding class for the following:
#Text: "", # class: ''
Whitespace: "underline #f8f8f8", # class: 'w'
Error: "#a40000 border:#ef2929", # class: 'err'
Other: "#000000", # class 'x'
Comment: "italic #8f5902", # class: 'c'
Comment.Preproc: "noitalic", # class: 'cp'
Keyword: "bold #004461", # class: 'k'
Keyword.Constant: "bold #004461", # class: 'kc'
Keyword.Declaration: "bold #004461", # class: 'kd'
Keyword.Namespace: "bold #004461", # class: 'kn'
Keyword.Pseudo: "bold #004461", # class: 'kp'
Keyword.Reserved: "bold #004461", # class: 'kr'
Keyword.Type: "bold #004461", # class: 'kt'
Operator: "#582800", # class: 'o'
Operator.Word: "bold #004461", # class: 'ow' - like keywords
Punctuation: "bold #000000", # class: 'p'
# because special names such as Name.Class, Name.Function, etc.
# are not recognized as such later in the parsing, we choose them
# to look the same as ordinary variables.
Name: "#000000", # class: 'n'
Name.Attribute: "#c4a000", # class: 'na' - to be revised
Name.Builtin: "#004461", # class: 'nb'
Name.Builtin.Pseudo: "#3465a4", # class: 'bp'
Name.Class: "#000000", # class: 'nc' - to be revised
Name.Constant: "#000000", # class: 'no' - to be revised
Name.Decorator: "#888", # class: 'nd' - to be revised
Name.Entity: "#ce5c00", # class: 'ni'
Name.Exception: "bold #cc0000", # class: 'ne'
Name.Function: "#000000", # class: 'nf'
Name.Property: "#000000", # class: 'py'
Name.Label: "#f57900", # class: 'nl'
Name.Namespace: "#000000", # class: 'nn' - to be revised
Name.Other: "#000000", # class: 'nx'
Name.Tag: "bold #004461", # class: 'nt' - like a keyword
Name.Variable: "#000000", # class: 'nv' - to be revised
Name.Variable.Class: "#000000", # class: 'vc' - to be revised
Name.Variable.Global: "#000000", # class: 'vg' - to be revised
Name.Variable.Instance: "#000000", # class: 'vi' - to be revised
Number: "#990000", # class: 'm'
Literal: "#000000", # class: 'l'
Literal.Date: "#000000", # class: 'ld'
String: "#4e9a06", # class: 's'
String.Backtick: "#4e9a06", # class: 'sb'
String.Char: "#4e9a06", # class: 'sc'
String.Doc: "italic #8f5902", # class: 'sd' - like a comment
String.Double: "#4e9a06", # class: 's2'
String.Escape: "#4e9a06", # class: 'se'
String.Heredoc: "#4e9a06", # class: 'sh'
String.Interpol: "#4e9a06", # class: 'si'
String.Other: "#4e9a06", # class: 'sx'
String.Regex: "#4e9a06", # class: 'sr'
String.Single: "#4e9a06", # class: 's1'
String.Symbol: "#4e9a06", # class: 'ss'
Generic: "#000000", # class: 'g'
Generic.Deleted: "#a40000", # class: 'gd'
Generic.Emph: "italic #000000", # class: 'ge'
Generic.Error: "#ef2929", # class: 'gr'
Generic.Heading: "bold #000080", # class: 'gh'
Generic.Inserted: "#00A000", # class: 'gi'
Generic.Output: "#888", # class: 'go'
Generic.Prompt: "#745334", # class: 'gp'
Generic.Strong: "bold #000000", # class: 'gs'
Generic.Subheading: "bold #800080", # class: 'gu'
Generic.Traceback: "bold #a40000", # class: 'gt'
}
| gpl-2.0 |
joshmoore/openmicroscopy | components/tools/OmeroPy/test/integration/emanScripts.py | 4 | 24635 | #!/usr/bin/env python
"""
Integration test for testing various EMAN2 scripts functionality.
Not all of the scripts are covered. E.g ctf.py, openInChimera.py, eman2omero.py, either because they are
too tricky to test or because they cover very similar functionality to other scripts tested below.
dir(self)
'assertAlmostEqual', 'assertAlmostEquals', 'assertEqual', 'assertEquals', 'assertFalse', 'assertNotAlmostEqual', 'assertNotAlmostEquals',
'assertNotEqual', 'assertNotEquals', 'assertRaises', 'assertTrue', 'assert_', 'client', 'countTestCases', 'debug', 'defaultTestResult',
'fail', 'failIf', 'failIfAlmostEqual', 'failIfEqual', 'failUnless', 'failUnlessAlmostEqual', 'failUnlessEqual', 'failUnlessRaises',
'failureException', 'id', 'login_args', 'new_user', 'query', 'root', 'run', 'setUp', 'sf', 'shortDescription', 'tearDown', 'testfoo',
'tmpfile', 'tmpfiles', 'update'
** IMPORTANT: Run test from OmeroPy/ **
PYTHONPATH=$PYTHONPATH:.:test:build/lib ICE_CONFIG=/Users/will/Documents/workspace/Omero/etc/ice.config python integration/emanScripts.py
Add E.g. TestEmanScripts.testRunSpiderProcedure to command to run a single test.
"""
import unittest, time
#import test.integration.library as lib
import integration.library as lib
import omero
import omero.clients
from omero.rtypes import *
from omero_model_ExperimenterI import ExperimenterI
from omero_model_ExperimenterGroupI import ExperimenterGroupI
from omero_model_PermissionsI import PermissionsI
import omero.util.script_utils as scriptUtil
import omero.scripts
from omero import ApiUsageException
import os
import numpy
try:
from PIL import Image, ImageDraw # see ticket:2597
except ImportError:
import Image, ImageDraw # see ticket:2597
try:
from EMAN2 import *
except ImportError:
print "Install EMAN2 for tests to pass!!!"
boxerTestImage = "/Users/will/Documents/biology-data/testData/boxerTest.tiff"
smallTestImage = "/Users/will/Documents/biology-data/testData/smallTest.tiff"
runSpiderScriptPath = "scripts/EMAN2/Run_Spider_Procedure.py"
saveImageAsScriptPath = "scripts/EMAN2/Save_Image_As_Em.py"
export2emScriptPath = "scripts/EMAN2/export2em.py"
boxerScriptPath = "scripts/EMAN2/Auto_Boxer.py"
imagesFromRoisPath = "scripts/omero/util_scripts/Images_From_ROIs.py"
emanFiltersScript = "scripts/EMAN2/Eman_Filters.py"
class TestEmanScripts(lib.ITest):
def testFilterScript(self):
print "testFilterScript"
# root session is root.sf
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
admin = self.root.sf.getAdminService()
# run as root
session = self.root.sf
client = self.root
# upload script
scriptService = session.getScriptService()
scriptId = self.uploadScript(scriptService, emanFiltersScript)
# services
updateService = session.getUpdateService()
containerService = session.getContainerService()
try:
a=test_image()
planeData = EMNumPy.em2numpy(a)
except:
print "Couldn't create EMAN2 test image. EMAN2 import failed?"
return
image = importImage(session, None, "filterTestImage", planeData)
imageId = image.getId().getValue()
# put image in dataset and project
# create dataset
dataset = omero.model.DatasetI()
dsName = "emanFilters-test"
dataset.name = rstring(dsName)
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring("emanFilters-test")
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
# put image in dataset
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(imageId, False)
updateService.saveAndReturnObject(dlink)
# run script with all parameters. See http://blake.bcm.edu/emanwiki/Eman2ProgQuickstart
newDatasetName = "filter-results"
filterParams = {"sigma": omero.rtypes.rstring('0.125')}
argMap = {"IDs":omero.rtypes.rlist([dataset.id]), # process these images
"Data_Type": omero.rtypes.rstring("Dataset"),
"Filter_Name":omero.rtypes.rstring("filter.lowpass.gauss"), # using this filter
"Filter_Params":omero.rtypes.rmap(filterParams), # additional params
"New_Dataset_Name": omero.rtypes.rstring(newDatasetName), # optional: put results in new dataset
}
runScript(scriptService, client, scriptId, argMap)
# try with minimal parameters - put results into same dataset.
imageIds = [omero.rtypes.rlong(imageId)]
aMap = {"IDs":omero.rtypes.rlist(imageIds), # process these images
"Data_Type": omero.rtypes.rstring("Image"),
"Filter_Name":omero.rtypes.rstring("normalize"), # using this filter - no params
}
runScript(scriptService, client, scriptId, aMap)
rMap = {"IDs":omero.rtypes.rlist(imageIds), # process these images
"Data_Type": omero.rtypes.rstring("Image"),
"Filter_Name":omero.rtypes.rstring("normalize.edgemean"), # using this filter - no params
}
runScript(scriptService, client, scriptId, rMap)
# should now have 2 datasets in the project above...
pros = containerService.loadContainerHierarchy("Project", [project.id.val], None)
datasetFound = False
for p in pros:
self.assertEquals(2, len(p.linkedDatasetList())) # 2 datasets
for ds in p.linkedDatasetList():
# new dataset should have 1 image
if ds.name.val == newDatasetName:
datasetFound = True
iList = containerService.getImages("Dataset", [ds.id.val], None)
self.assertEquals(1, len(iList))
else:
# existing dataset should have 3 images.
self.assertEquals(ds.name.val, dsName)
iList = containerService.getImages("Dataset", [ds.id.val], None)
self.assertEquals(3, len(iList))
self.assertTrue(datasetFound, "No dataset found with EMAN-filtered images")
def testImagesFromRois(self):
"""
Uploads an image, adds rectangle ROIs, then runs the imagesFromRois.py script to generate
new images in a dataset. Then we check that the dataset exists with the expected number of images.
"""
print "testImagesFromRois"
# root session is root.sf
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
admin = self.root.sf.getAdminService()
# upload script as root
scriptService = self.root.sf.getScriptService()
scriptId = self.uploadScript(scriptService, imagesFromRoisPath)
# run as root
session = self.root.sf
client = self.root
# create user services
roiService = session.getRoiService()
queryService = session.getQueryService()
updateService = session.getUpdateService()
containerService = session.getContainerService()
# import image and manually add rois
imagePath = boxerTestImage
imageName = "roi2imageTest"
image = importImage(session, imagePath, imageName)
iId = image.getId().getValue()
x, y, width, height = (1355, 600, 320, 325)
addRectangleRoi(updateService, x, y, width, height, image)
x, y, width, height = (890, 200, 310, 330)
addRectangleRoi(updateService, x, y, width, height, image)
# put image in dataset and project
# create dataset
dataset = omero.model.DatasetI()
dataset.name = rstring("imagesFromRoi-test")
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring("imagesFromRoi-test")
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
# put image in dataset
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(image.id.val, False)
updateService.saveAndReturnObject(dlink)
containerName = "particles"
ids = [omero.rtypes.rlong(iId), ]
argMap = {
"Image_IDs": omero.rtypes.rlist(ids),
"Container_Name": rstring(containerName),
}
runScript(scriptService, client, scriptId, argMap)
# now we should have a dataset with 2 images, in project
newDatasetName = containerName
pros = containerService.loadContainerHierarchy("Project", [project.id.val], None)
datasetFound = False
for p in pros:
for ds in p.linkedDatasetList():
if ds.name.val == newDatasetName:
datasetFound = True
dsId = ds.id.val
iList = containerService.getImages("Dataset", [dsId], None)
self.assertEquals(2, len(iList))
self.assertTrue(datasetFound, "No dataset: %s found with images from ROIs" % newDatasetName)
def testBoxer(self):
"""
Uploads a single particle image (path defined below)
Then adds ROIs for a couple of user-picked particles. These match the test image.
The 'root' uploads the "boxer.py" script, and it is run by a regular
user, to add auto-picked particles as ROIs to the image.
This test, including running of script takes > 2 mins!
"""
print "testBoxer"
# root session is root.sf
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
admin = self.root.sf.getAdminService()
# run as root
client = self.root
session = self.root.sf
# create user services
updateService = session.getUpdateService()
roiService = session.getRoiService()
# import image and manually pick particles.
imagePath = boxerTestImage
image = importImage(session, imagePath)
iId = image.getId().getValue()
x, y, width, height = (1355, 600, 320, 325) # script should re-size to 330
addRectangleRoi(updateService, x, y, width, height, image)
x, y, width, height = (890, 200, 310, 330)
addRectangleRoi(updateService, x, y, width, height, image)
# put image in dataset and project
# create dataset
dataset = omero.model.DatasetI()
dataset.name = rstring("boxer-test")
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring("boxer-test")
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
# put image in dataset
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(image.id.val, False)
updateService.saveAndReturnObject(dlink)
# upload (as root) and run the boxer.py script as user
scriptService = self.root.sf.getScriptService()
scriptId = self.uploadScript(scriptService, boxerScriptPath)
ids = [omero.rtypes.rlong(iId), ]
argMap = {"Image_IDs": omero.rtypes.rlist(ids),}
runScript(scriptService, client, scriptId, argMap)
# if the script ran OK, we should have more than the 2 ROIs we added above
result = roiService.findByImage(iId, None)
rectCount = 0
for roi in result.rois:
for shape in roi.copyShapes():
if type(shape) == omero.model.RectI:
width = shape.getWidth().getValue()
height = shape.getHeight().getValue()
self.assertEquals(330, width)
self.assertEquals(330, height)
rectCount += 1
self.assertTrue(rectCount > 2, "No ROIs added by boxer.py script")
def testExport2Em(self):
"""
Tests the export2em.py command-line script by creating an image in OMERO, then
running the export2em.py script from command line and checking that an image has been exported.
The saveImageAs.py script is first uploaded to the scripting service, since this is required by export2em.py
"""
print "testExport2Em"
# root session is root.sf
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
admin = self.root.sf.getAdminService()
# upload saveImageAs.py script as root
scriptService = self.root.sf.getScriptService()
scriptId = self.uploadScript(scriptService, saveImageAsScriptPath)
# upload image as root, since only root has only root has permission to run
# export2em.py because it uses the scripting service to look up the 'saveImageAs.py'
# script we just uploaded as root.
session = self.root.sf
updateService = session.getUpdateService()
# import image into dataset and project
iId = importImage(session, smallTestImage).getId().getValue()
imageName = os.path.basename(smallTestImage)
# create dataset
dataset = omero.model.DatasetI()
dataset.name = rstring("export2em-test")
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring("export2em-test")
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
# put image in dataset
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(iId, False)
updateService.saveAndReturnObject(dlink)
extension = "png"
commandArgs = []
commandArgs.append("python %s" % export2emScriptPath)
commandArgs.append("-h localhost")
#commandArgs.append("-u %s" % new_exp.omeName.val)
commandArgs.append("-u root")
commandArgs.append("-p omero")
commandArgs.append("-i %s" % iId)
commandArgs.append("-e %s" % extension)
commandString = " ".join(commandArgs)
if not imageName.endswith(".%s" % extension):
imageName = "%s.%s" % (imageName, extension)
self.assertFalse(os.path.exists(imageName)) # make sure we start with no file
# run from command line
os.system(commandString)
# the downloaded file should be local. Try to find and open it.
self.assertTrue(os.path.exists(imageName))
# import again to test
try:
a=EMData()
a.read_image(imageName)
planeData = EMNumPy.em2numpy(a)
except:
print "Couldn't create EMAN2 test image. EMAN2 import failed?"
return
reImportId = importImage(session, None, imageName, planeData).getId().getValue()
#reImportId = importImage(session, imageName)
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(reImportId, False)
updateService.saveAndReturnObject(dlink)
os.remove(imageName)
def testRunSpiderProcedure(self):
"""
Tests the runSpiderProcedure.py script by uploading a simple Spider Procedure File (spf) to
OMERO as an Original File, creating an image in OMERO, then
running the export2em.py script from command line and checking that an image has been exported.
The saveImageAs.py script is first uploaded to the scripting service, since this is required by export2em.py
"""
print "testRunSpiderProcedure"
# root session is root.sf
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
admin = self.root.sf.getAdminService()
# upload saveImageAs.py script as root
scriptService = self.root.sf.getScriptService()
scriptId = self.uploadScript(scriptService, runSpiderScriptPath)
session = self.root.sf # do everything as root for now
# create services
queryService = session.getQueryService()
updateService = session.getUpdateService()
rawFileStore = session.createRawFileStore()
containerService = session.getContainerService()
# import image
image = importImage(session, smallTestImage)
iId = image.getId().getValue()
# put image in dataset and project
# create dataset
dataset = omero.model.DatasetI()
dataset.name = rstring("spider-test")
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring("spider-test")
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
# put image in dataset
dlink = omero.model.DatasetImageLinkI()
dlink.parent = omero.model.DatasetI(dataset.id.val, False)
dlink.child = omero.model.ImageI(image.id.val, False)
updateService.saveAndReturnObject(dlink)
# create and upload a Spider Procedure File
# make a temp text file. Example from http://www.wadsworth.org/spider_doc/spider/docs/quickstart.html
f = open("spider.spf", 'w')
f.write("RT\n")
f.write("test001\n")
f.write("rot001\n")
f.write("60\n")
f.write("\n")
f.write("IP\n")
f.write("rot001\n")
f.write("big001\n")
f.write("150,150\n")
f.write("\n")
f.write("WI\n")
f.write("big001\n")
f.write("win001\n")
f.write("75,75\n")
f.write("1,75\n")
f.write("\n")
f.write("EN D")
f.close()
fileAnnot = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, image, "spider.spf", "text/plain")
os.remove("spider.spf")
newDatasetName = "spider-results"
# run script
ids = [omero.rtypes.rlong(iId), ]
argMap = {"IDs":omero.rtypes.rlist(ids), # process these images
"Data_Type": omero.rtypes.rstring("Image"),
"Spf": omero.rtypes.rstring(str(fileAnnot.id.val)),
"New_Dataset_Name": omero.rtypes.rstring(newDatasetName),
"Input_Name": omero.rtypes.rstring("test001"),
"Output_Name": omero.rtypes.rstring("win001")}
runScript(scriptService, self.root, scriptId, argMap)
# check that image has been created.
# now we should have a dataset with 1 image, in project
pros = containerService.loadContainerHierarchy("Project", [project.id.val], None)
datasetFound = False
for p in pros:
for ds in p.linkedDatasetList():
if ds.name.val == newDatasetName:
datasetFound = True
dsId = ds.id.val
iList = containerService.getImages("Dataset", [dsId], None)
self.assertEquals(1, len(iList))
self.assertTrue(datasetFound, "No dataset found with images from ROIs")
def uploadScript(self, scriptService, scriptPath):
file = open(scriptPath)
scriptText = file.read()
file.close()
#try:
uuid = self.root.sf.getAdminService().getEventContext().sessionUuid
path = "%s/%s" % (uuid, scriptPath)
scriptId = scriptService.uploadOfficialScript(path, scriptText)
return scriptId
def runScript(scriptService, client, scriptId, argMap, returnKey=None):
# The last parameter is how long to wait as an RInt
proc = scriptService.runScript(scriptId, argMap, None)
try:
cb = omero.scripts.ProcessCallbackI(client, proc)
while not cb.block(1000): # ms.
pass
cb.close()
results = proc.getResults(0) # ms
finally:
proc.close(False)
if 'stderr' in results:
origFile = results['stderr'].getValue()
# But, we still get stderr from EMAN2 import (duplicate numpy etc.)
print "Script generated StdErr in file:" , origFile.getId().getValue()
if returnKey and returnKey in results:
return results[returnKey]
def editScript(scriptService, scriptPath):
file = open(scriptPath)
scriptText = file.read()
file.close()
scriptPath = scriptPath.replace("scripts/EMAN2", "/EMAN2") # convert scripts/EMAN2/script.py to /EMAN2/scripts.py
# need the script Original File to edit
scripts = scriptService.getScripts()
if not scriptPath.startswith("/"): scriptPath = "/" + scriptPath
namedScripts = [s for s in scripts if s.path.val + s.name.val == scriptPath]
script = namedScripts[-1]
#print "Editing script:", scriptPath
scriptService.editScript(script, scriptText)
return script.id.val
def addRectangleRoi(updateService, x, y, width, height, image):
"""
Adds a Rectangle (particle) to the current OMERO image, at point x, y.
Uses the self.image (OMERO image) and self.updateService
"""
# create an ROI, add the rectangle and save
roi = omero.model.RoiI()
roi.setImage(image)
r = updateService.saveAndReturnObject(roi)
# create and save a rectangle shape
rect = omero.model.RectI()
rect.x = rdouble(x)
rect.y = rdouble(y)
rect.width = rdouble(width)
rect.height = rdouble(height)
rect.theZ = rint(0)
rect.theT = rint(0)
rect.locked = rbool(True) # don't allow editing
rect.strokeWidth = rint(6)
# link the rectangle to the ROI and save it
rect.setRoi(r)
r.addShape(rect)
updateService.saveAndReturnObject(rect)
def getPlaneFromImage(imagePath):
"""
Reads a local image (E.g. single plane tiff) and returns it as a numpy 2D array.
@param imagePath Path to image.
"""
i = Image.open(imagePath)
a = numpy.asarray(i)
return a
def importImage(session, imagePath, imageName=None, planeData=None):
if imagePath != None:
data = getPlaneFromImage(imagePath)
if len(data.shape) == 3:
plane2D = data[0] # this actually slices the wrong way. E.g. Gives a row with 3 channels.
else: plane2D = data
else:
plane2D = planeData
if imageName == None:
imageName = imagePath
image = scriptUtil.createNewImage(session, [plane2D], imageName, "description", dataset=None)
return image
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
alshedivat/tensorflow | tensorflow/tools/common/test_module1.py | 61 | 1045 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A module target for TraverseTest.test_module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.tools.common import test_module2
class ModuleClass1(object):
def __init__(self):
self._m2 = test_module2.ModuleClass2()
def __model_class1_method__(self):
pass
| apache-2.0 |
Muterra/py_golix | golix/cipher.py | 2 | 43384 | '''
LICENSING
-------------------------------------------------
golix: A python library for Golix protocol object manipulation.
Copyright (C) 2016 Muterra, Inc.
Contributors
------------
Nick Badger
badg@muterra.io | badg@nickbadger.com | nickbadger.com
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
------------------------------------------------------
A NOTE ON RANDOM NUMBERS...
PyCryptoDome sources randomness from os.urandom(). This should be secure
for most applications. HOWEVER, if your system is low on entropy (can
be an issue in high-demand applications like servers), urandom *will not
block to wait for entropy*, and will revert (ish?) to potentially
insufficiently secure pseudorandom generation. In that case, it might be
better to source from elsewhere (like a hardware RNG).
Some initial temporary thoughts:
1. Need to refactor signing, etc into identities.
2. Identity base class should declare supported cipher suites as a set
3. Each identity class should += the set with their support, allowing
for easy multi-inheritance for multiple identity support
4. Identities then insert the author into the file
5. How does this interact with asymmetric objects with symmetric sigs?
Should just look for an instance of the object? It would be nice
to totally factor crypto awareness out of the objects entirely,
except (of course) for address algorithms.
6. From within python, should the identies be forced to ONLY support
a single ciphersuite? That would certainly make life easier. A
LOT easier. Yeah, let's do that then. Multi-CS identities can
multi-subclass, and will need to add some kind of glue code for
key reuse. Deal with that later, but it'll probably entail
backwards-incompatible changes.
7. Then, the identities should also generate secrets. That will also
remove people from screwing up and using ex. random.random().
But what to do with the API for that? Should identity.finalize(obj)
return (key, obj) pair or something? That's not going to be useful
for all objects though, because not all objects use secrets. Really,
the question is, how to handle GEOCs in a way that makes sense?
Maybe add an Identity.secrets(ghid) attribute or summat? Though
returning just the bytes would be really unfortunate for app
development, because you'd have to unpack the generated bytes to
figure out the ghid. What about returning a namedtuple, and adding
a field for secrets in the GEOC? that might be something to add
to the actual objects (ex GEOC) instead of the identity. That would
also reduce the burden on identities for state management of
generated objects, which should really be handled at a higher level
than this library.
8. Algorithm precedence order should be defined globally, but capable
of being overwritten
'''
# Global dependencies
import abc
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import hmac
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import ciphers
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.kdf import hkdf
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from donna25519 import PrivateKey as ECDHPrivate
from donna25519 import PublicKey as ECDHPublic
from smartyparse import ParseError
# Interpackage dependencies
from .exceptions import SecurityError
from .utils import Ghid
from .utils import _dummy_ghid
from .crypto_utils import ADDRESS_ALGOS
from .crypto_utils import Secret
from .crypto_utils import AsymHandshake
from .crypto_utils import AsymAck
from .crypto_utils import AsymNak
from .crypto_utils import _dummy_asym
from .crypto_utils import _dummy_mac
from .crypto_utils import _dummy_signature
from .crypto_utils import _dummy_address
from .crypto_utils import _dummy_pubkey
from .crypto_utils import _dummy_pubkey_exchange
from ._getlow import GIDC
from ._getlow import GEOC
from ._getlow import GOBS
from ._getlow import GOBD
from ._getlow import GDXX
from ._getlow import GARQ
from ._getlow import GARQHandshake
from ._getlow import GARQAck
from ._getlow import GARQNak
# Some globals
CRYPTO_BACKEND = default_backend()
DEFAULT_ADDRESSER = 1
DEFAULT_CIPHER = 1
# Control * imports
__all__ = [
'FirstParty1',
'SecondParty1',
'ThirdParty1'
]
# Some utilities
class _NoopSHA512(hashes.SHA512):
def __init__(self, noopdata, *args, **kwargs):
self.__data = noopdata
super().__init__(*args, **kwargs)
self.algorithm = self
def copy(self):
''' Total NOOP, because self cannot change.
'''
return self
def update(self, data):
# Noop noop noop
pass
def finalize(self):
# Yay we get to do something!
return self.__data
class _IdentityBase(metaclass=abc.ABCMeta):
def __init__(self, keys, ghid):
self._ghid = ghid
try:
self._signature_key = keys['signature']
self._encryption_key = keys['encryption']
self._exchange_key = keys['exchange']
except (KeyError, TypeError) as e:
raise RuntimeError(
'Generating ID from existing keys requires dict-like obj '
'with "signature", "encryption", and "exchange" keys.'
) from e
@property
def ghid(self):
return self._ghid
@property
def ciphersuite(self):
return self._ciphersuite
@classmethod
def _dispatch_address(cls, address_algo):
if address_algo == 'default':
address_algo = cls.DEFAULT_ADDRESS_ALGO
elif address_algo not in ADDRESS_ALGOS:
raise ValueError(
'Address algorithm unavailable for use: ' + str(address_algo)
)
return address_algo
@classmethod
def _typecheck_secret(cls, secret):
# Awkward but gets the job done
if not isinstance(secret, Secret):
return False
if secret.cipher != cls._ciphersuite:
return False
return True
class _ObjectHandlerBase(metaclass=abc.ABCMeta):
''' Base class for anything that needs to unpack Golix objects.
'''
@staticmethod
def unpack_identity(packed):
gidc = GIDC.unpack(packed)
return gidc
@staticmethod
def unpack_container(packed):
geoc = GEOC.unpack(packed)
return geoc
@staticmethod
def unpack_bind_static(packed):
gobs = GOBS.unpack(packed)
return gobs
@staticmethod
def unpack_bind_dynamic(packed):
gobd = GOBD.unpack(packed)
return gobd
@staticmethod
def unpack_debind(packed):
gdxx = GDXX.unpack(packed)
return gdxx
@staticmethod
@abc.abstractmethod
def unpack_request(packed):
''' Unpacks requests. Different for firstparties and
thirdparties, but used by both in unpack_any.
'''
pass
def unpack_any(self, packed):
''' Try to unpack using any available parser.
Raises TypeError if no parser is found.
'''
for parser in (self.unpack_identity,
self.unpack_container,
self.unpack_bind_static,
self.unpack_bind_dynamic,
self.unpack_debind,
self.unpack_request):
try:
obj = parser(packed)
# Hm, don't really like this.
except (ParseError, TypeError):
pass
else:
break
else:
raise ParseError(
'Packed data does not appear to be a Golix object.'
)
return obj
class _SecondPartyBase(metaclass=abc.ABCMeta):
@classmethod
def from_keys(cls, keys, address_algo):
''' Creates a secondparty from unpacked keys -- DON'T use this
if you have an existing MIDC.
'''
try:
# Turn them into bytes first.
packed_keys = cls._pack_keys(keys)
except (KeyError, TypeError) as e:
raise RuntimeError(
'Generating ID from existing keys requires dict-like obj '
'with "signature", "encryption", and "exchange" keys.'
) from e
gidc = GIDC(
signature_key=packed_keys['signature'],
encryption_key=packed_keys['encryption'],
exchange_key=packed_keys['exchange']
)
gidc.pack(cipher=cls._ciphersuite, address_algo=address_algo)
ghid = gidc.ghid
self = cls(keys=keys, ghid=ghid)
self.packed = gidc.packed
return self
@classmethod
def from_identity(cls, gidc):
''' Loads an unpacked gidc into a SecondParty. Note that this
does not select the correct SecondParty for any given gidc's
ciphersuite.
'''
ghid = gidc.ghid
keys = cls._unpack_keys({
'signature': gidc.signature_key,
'encryption': gidc.encryption_key,
'exchange': gidc.exchange_key
})
self = cls(keys=keys, ghid=ghid)
return self
@classmethod
def from_packed(cls, packed):
''' Loads a packed gidc into a SecondParty. Also does not select
the correct SecondParty for the packed gidc's ciphersuite.
'''
gidc = _ObjectHandlerBase.unpack_identity(packed)
self = cls.from_identity(gidc)
self.packed = packed
return self
@classmethod
@abc.abstractmethod
def _pack_keys(cls, keys):
''' Convert self.keys from objects used for crypto operations
into bytes-like objects suitable for output into a GIDC.
'''
pass
@classmethod
@abc.abstractmethod
def _unpack_keys(cls, keys):
''' Convert keys dic into objects used for crypto operations
from bytes-like objects used in GIDC.
'''
pass
class _FirstPartyBase(_ObjectHandlerBase, metaclass=abc.ABCMeta):
DEFAULT_ADDRESS_ALGO = DEFAULT_ADDRESSER
def __init__(self, keys=None, ghid=None, address_algo='default', *args,
**kwargs):
self.address_algo = self._dispatch_address(address_algo)
# Load an existing identity
if keys is not None and ghid is not None:
self._second_party = self._generate_second_party(
keys,
self.address_algo
)
# Catch any improper declaration
elif keys is not None or ghid is not None:
raise TypeError(
'Generating an ID manually from existing keys requires '
'both keys and ghid.'
)
# Generate a new identity
else:
keys = self._generate_keys()
self._second_party = self._generate_second_party(
keys,
self.address_algo
)
ghid = self._second_party.ghid
# Now dispatch super() with the adjusted keys, ghid
super().__init__(keys=keys, ghid=ghid, *args, **kwargs)
@classmethod
def _typecheck_2ndparty(cls, obj):
# Type check the partner. Must be SecondPartyX or similar.
if not isinstance(obj, cls._2PID):
raise TypeError(
'Object must be a SecondParty of compatible type '
'with the FirstParty initiating the request/ack/nak.'
)
else:
return True
@property
def second_party(self):
# Note: this is going to error out if we're loading an identity, since
# we're not currently passing in the packed identity.
return self._second_party
def make_container(self, secret, plaintext):
if not self._typecheck_secret(secret):
raise TypeError(
'Secret must be a properly-formatted Secret compatible with '
'the current identity\'s declared ciphersuite.'
)
geoc = GEOC(author=self.ghid)
geoc.payload = self._encrypt(secret, plaintext)
geoc.pack(cipher=self.ciphersuite, address_algo=self.address_algo)
signature = self._sign(geoc.ghid.address)
geoc.pack_signature(signature)
return geoc
def make_bind_static(self, target):
gobs = GOBS(
binder = self.ghid,
target = target
)
gobs.pack(cipher=self.ciphersuite, address_algo=self.address_algo)
signature = self._sign(gobs.ghid.address)
gobs.pack_signature(signature)
return gobs
def make_bind_dynamic(self, counter, target_vector, ghid_dynamic=None):
gobd = GOBD(
binder = self.ghid,
counter = counter,
target_vector = target_vector,
ghid_dynamic = ghid_dynamic
)
gobd.pack(cipher=self.ciphersuite, address_algo=self.address_algo)
signature = self._sign(gobd.ghid.address)
gobd.pack_signature(signature)
return gobd
def make_debind(self, target):
gdxx = GDXX(
debinder = self.ghid,
target = target
)
gdxx.pack(cipher=self.ciphersuite, address_algo=self.address_algo)
signature = self._sign(gdxx.ghid.address)
gdxx.pack_signature(signature)
return gdxx
def make_handshake(self, secret, target):
return AsymHandshake(
author = self.ghid,
target = target,
secret = secret
)
def make_ack(self, target, status=0):
return AsymAck(
author = self.ghid,
target = target,
status = status
)
def make_nak(self, target, status=0):
return AsymNak(
author = self.ghid,
target = target,
status = status
)
def make_request(self, recipient, request):
self._typecheck_2ndparty(recipient)
# I'm actually okay with this performance hit, since it forces some
# level of type checking here. Which is, I think, in this case, good.
if isinstance(request, AsymHandshake):
request = GARQHandshake(
author = request.author,
target = request.target,
secret = request.secret
)
elif isinstance(request, AsymAck):
request = GARQAck(
author = request.author,
target = request.target,
status = request.status
)
elif isinstance(request, AsymNak):
request = GARQNak(
author = request.author,
target = request.target,
status = request.status
)
else:
raise TypeError(
'Request must be an AsymHandshake, AsymAck, or AsymNak '
'(or subclass thereof).'
)
request.pack()
plaintext = request.packed
# Convert the plaintext to a proper payload and create a garq from it
payload = self._encrypt_asym(recipient, plaintext)
del plaintext
garq = GARQ(
recipient = recipient.ghid,
payload = payload
)
# Pack 'er up and generate a MAC for it
garq.pack(cipher=self.ciphersuite, address_algo=self.address_algo)
garq.pack_signature(
self._mac(
key = self._derive_shared(recipient),
data = garq.ghid.address
)
)
return garq
@classmethod
def receive_container(cls, author, secret, container):
if not isinstance(container, GEOC):
raise TypeError(
'Container must be an unpacked GEOC, for example, as returned '
'from unpack_container.'
)
cls._typecheck_2ndparty(author)
signature = container.signature
cls._verify(author, signature, container.ghid.address)
plaintext = cls._decrypt(secret, container.payload)
# This will need to be converted into a namedtuple or something
return plaintext
@classmethod
def receive_bind_static(cls, binder, binding):
if not isinstance(binding, GOBS):
raise TypeError(
'Binding must be an unpacked GOBS, for example, as returned '
'from unpack_bind_static.'
)
cls._typecheck_2ndparty(binder)
signature = binding.signature
cls._verify(binder, signature, binding.ghid.address)
# This will need to be converted into a namedtuple or something
return binding.target
@classmethod
def receive_bind_dynamic(cls, binder, binding):
if not isinstance(binding, GOBD):
raise TypeError(
'Binding must be an unpacked GOBD, for example, as returned '
'from unpack_bind_dynamic.'
)
cls._typecheck_2ndparty(binder)
signature = binding.signature
cls._verify(binder, signature, binding.ghid.address)
# This will need to be converted into a namedtuple or something
return binding.target
@classmethod
def receive_debind(cls, debinder, debinding):
if not isinstance(debinding, GDXX):
raise TypeError(
'Debinding must be an unpacked GDXX, for example, as returned '
'from unpack_debind.'
)
cls._typecheck_2ndparty(debinder)
signature = debinding.signature
cls._verify(debinder, signature, debinding.ghid.address)
# This will need to be converted into a namedtuple or something
return debinding.target
def unpack_request(self, packed):
garq = GARQ.unpack(packed)
plaintext = self._decrypt_asym(garq.payload)
# Could do this with a loop, but it gets awkward when trying to
# assign stuff to the resulting object.
try:
unpacked = GARQHandshake.unpack(plaintext)
request = AsymHandshake(
author = unpacked.author,
target = unpacked.target,
secret = unpacked.secret
)
except ParseError:
try:
unpacked = GARQAck.unpack(plaintext)
request = AsymAck(
author = unpacked.author,
target = unpacked.target,
status = unpacked.status
)
except ParseError:
try:
unpacked = GARQNak.unpack(plaintext)
request = AsymNak(
author = unpacked.author,
target = unpacked.target,
status = unpacked.status
)
except ParseError:
raise SecurityError('Could not securely unpack request.')
garq._plaintext = request
garq._author = request.author
return garq
def receive_request(self, requestor, request):
''' Verifies the request and exposes its contents.
'''
# Typecheck all the things
self._typecheck_2ndparty(requestor)
# Also make sure the request is something we've already unpacked
if not isinstance(request, GARQ):
raise TypeError(
'Request must be an unpacked GARQ, as returned from '
'unpack_request.'
)
try:
plaintext = request._plaintext
except AttributeError as e:
raise TypeError(
'Request must be an unpacked GARQ, as returned from '
'unpack_request.'
) from e
self._verify_mac(
key = self._derive_shared(requestor),
data = request.ghid.address,
mac = request.signature
)
return plaintext
@classmethod
@abc.abstractmethod
def _generate_second_party(cls, keys, address_algo):
''' MUST ONLY be called when generating one from scratch, not
when loading one. Loading must always be done directly through
loading a SecondParty.
'''
pass
@abc.abstractmethod
def _generate_keys(self):
''' Create a set of keys for use in the identity.
Must return a mapping of keys with the following values:
{
'signature': <signature key>,
'encryption': <encryption key>,
'exchange': <exchange key>
}
In a form that is usable by the rest of the FirstParty
crypto functions (this is dependent on the individual class'
implementation, ex its crypto library).
'''
pass
@classmethod
@abc.abstractmethod
def new_secret(cls, *args, **kwargs):
''' Placeholder method to create new symmetric secret. Returns
a Secret().
'''
return Secret(cipher=cls._ciphersuite, *args, **kwargs)
@abc.abstractmethod
def _sign(self, data):
''' Placeholder signing method.
'''
pass
@abc.abstractmethod
def _verify(self, public, signature, data):
''' Verifies signature against data using SecondParty public.
raises SecurityError if verification fails.
returns True on success.
'''
pass
@abc.abstractmethod
def _encrypt_asym(self, public, data):
''' Placeholder asymmetric encryptor.
'''
pass
@abc.abstractmethod
def _decrypt_asym(self, data):
''' Placeholder asymmetric decryptor.
'''
pass
@classmethod
@abc.abstractmethod
def _decrypt(cls, secret, data):
''' Placeholder symmetric decryptor.
'''
pass
@classmethod
@abc.abstractmethod
def _encrypt(cls, secret, data):
''' Placeholder symmetric encryptor.
'''
pass
@abc.abstractmethod
def _derive_shared(self, partner):
''' Derive a shared secret (not necessarily a Secret!) with the
partner.
'''
pass
@classmethod
@abc.abstractmethod
def _mac(cls, key, data):
''' Generate a MAC for data using key.
'''
pass
@classmethod
@abc.abstractmethod
def _verify_mac(cls, key, mac, data):
''' Generate a MAC for data using key.
'''
pass
@abc.abstractmethod
def _serialize(self):
''' Convert private keys into a standardized format. Don't save,
just return a dictionary with bytes objects:
{
'ghid': self.ghid,
'signature': self._signature_key,
'encryption': self._encryption_key,
'exchange': self._exchange_key
}
(etc)
'''
pass
@classmethod
@abc.abstractmethod
def _from_serialized(cls, serialization):
''' Create an instance of the class from a dictionary as created
by cls._serialize.
'''
pass
class _ThirdPartyBase(_ObjectHandlerBase, metaclass=abc.ABCMeta):
''' Subclass this (on a per-ciphersuite basis) for servers, and
other parties that have no access to privileged information.
They can only verify.
'''
@property
def ciphersuite(self):
return self._ciphersuite
@classmethod
def _dispatch_address(cls, address_algo):
if address_algo == 'default':
address_algo = cls.DEFAULT_ADDRESS_ALGO
elif address_algo not in ADDRESS_ALGOS:
raise ValueError(
'Address algorithm unavailable for use: ' + str(address_algo)
)
return address_algo
@staticmethod
def unpack_object(packed):
''' Unpacks any Golix object.
'''
success = False
for golix_format in (GIDC, GEOC, GOBS, GOBD, GDXX, GARQ):
try:
obj = golix_format.unpack(packed)
success = True
# Hm, don't really like this.
except (ParseError, TypeError):
pass
if not success:
raise ParseError(
'Packed data does not appear to be a Golix object.'
)
return obj
@classmethod
def unpack_request(cls, packed):
''' Unpack public everything from a request.
(Cannot verify, at least for the existing ciphersuites, as of
2016-03).
'''
garq = GARQ.unpack(packed)
return garq
@classmethod
def verify_object(cls, second_party, obj):
''' Verifies the signature of any symmetric object (aka
everything except GARQ) against data.
raises TypeError if obj is an asymmetric object (or otherwise
unsupported).
raises SecurityError if verification fails.
returns True on success.
'''
if isinstance(obj, GEOC) or \
isinstance(obj, GOBS) or \
isinstance(obj, GOBD) or \
isinstance(obj, GDXX):
return cls._verify(
public = second_party,
signature = obj.signature,
data = obj.ghid.address
)
elif isinstance(obj, GARQ):
raise ValueError(
'Asymmetric objects cannot be verified by third parties. '
'They can only be verified by their recipients.'
)
elif isinstance(obj, GIDC):
raise ValueError(
'Identity containers are inherently un-verified.'
)
else:
raise TypeError('Obj must be a Golix object: GIDC, GEOC, etc.')
@classmethod
@abc.abstractmethod
def _verify(cls, public, signature, data):
''' Verifies signature against data using SecondParty public.
raises SecurityError if verification fails.
returns True on success.
'''
pass
class SecondParty0(_SecondPartyBase, _IdentityBase):
_ciphersuite = 0
@classmethod
def _pack_keys(cls, keys):
return keys
@classmethod
def _unpack_keys(cls, keys):
return keys
class FirstParty0(_FirstPartyBase, _IdentityBase):
''' FOR TESTING PURPOSES ONLY.
Entirely inoperative. Correct API, but ignores all input, creating
only a symbolic output.
NOTE THAT INHERITANCE ORDER MATTERS! Must be first a FirstParty,
and second an Identity.
'''
_ciphersuite = 0
_2PID = SecondParty0
# Well it's not exactly repeating yourself, though it does mean there
# are sorta two ways to perform decryption. Best practice = always decrypt
# using the author's SecondParty
@classmethod
def _generate_second_party(cls, keys, address_algo):
keys = {}
keys['signature'] = _dummy_pubkey
keys['encryption'] = _dummy_pubkey
keys['exchange'] = _dummy_pubkey_exchange
return cls._2PID.from_keys(keys, address_algo)
def _generate_keys(self):
keys = {}
keys['signature'] = _dummy_pubkey
keys['encryption'] = _dummy_pubkey
keys['exchange'] = _dummy_pubkey_exchange
return keys
def _serialize(self):
return {
'ghid': bytes(self.ghid),
'signature': self._signature_key,
'encryption': self._encryption_key,
'exchange': self._exchange_key
}
@classmethod
def _from_serialized(cls, serialization):
try:
ghid = Ghid.from_bytes(serialization['ghid'])
keys = {
'signature': serialization['signature'],
'encryption': serialization['encryption'],
'exchange': serialization['exchange']
}
except (TypeError, KeyError) as e:
raise TypeError(
'serialization must be compatible with _serialize.'
) from e
return cls(keys=keys, ghid=ghid)
@classmethod
def new_secret(cls):
''' Placeholder method to create new symmetric secret.
'''
return super().new_secret(key=bytes(32), seed=None)
def _sign(self, data):
''' Placeholder signing method.
Data must be bytes-like. Private key should be a dictionary
formatted with all necessary components for a private key (?).
'''
return _dummy_signature
@classmethod
def _verify(cls, public, signature, data):
''' Verifies an author's signature against bites. Errors out if
unsuccessful. Returns True if successful.
Data must be bytes-like. public_key should be a dictionary
formatted with all necessary components for a public key (?).
Signature must be bytes-like.
'''
cls._typecheck_2ndparty(public)
return True
def _encrypt_asym(self, public, data):
''' Placeholder asymmetric encryptor.
Data should be bytes-like. Public key should be a dictionary
formatted with all necessary components for a public key.
'''
self._typecheck_2ndparty(public)
return _dummy_asym
def _decrypt_asym(self, data):
''' Placeholder asymmetric decryptor.
Maybe add kwarguments do define what kind of internal object is
returned? That would be smart.
Or, even better, do an arbitrary object content, and then encode
what class of internal object to use there. That way, it's not
possible to accidentally encode secrets publicly, but you can
also emulate behavior of normal exchange.
Data should be bytes-like. Public key should be a dictionary
formatted with all necessary components for a public key.
'''
# Note that this will error out when trying to load components,
# since it's 100% an invalid declaration of internal content.
# But, it's a good starting point.
return _dummy_asym
@classmethod
def _decrypt(cls, secret, data):
''' Placeholder symmetric decryptor.
Data should be bytes-like. Key should be bytes-like.
'''
return data
@classmethod
def _encrypt(cls, secret, data):
''' Placeholder symmetric encryptor.
Data should be bytes-like. Key should be bytes-like.
'''
return data
def _derive_shared(self, partner):
''' Derive a shared secret with the partner.
'''
self._typecheck_2ndparty(partner)
return b'[[ Placeholder shared secret ]]'
@classmethod
def _mac(cls, key, data):
''' Generate a MAC for data using key.
'''
return _dummy_mac
@classmethod
def _verify_mac(cls, key, mac, data):
return True
class ThirdParty0(_ThirdPartyBase):
_ciphersuite = 0
# Note that, since this classmethod is from a different class, the
# cls passed internally will be FirstParty0, NOT ThirdParty0.
_verify = FirstParty0._verify
class SecondParty1(_SecondPartyBase, _IdentityBase):
_ciphersuite = 1
@classmethod
def _pack_keys(cls, keys):
packkeys = {
'signature': int.to_bytes(
keys['signature'].public_numbers().n,
length=512,
byteorder='big'),
'encryption': int.to_bytes(
keys['encryption'].public_numbers().n,
length=512,
byteorder='big'),
'exchange': keys['exchange'].public,
}
return packkeys
@classmethod
def _unpack_keys(cls, keys):
n_sig = int.from_bytes(keys['signature'], byteorder='big')
n_enc = int.from_bytes(keys['encryption'], byteorder='big')
nums_sig = rsa.RSAPublicNumbers(n=n_sig, e=65537)
nums_enc = rsa.RSAPublicNumbers(n=n_enc, e=65537)
unpackkeys = {
'signature': nums_sig.public_key(CRYPTO_BACKEND),
'encryption': nums_enc.public_key(CRYPTO_BACKEND),
'exchange': ECDHPublic(bytes(keys['exchange'])),
}
return unpackkeys
# RSA-PSS Signature salt length.
# Put these here because explicit is better than implicit!
_PSS_SALT_LENGTH = hashes.SHA512.digest_size
class FirstParty1(_FirstPartyBase, _IdentityBase):
''' ... Hmmm
'''
_ciphersuite = 1
_2PID = SecondParty1
# Well it's not exactly repeating yourself, though it does mean there
# are sorta two ways to perform decryption. Best practice = always decrypt
# using the author's SecondParty
@classmethod
def _generate_second_party(cls, keys, address_algo):
pubkeys = {
'signature': keys['signature'].public_key(),
'encryption': keys['encryption'].public_key(),
'exchange': keys['exchange'].get_public()
}
del keys
return cls._2PID.from_keys(keys=pubkeys, address_algo=address_algo)
@classmethod
def _generate_keys(cls):
keys = {}
keys['signature'] = rsa.generate_private_key(
public_exponent = 65537,
key_size = 4096,
backend = CRYPTO_BACKEND
)
keys['encryption'] = rsa.generate_private_key(
public_exponent = 65537,
key_size = 4096,
backend = CRYPTO_BACKEND
)
keys['exchange'] = ECDHPrivate()
return keys
def _serialize(self):
return {
'ghid': bytes(self.ghid),
'signature': self._signature_key.private_bytes(
encoding = serialization.Encoding.DER,
format = serialization.PrivateFormat.PKCS8,
encryption_algorithm = serialization.NoEncryption()
),
'encryption': self._encryption_key.private_bytes(
encoding = serialization.Encoding.DER,
format = serialization.PrivateFormat.PKCS8,
encryption_algorithm = serialization.NoEncryption()
),
'exchange': bytes(self._exchange_key.private)
}
@classmethod
def _from_serialized(cls, condensed):
try:
ghid = Ghid.from_bytes(condensed['ghid'])
keys = {
'signature': serialization.load_der_private_key(
data = condensed['signature'],
password = None,
backend = CRYPTO_BACKEND
),
'encryption': serialization.load_der_private_key(
data = condensed['encryption'],
password = None,
backend = CRYPTO_BACKEND
),
'exchange': ECDHPrivate.load(condensed['exchange'])
}
except (TypeError, KeyError) as e:
raise TypeError(
'serialization must be compatible with _serialize.'
) from e
return cls(keys=keys, ghid=ghid)
@classmethod
def new_secret(cls):
''' Returns a new secure Secret().
'''
key = os.urandom(32)
nonce = os.urandom(16)
return super().new_secret(key=key, seed=nonce)
@classmethod
def _encrypt(cls, secret, data):
''' Symmetric encryptor.
'''
# Could we do eg memoryview instead?
if not isinstance(data, bytes):
data = bytes(data)
instance = ciphers.Cipher(
ciphers.algorithms.AES(secret.key),
ciphers.modes.CTR(secret.seed),
backend = CRYPTO_BACKEND
)
worker = instance.encryptor()
return worker.update(data) + worker.finalize()
@classmethod
def _decrypt(cls, secret, data):
''' Symmetric decryptor.
Handle multiple ciphersuites by having a SecondParty for
whichever author created it, and calling their decrypt instead.
'''
# Could we do eg memoryview instead?
if not isinstance(data, bytes):
data = bytes(data)
instance = ciphers.Cipher(
ciphers.algorithms.AES(secret.key),
ciphers.modes.CTR(secret.seed),
backend = CRYPTO_BACKEND
)
worker = instance.decryptor()
return worker.update(data) + worker.finalize()
def _sign(self, data):
''' Signing method.
'''
signer = self._signature_key.signer(
padding.PSS(
mgf = padding.MGF1(hashes.SHA512()),
salt_length = _PSS_SALT_LENGTH
),
hashes.SHA512()
)
signer._hash_ctx = _NoopSHA512(data)
return signer.finalize()
# IT WOULD BE NICE TO BE ABLE TO USE THIS GRRRRRRRRRRRRRRRRRR
signature = self._signature_key.sign(
bytes(data),
padding.PSS(
mgf = padding.MGF1(hashes.SHA512()),
salt_length = _PSS_SALT_LENGTH
),
_NoopSHA512(data)
)
return signature
@classmethod
def _verify(cls, public, signature, data):
''' Verifies an author's signature against bites. Errors out if
unsuccessful. Returns True if successful.
Data must be bytes-like. public_key should be a dictionary
formatted with all necessary components for a public key (?).
Signature must be bytes-like.
'''
cls._typecheck_2ndparty(public)
try:
verifier = public._signature_key.verifier(
bytes(signature),
padding.PSS(
mgf = padding.MGF1(hashes.SHA512()),
salt_length = _PSS_SALT_LENGTH
),
hashes.SHA512()
)
verifier._hash_ctx = _NoopSHA512(data)
verifier.verify()
# IT WOULD BE NICE TO BE ABLE TO USE THIS TOO!!!! grumble grumble
# public._signature_key.verify(
# bytes(signature),
# bytes(data),
# padding.PSS(
# mgf = padding.MGF1(hashes.SHA512()),
# salt_length = _PSS_SALT_LENGTH
# ),
# _NoopSHA512(data)
# )
except InvalidSignature as exc:
raise SecurityError('Failed to verify signature.') from exc
return True
def _encrypt_asym(self, public, data):
''' Placeholder asymmetric encryptor.
Data should be bytes-like. Public key should be a dictionary
formatted with all necessary components for a public key.
'''
self._typecheck_2ndparty(public)
ciphertext = public._encryption_key.encrypt(
bytes(data),
padding.OAEP(
mgf = padding.MGF1(algorithm=hashes.SHA512()),
algorithm = hashes.SHA512(),
label = b''
)
)
return ciphertext
def _decrypt_asym(self, data):
''' Placeholder asymmetric decryptor.
'''
plaintext = self._encryption_key.decrypt(
bytes(data),
padding.OAEP(
mgf = padding.MGF1(algorithm=hashes.SHA512()),
algorithm = hashes.SHA512(),
label = b''
)
)
return plaintext
def _derive_shared(self, partner):
''' Derive a shared secret with the partner.
'''
# Call the donna25519 exchange method and return bytes
ecdh = self._exchange_key.do_exchange(partner._exchange_key)
# Get both of our addresses and then the bitwise XOR of them both
my_hash = self.ghid.address
their_hash = partner.ghid.address
salt = bytes([a ^ b for a, b in zip(my_hash, their_hash)])
instance = hkdf.HKDF(
algorithm = hashes.SHA512(),
length = hashes.SHA512.digest_size,
salt = salt,
info = b'',
backend = CRYPTO_BACKEND
)
key = instance.derive(ecdh)
# Might as well do this immediately, not that it really adds anything
del ecdh, my_hash, their_hash, salt
return key
@classmethod
def _mac(cls, key, data):
''' Generate a MAC for data using key.
'''
h = hmac.HMAC(
key,
hashes.SHA512(),
backend = CRYPTO_BACKEND
)
h.update(data)
return h.finalize()
@classmethod
def _verify_mac(cls, key, mac, data):
''' Verify an existing MAC.
'''
if not isinstance(mac, bytes):
mac = bytes(mac)
if not isinstance(data, bytes):
data = bytes(data)
h = hmac.HMAC(
key,
hashes.SHA512(),
backend = CRYPTO_BACKEND
)
h.update(data)
try:
h.verify(mac)
except InvalidSignature as exc:
raise SecurityError('Failed to verify MAC.') from exc
return True
class ThirdParty1(_ThirdPartyBase):
_ciphersuite = 1
# Note that, since this classmethod is from a different class, the
# cls passed internally will be FirstParty0, NOT ThirdParty0.
_verify = FirstParty1._verify
| unlicense |
ngkogkos/volatility-plugins | facebook_extractor.py | 1 | 18867 | """
@author: Nick Gk (@ngkogkos)
@license: The MIT License (MIT)
@contact: ngkogkos@protonmail.com
"""
# Volatility's stuff
import volatility.commands as commands
import volatility.scan as scan
import volatility.utils as utils
import volatility.addrspace as addrspace
import volatility.obj as obj
from volatility.renderers import TreeGrid
# Auxiliary modules
from hashlib import sha1
from datetime import datetime
import json
import pprint
import struct
# TO-DO:
#
def isprintable(s, codec='utf8'):
"""Checks where a character is Printable or not."""
try:
s.decode(codec)
except UnicodeDecodeError:
return False
else:
return True
class FacebookScanner(scan.BaseScanner):
"""Scans for needles inheriting from BaseScanner."""
checks = []
def __init__(self, needles=None):
self.needles = needles
self.checks = [("MultiStringFinderCheck", {'needles': needles})]
scan.BaseScanner.__init__(self)
def scan(self, address_space, offset=0, maxlen=None):
for offset in scan.BaseScanner.scan(self, address_space,
offset, maxlen):
yield offset
class FacebookFindOwner():
"""Finds the Facebook Account Owner's ID."""
def findowner(self, address_space):
start_tag = "/auth/user_data/fb_me_user{\"uid\":\""
stop_tag = "\",\"first_name\":\""
# Maintain a list of possible Owners!
uniqueOwnerIDs = []
scanner = FacebookScanner(needles=[start_tag])
for offset in scanner.scan(address_space):
fb_buff = address_space.read(offset+len(start_tag), 256)
iter1 = 0
while iter1 < len(fb_buff):
# Make sure that the owner's ID weren't found again,
# and also it is numerical and not some random rubbish
if fb_buff[iter1:iter1+len(stop_tag)] == stop_tag and \
fb_buff[:iter1].isdigit() and \
fb_buff[:iter1] not in uniqueOwnerIDs:
uniqueOwnerIDs.append(fb_buff[:iter1])
iter1 += 1
# This is in case more than 1 people logged in
# into facebook prior capturing the RAM dump
if len(uniqueOwnerIDs) > 1:
print "Found more than one possible Owner IDs: ",
print uniqueOwnerIDs
return "multipleids"
elif len(uniqueOwnerIDs) == 1:
return uniqueOwnerIDs[0]
else:
return "unknown"
class FacebookGrabInfo(commands.Command):
"""Carves the memory dump for Owner's personal info JSON struct."""
def __init__(self, config, *args, **kwargs):
commands.Command.__init__(self, config, *args, **kwargs)
config.add_option('format', short_option=None,
default='pretty', type='str',
help='Choose how this plugin should output the JSON results:\n'
'Accepted values: pretty, visualizer')
config.add_option("OID", short_option=None,
default=None, type='str',
help='Facebook ID of the logged in account aka owner\'s ID')
def calculate(self):
profileJsons = []
address_space = utils.load_as(self._config, astype='physical')
start_tag = "/auth/user_data/fb_me_user{\"uid\":\""
id_tag = "{\"uid\":\""
# There are 2 possible byte sequences that this JSON structure
# ends with in memory, so define both
stop_tag1 = "profile_picture_is_silhouette\":false}"
stop_tag2 = "profile_picture_is_silhouette\":true}"
if self._config.OID is None:
ownerID = FacebookFindOwner().findowner(address_space)
if ownerID == "unknown":
print "Could not find the owner's ID... Try to provide it with the oid paremeter!"
return "iderr"
elif ownerID == "multipleids":
print "Please specify the owner's id with the oid parameter, because multiple IDs were found!"
return "iderr"
elif self._config.OID is not None:
ownerID = self._config.OID
scanner = FacebookScanner(needles=[start_tag])
for offset in scanner.scan(address_space):
fb_buff = address_space.read(offset+len(start_tag)-len(id_tag), 4096)
idoffset = fb_buff[len(id_tag):].find("\"")
jsonOwnerID = fb_buff[len(id_tag):len(id_tag)+idoffset]
if ownerID != jsonOwnerID:
# Found JSON structure from different account,
# so just continue looking
continue
iter1 = 0
while iter1 < len(fb_buff):
if fb_buff[iter1:iter1+len(stop_tag1)] == stop_tag1 or \
fb_buff[iter1:iter1+len(stop_tag2)] == stop_tag2:
# Use a generic exception handler, because of
# random JSON looking artifacts or corrupted ones
try:
tmpJsonDes = json.loads(fb_buff[:iter1+len(stop_tag1)])
tempJson = fb_buff[:iter1+len(stop_tag1)]
if tempJson not in profileJsons:
profileJsons.append(tempJson)
except Exception as e:
break
iter1 += 1
# Yield only the longest json which will probably have more information
try:
return max(profileJsons, key=len)
except Exception as e:
return "err"
def render_text(self, outfd, data):
if data == "iderr":
return
if data == "err":
print "[ERROR] Couldn't find Facebook's user info JSON structure in dump.."
return
if self._config.FORMAT == "pretty":
pprint.pprint(json.loads(data))
elif self._config.FORMAT == "visualizer":
print data
print "\n[!] " + "You should definitely paste the above JSON data " \
"in an online JSON visualizer, like http://jsonviewer.stack.hu/"
else:
pprint.pprint(json.loads(data.next()))
return
class FacebookContacts(commands.Command):
"""Finds possible Facebook contacts"""
def __init__(self, config, *args, **kwargs):
commands.Command.__init__(self, config, *args, **kwargs)
config.add_option("OID", short_option=None,
default=None, type='str',
help='Facebook ID of the logged in account aka owner\'s ID')
self.contactsList = {}
def calculate(self):
address_space = utils.load_as(self._config, astype='physical')
if self._config.OID is None:
ownerID = FacebookFindOwner().findowner(address_space)
elif self._config.OID is not None:
ownerID = self._config.OID
# fbcontacts_tag = ("\x22\x75\x73\x65\x72\x5F\x6B\x65\x79\x22\x3A"
# "\x22\x46\x41\x43\x45\x42\x4F\x4F\x4B\x3A")
fbcontacts_tag = "\"user_key\":\"FACEBOOK:"
contactsScanner = FacebookScanner(needles=[fbcontacts_tag, ])
for offset in contactsScanner.scan(address_space):
contacts_buff = address_space.read(offset - (512/2), 512)
citer = 0
f1 = False
f2 = False
# Find JSON's starting and ending offsets
while citer < 512:
if contacts_buff[citer:citer + 9] == "{\"email\":":
conJsonStart = citer
f1 = True
if contacts_buff[citer:citer + 9] == ",\"name\":\"":
conJsonEnd = citer + 9
f2 = True
citer += 1
# Make sure this is a full JSON and not a corrupted one
if not (f1 and f2):
continue
for c in range(conJsonEnd, len(contacts_buff)):
if contacts_buff[c] == '"':
conJsonEnd = c + 2
# Sanity check in case start offset
# is higher than the end offset
if conJsonStart >= conJsonEnd:
continue
con = contacts_buff[conJsonStart:conJsonEnd]
try:
contactData = json.loads(con)
# Make sure its not a duplicate finding!
if not contactData.get("user_key") in self.contactsList:
self.contactsList[contactData.get("user_key")] = contactData
if contactData.get("user_key").split(":")[1] == ownerID:
contactOwnerID = contactData.get("user_key").split(":")[1] + " [OWNER]"
else:
contactOwnerID = contactData.get("user_key").split(":")[1]
contact = (contactOwnerID,
contactData.get("email"),
contactData.get("name"))
yield contact
# Handle this exception more properly?
except Exception as e:
continue
def unified_output(self, data):
return TreeGrid([("Facebook ID", str),
("Email Address", str),
("Full Name", str)],
self.generator(data))
def generator(self, data):
for uk, e, n in data:
try:
yield(0,
[str(uk),
str(e),
str(n)])
except Exception as e:
print "[ERROR] Something went bad: Facebook ID: " + uk + ", Email Address: " + e + ", Full Name: " + n
def render_text(self, outfd, data):
self.table_header(outfd, [("Facebook ID", "30"),
("Email Address", "50"),
("Full Name", "")])
for uk, e, n in data:
try:
self.table_row(outfd, uk, e, n)
except Exception as e:
print "[ERROR] Something went bad: Facebook ID: " + uk + ", Email Address: " + e + ", Full Name: " + n
def render_csv(self, outfd, data):
for uk, e, n in data:
outfd.write("{0},{1},{2}\n".format(uk, e, n))
class FacebookMessages(commands.Command):
"""Carves the memory for every message exchanged between the Owner and another contact"""
def convertToTimestamp(self, dt):
"""Convert a human readable datetime in timestamp"""
diff = dt - datetime(1970, 1, 1)
return int(diff.total_seconds())
def convertUnixTime(self, nsec):
""" Convert unix epoch time in nanoseconds to a date string """
try:
time_val = struct.pack("<I", nsec // 1000000000)
time_buf = addrspace.BufferAddressSpace(self._config, data=time_val)
time_obj = obj.Object("UnixTimeStamp", offset=0,
vm=time_buf, is_utc=True)
return time_obj
except Exception as e:
return None
def __init__(self, config, *args, **kwargs):
commands.Command.__init__(self, config, *args, **kwargs)
config.add_option("OID", short_option=None,
default=None, type='str',
help='(Owner ID) Facebook ID of the logged in account aka owner\'s ID')
config.add_option('CID', short_option=None,
default=None, type='str',
help='[Required] (Contact ID) Facebook ID of 2nd party chatting with the owner')
config.add_option('STRIP-DUPLICATES', short_option=None,
action='store_true', dest='duplicates',
help='Do not display duplicate messages')
config.add_option('BUFFER', short_option='b',
default=1024, type='int',
help='Look up chunk size for messages')
config.add_option('LOWYEAR', short_option=None,
default=2013, type='int',
help='Low year boundary')
config.add_option('HIGHYEAR', short_option=None,
default=2017, type='int',
help='High year boundary')
def calculate(self):
address_space = utils.load_as(self._config, astype='physical')
msgsDict = {}
foundItemsHashes = []
if self._config.OID is None:
ownerID = FacebookFindOwner().findowner(address_space)
if ownerID == "unknown":
print "Could not find the owner's ID... Try to provide it with the oid paremeter!"
return
elif ownerID == "multipleids":
print "Please specify the owner's id with the oid parameter, because multiple IDs were found!"
return
elif self._config.OID is not None:
ownerID = self._config.OID
if not self._config.CID:
print "The --cid argument is required!"
return
contactID = self._config.CID
fbchat_stop_tag = "{\"email\":\""
fbchat_start_tag = "ONE_TO_ONE:" + contactID + ":" + ownerID + "t"
scanner = FacebookScanner(needles=[fbchat_start_tag])
# Begin looking for possible messages
for offset in scanner.scan(address_space):
# Special case which could happen if needles are
# found in the very beginning of memory dump
if offset < self._config.BUFFER:
fb_buff = address_space.read(0+len(fbchat_start_tag), offset)
else:
fb_buff = address_space.read(offset+len(fbchat_start_tag), self._config.BUFFER)
# Build 2 timestamp lowyear and highyear variables
# for later usage
lowdt = datetime(int(self._config.LOWYEAR), 1, 1)
lowdt = self.convertToTimestamp(lowdt)
highdt = datetime(int(self._config.HIGHYEAR)+1, 1, 1)
highdt = self.convertToTimestamp(highdt)
iter1 = 0
boundByTimestampFlag = False
# Find the leftmost starting point of a message
while iter1 < len(fb_buff):
# If this is true it is very possible for this to be the unix
# timestamp and hence the message begins from this offset
try:
if any(not isprintable(fb_buff[iter1 + 0 + x]) for x in range(8)):
timestamp = fb_buff[iter1:iter1+8]
# Convert timestamp to int miliseconds
timestamp = int(timestamp.encode("hex"), 16)
# Check whether this messages timestamp is inside the specified time period
if int(str(timestamp)[:10]) >= lowdt and \
int(str(timestamp)[:10]) <= highdt:
boundByTimestampFlag = True
# Move i +8 positions ahead
# since the unix timestamp is 8bytes
iter1 += 8
break
except Exception as e:
break
iter1 += 1
# If the above limitations weren't met
# continue looking for messages
if not boundByTimestampFlag:
continue
# Find the rightmost ending point of a message
# In other words try to "capture" the message artifact
# inside left and right expected string sequences
boundByRightTagFlag = False
iter2 = iter1
while iter2 < len(fb_buff):
if fb_buff[iter2:iter2 + len(fbchat_stop_tag)] == fbchat_stop_tag:
boundByRightTagFlag = True
break
iter2 += 1
if not boundByRightTagFlag:
continue
# Find the sender of the message
iter3 = iter2 + len(fbchat_stop_tag)
fbchat_name_tag = ",\"name\":\""
flag3found = False
while iter3 < len(fb_buff):
if fb_buff[iter3:iter3+len(fbchat_name_tag)] == fbchat_name_tag:
contactName = fb_buff[iter3+len(fbchat_name_tag):].split("\"", 1)[0]
flag3found = True
break
iter3 += 1
if not flag3found:
continue
# Only if dupes argument is strictly enabled, then avoid
# displaying duplicate messages!
if self._config.duplicates:
# Calculate the SHA1 of message and if it
# has been already found DO NOT yield it
msgSHA1 = sha1(fb_buff[iter1:iter2]).hexdigest()
# If this message is already stored, keep looking
if msgSHA1 in foundItemsHashes:
continue
else:
foundItemsHashes.append(msgSHA1)
# Store in the Dictionary a list that contains the contact name
# and the message sent by him!
msgsDict[timestamp] = [contactName, fb_buff[iter1:iter2]]
# Yield results sorted by time!
for k in sorted(msgsDict):
dt = self.convertUnixTime(k)
if dt is not None:
yield msgsDict[k][0], dt, msgsDict[k][1]
def unified_output(self, data):
return TreeGrid([("User Name", str),
("Timestamp", str),
("Message", str)],
self.generator(data))
def generator(self, data):
for un, t, m in data:
try:
yield(0,
[str(un),
str(t),
str(m)])
except Exception as e:
print "[ERROR] Something went bad: User Name: " + un + ", Timestamp: " + t + ", Message: " + m
def render_text(self, outfd, data):
# Leaving the Message column without size specified,
# will allow Volatility to render it properly
# by finding the max Message record size
self.table_header(outfd, [("User Name", "40"),
("Timestamp", "28"),
("Message", "")])
for un, t, m in data:
try:
self.table_row(outfd, un, t, m)
except Exception as e:
print "[ERROR] Something went bad: User Name: " + un + ", Timestamp: " + t + ", Message: " + m
def render_csv(self, outfd, data):
outfd.write()
for un, t, m in data:
outfd.write("{0},{1},{2}\n".format(un, t, m))
| mit |
thaim/ansible | lib/ansible/plugins/doc_fragments/fortios.py | 44 | 1878 | # -*- coding: utf-8 -*-
# Copyright: (c) 2017, Benjamin Jolivot <bjolivot@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
options:
file_mode:
description:
- Don't connect to any device, only use I(config_file) as input and Output.
type: bool
default: no
version_added: "2.4"
config_file:
description:
- Path to configuration file. Required when I(file_mode) is True.
type: path
version_added: "2.4"
host:
description:
- Specifies the DNS hostname or IP address for connecting to the remote fortios device. Required when I(file_mode) is False.
type: str
username:
description:
- Configures the username used to authenticate to the remote device. Required when I(file_mode) is True.
type: str
password:
description:
- Specifies the password used to authenticate to the remote device. Required when I(file_mode) is True.
type: str
timeout:
description:
- Timeout in seconds for connecting to the remote device.
type: int
default: 60
vdom:
description:
- Specifies on which vdom to apply configuration
type: str
backup:
description:
- This argument will cause the module to create a backup of
the current C(running-config) from the remote device before any
changes are made. The backup file is written to the i(backup)
folder.
type: bool
default: no
backup_path:
description:
- Specifies where to store backup files. Required if I(backup=yes).
type: path
backup_filename:
description:
- Specifies the backup filename. If omitted filename will be
formatted like HOST_config.YYYY-MM-DD@HH:MM:SS
type: str
'''
| mit |
HiroIshikawa/21playground | flask-sample/hello/venv/lib/python3.5/site-packages/requests/utils.py | 36 | 20716 | # -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import collections
import io
import os
import platform
import re
import sys
import socket
import struct
import warnings
from . import __version__
from . import certs
from .compat import parse_http_list as _parse_list_header
from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
builtin_str, getproxies, proxy_bypass, urlunparse,
basestring)
from .cookies import RequestsCookieJar, cookiejar_from_dict
from .structures import CaseInsensitiveDict
from .exceptions import InvalidURL
_hush_pyflakes = (RequestsCookieJar,)
NETRC_FILES = ('.netrc', '_netrc')
DEFAULT_CA_BUNDLE_PATH = certs.where()
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
return d
def super_len(o):
if hasattr(o, '__len__'):
return len(o)
if hasattr(o, 'len'):
return o.len
if hasattr(o, 'fileno'):
try:
fileno = o.fileno()
except io.UnsupportedOperation:
pass
else:
return os.fstat(fileno).st_size
if hasattr(o, 'getvalue'):
# e.g. BytesIO, cStringIO.StringIO
return len(o.getvalue())
def get_netrc_auth(url, raise_errors=False):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See http://bugs.python.org/issue20164 &
# https://github.com/kennethreitz/requests/issues/1846
return
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
# Strip port numbers from netloc
host = ri.netloc.split(':')[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# AppEngine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if (name and isinstance(name, basestring) and name[0] != '<' and
name[-1] != '>'):
return os.path.basename(name)
def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value)
def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples.
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, collections.Mapping):
value = value.items()
return list(value)
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It basically works like :func:`parse_set_header` just that items
may appear multiple times and case sensitivity is preserved.
The return value is a standard :class:`list`:
>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the :class:`list` again, use the
:func:`dump_header` function.
:param value: a string with a list header.
:return: :class:`list`
"""
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
return value
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
"""
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
return cookie_dict
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
cj2 = cookiejar_from_dict(cookie_dict)
cj.update(cj2)
return cj
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
warnings.warn((
'In requests 3.0, get_encodings_from_content will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content))
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
if r.encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b'', final=True)
if rv:
yield rv
def iter_slices(string, slice_length):
"""Iterate over slices of a string."""
pos = 0
while pos < len(string):
yield string[pos:pos + slice_length]
pos += slice_length
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. fall back and replace all unicode characters
"""
warnings.warn((
'In requests 3.0, get_unicode_from_response will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ "0123456789-._~")
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
def requote_uri(uri):
"""Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted.
"""
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved,
# unreserved, or '%')
return quote(unquote_unreserved(uri), safe=safe_with_percent)
except InvalidURL:
# We couldn't unquote the given URI, so let's try quoting it, but
# there may be unquoted '%'s in the URI. We need to make sure they're
# properly quoted so they do not cause issues elsewhere.
return quote(uri, safe=safe_without_percent)
def address_in_network(ip, net):
"""
This function allows you to check if on IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def dotted_netmask(mask):
"""
Converts mask from /xx format to xxx.xxx.xxx.xxx
Example: if mask is 24 function returns 255.255.255.0
"""
bits = 0xffffffff ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack('>I', bits))
def is_ipv4_address(string_ip):
try:
socket.inet_aton(string_ip)
except socket.error:
return False
return True
def is_valid_cidr(string_network):
"""Very simple check of the cidr format in no_proxy variable"""
if string_network.count('/') == 1:
try:
mask = int(string_network.split('/')[1])
except ValueError:
return False
if mask < 1 or mask > 32:
return False
try:
socket.inet_aton(string_network.split('/')[0])
except socket.error:
return False
else:
return False
return True
def should_bypass_proxies(url):
"""
Returns whether we should bypass proxies or not.
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_proxy('no_proxy')
netloc = urlparse(url).netloc
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the netloc, both with and without the port.
no_proxy = (
host for host in no_proxy.replace(' ', '').split(',') if host
)
ip = netloc.split(':')[0]
if is_ipv4_address(ip):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(ip, proxy_ip):
return True
else:
for host in no_proxy:
if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True
# If the system proxy settings indicate that this URL should be bypassed,
# don't proxy.
# The proxy_bypass function is incredibly buggy on OS X in early versions
# of Python 2.6, so allow this call to fail. Only catch the specific
# exceptions we've seen, though: this call failing in other ways can reveal
# legitimate problems.
try:
bypass = proxy_bypass(netloc)
except (TypeError, socket.gaierror):
bypass = False
if bypass:
return True
return False
def get_environ_proxies(url):
"""Return a dict of environment proxies."""
if should_bypass_proxies(url):
return {}
else:
return getproxies()
def select_proxy(url, proxies):
"""Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
"""
proxies = proxies or {}
urlparts = urlparse(url)
proxy = proxies.get(urlparts.scheme+'://'+urlparts.hostname)
if proxy is None:
proxy = proxies.get(urlparts.scheme)
return proxy
def default_user_agent(name="python-requests"):
"""Return a string representing the default user agent."""
return '%s/%s' % (name, __version__)
def default_headers():
return CaseInsensitiveDict({
'User-Agent': default_user_agent(),
'Accept-Encoding': ', '.join(('gzip', 'deflate')),
'Accept': '*/*',
'Connection': 'keep-alive',
})
def parse_header_links(value):
"""Return a dict of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
"""
links = []
replace_chars = " '\""
for val in re.split(", *<", value):
try:
url, params = val.split(";", 1)
except ValueError:
url, params = val, ''
link = {}
link["url"] = url.strip("<> '\"")
for param in params.split(";"):
try:
key, value = param.split("=")
except ValueError:
break
link[key.strip(replace_chars)] = value.strip(replace_chars)
links.append(link)
return links
# Null bytes; no need to recreate these on each call to guess_json_utf
_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3
def guess_json_utf(data):
# JSON always starts with two ASCII characters, so detection is as
# easy as counting the nulls and from their location and count
# determine the encoding. Also detect a BOM, if present.
sample = data[:4]
if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE):
return 'utf-32' # BOM included
if sample[:3] == codecs.BOM_UTF8:
return 'utf-8-sig' # BOM included, MS style (discouraged)
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
return 'utf-16' # BOM included
nullcount = sample.count(_null)
if nullcount == 0:
return 'utf-8'
if nullcount == 2:
if sample[::2] == _null2: # 1st and 3rd are null
return 'utf-16-be'
if sample[1::2] == _null2: # 2nd and 4th are null
return 'utf-16-le'
# Did not detect 2 valid UTF-16 ascii-range characters
if nullcount == 3:
if sample[:3] == _null3:
return 'utf-32-be'
if sample[1:] == _null3:
return 'utf-32-le'
# Did not detect a valid UTF-32 ascii-range character
return None
def prepend_scheme_if_needed(url, new_scheme):
'''Given a URL that may or may not have a scheme, prepend the given scheme.
Does not replace a present scheme with the one provided as an argument.'''
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
# urlparse is a finicky beast, and sometimes decides that there isn't a
# netloc present. Assume that it's being over-cautious, and switch netloc
# and path if urlparse decided there was no netloc.
if not netloc:
netloc, path = path, netloc
return urlunparse((scheme, netloc, path, params, query, fragment))
def get_auth_from_url(url):
"""Given a url with authentication components, extract them into a tuple of
username,password."""
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('', '')
return auth
def to_native_string(string, encoding='ascii'):
"""
Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise.
"""
out = None
if isinstance(string, builtin_str):
out = string
else:
if is_py2:
out = string.encode(encoding)
else:
out = string.decode(encoding)
return out
def urldefragauth(url):
"""
Given a url remove the fragment and the authentication part
"""
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ''))
| mit |
donutmonger/youtube-dl | youtube_dl/extractor/tmz.py | 126 | 2370 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class TMZIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tmz\.com/videos/(?P<id>[^/]+)/?'
_TEST = {
'url': 'http://www.tmz.com/videos/0_okj015ty/',
'md5': '791204e3bf790b1426cb2db0706184c0',
'info_dict': {
'id': '0_okj015ty',
'url': 'http://tmz.vo.llnwd.net/o28/2014-03/13/0_okj015ty_0_rt8ro3si_2.mp4',
'ext': 'mp4',
'title': 'Kim Kardashian\'s Boobs Unlock a Mystery!',
'description': 'Did Kim Kardasain try to one-up Khloe by one-upping Kylie??? Or is she just showing off her amazing boobs?',
'thumbnail': r're:http://cdnbakmi\.kaltura\.com/.*thumbnail.*',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
return {
'id': video_id,
'url': self._html_search_meta('VideoURL', webpage, fatal=True),
'title': self._og_search_title(webpage),
'description': self._og_search_description(webpage),
'thumbnail': self._html_search_meta('ThumbURL', webpage),
}
class TMZArticleIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tmz\.com/\d{4}/\d{2}/\d{2}/(?P<id>[^/]+)/?'
_TEST = {
'url': 'http://www.tmz.com/2015/04/19/bobby-brown-bobbi-kristina-awake-video-concert',
'md5': 'e482a414a38db73087450e3a6ce69d00',
'info_dict': {
'id': '0_6snoelag',
'ext': 'mp4',
'title': 'Bobby Brown Tells Crowd ... Bobbi Kristina is Awake',
'description': 'Bobby Brown stunned his audience during a concert Saturday night, when he told the crowd, "Bobbi is awake. She\'s watching me."',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
embedded_video_info_str = self._html_search_regex(
r'tmzVideoEmbedV2\("([^)]+)"\);', webpage, 'embedded video info')
embedded_video_info = self._parse_json(
embedded_video_info_str, video_id,
transform_source=lambda s: s.replace('\\', ''))
return self.url_result(
'http://www.tmz.com/videos/%s/' % embedded_video_info['id'])
| unlicense |
havard024/prego | venv/lib/python2.7/site-packages/whoosh/qparser/taggers.py | 96 | 3624 | # Copyright 2011 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Matt Chaput.
from whoosh.util.text import rcompile
# Tagger objects
class Tagger(object):
"""Base class for taggers, objects which match syntax in the query string
and translate it into a :class:`whoosh.qparser.syntax.SyntaxNode` object.
"""
def match(self, parser, text, pos):
"""This method should see if this tagger matches the query string at
the given position. If it matches, it should return
:param parser: the :class:`whoosh.qparser.default.QueryParser` object.
:param text: the text being parsed.
:param pos: the position in the text at which the tagger should try to
match.
"""
raise NotImplementedError
class RegexTagger(Tagger):
"""Tagger class that uses regular expressions to match the query string.
Subclasses should override ``create()`` instead of ``match()``.
"""
def __init__(self, expr):
self.expr = rcompile(expr)
def match(self, parser, text, pos):
match = self.expr.match(text, pos)
if match:
node = self.create(parser, match)
if node is not None:
node = node.set_range(match.start(), match.end())
return node
def create(self, parser, match):
"""When the regular expression matches, this method is called to
translate the regex match object into a syntax node.
:param parser: the :class:`whoosh.qparser.default.QueryParser` object.
:param match: the regex match object.
"""
raise NotImplementedError
class FnTagger(RegexTagger):
"""Tagger that takes a regular expression and a class or function, and for
matches calls the class/function with the regex match's named groups as
keyword arguments.
"""
def __init__(self, expr, fn, memo=""):
RegexTagger.__init__(self, expr)
self.fn = fn
self.memo = memo
def __repr__(self):
return "<%s %r (%s)>" % (self.__class__.__name__, self.expr, self.memo)
def create(self, parser, match):
return self.fn(**match.groupdict())
| mit |
cpennington/edx-platform | lms/djangoapps/verify_student/ssencrypt.py | 5 | 8534 | """
NOTE: Anytime a `key` is passed into a function here, we assume it's a raw byte
string. It should *not* be a string representation of a hex value. In other
words, passing the `str` value of
`"32fe72aaf2abb44de9e161131b5435c8d37cbdb6f5df242ae860b283115f2dae"` is bad.
You want to pass in the result of calling .decode('hex') on that, so this instead:
"'2\xfer\xaa\xf2\xab\xb4M\xe9\xe1a\x13\x1bT5\xc8\xd3|\xbd\xb6\xf5\xdf$*\xe8`\xb2\x83\x11_-\xae'"
An RSA public key can be in any of the following formats:
* X.509 subjectPublicKeyInfo DER SEQUENCE (binary or PEM encoding)
* PKCS#1 RSAPublicKey DER SEQUENCE (binary or PEM encoding)
* OpenSSH (textual public key only)
An RSA private key can be in any of the following formats:
* PKCS#1 RSAPrivateKey DER SEQUENCE (binary or PEM encoding)
* PKCS#8 PrivateKeyInfo DER SEQUENCE (binary or PEM encoding)
"""
import base64
import binascii
import hmac
import logging
import os
from hashlib import md5, sha256
import six
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives.padding import PKCS7
from six import text_type
log = logging.getLogger(__name__)
AES_BLOCK_SIZE_BYTES = int(AES.block_size / 8)
def encrypt_and_encode(data, key):
""" Encrypts and encodes `data` using `key' """
return base64.urlsafe_b64encode(aes_encrypt(data, key))
def decode_and_decrypt(encoded_data, key):
""" Decrypts and decodes `data` using `key' """
return aes_decrypt(base64.urlsafe_b64decode(encoded_data), key)
def aes_encrypt(data, key):
"""
Return a version of the `data` that has been encrypted to
"""
cipher = aes_cipher_from_key(key)
padded_data = pad(data)
encryptor = cipher.encryptor()
return encryptor.update(padded_data) + encryptor.finalize()
def aes_decrypt(encrypted_data, key):
"""
Decrypt `encrypted_data` using `key`
"""
cipher = aes_cipher_from_key(key)
decryptor = cipher.decryptor()
padded_data = decryptor.update(encrypted_data) + decryptor.finalize()
return unpad(padded_data)
def aes_cipher_from_key(key):
"""
Given an AES key, return a Cipher object that has `encryptor()` and
`decryptor()` methods. It will create the cipher to use CBC mode, and create
the initialization vector as Software Secure expects it.
"""
return Cipher(AES(key), CBC(generate_aes_iv(key)), backend=default_backend())
def generate_aes_iv(key):
"""
Return the initialization vector Software Secure expects for a given AES
key (they hash it a couple of times and take a substring).
"""
if six.PY3:
return md5(key + md5(key).hexdigest().encode('utf-8')).hexdigest()[:AES_BLOCK_SIZE_BYTES].encode('utf-8')
else:
return md5(key + md5(key).hexdigest()).hexdigest()[:AES_BLOCK_SIZE_BYTES]
def random_aes_key():
return os.urandom(32)
def pad(data):
""" Pad the given `data` such that it fits into the proper AES block size """
if six.PY3 and not isinstance(data, (bytes, bytearray)):
data = six.b(data)
padder = PKCS7(AES.block_size).padder()
return padder.update(data) + padder.finalize()
def unpad(padded_data):
""" remove all padding from `padded_data` """
unpadder = PKCS7(AES.block_size).unpadder()
return unpadder.update(padded_data) + unpadder.finalize()
def rsa_encrypt(data, rsa_pub_key_bytes):
"""
`rsa_pub_key_bytes` is a byte sequence with the public key
"""
if isinstance(data, text_type):
data = data.encode('utf-8')
if isinstance(rsa_pub_key_bytes, text_type):
rsa_pub_key_bytes = rsa_pub_key_bytes.encode('utf-8')
if rsa_pub_key_bytes.startswith(b'-----'):
key = serialization.load_pem_public_key(rsa_pub_key_bytes, backend=default_backend())
elif rsa_pub_key_bytes.startswith(b'ssh-rsa '):
key = serialization.load_ssh_public_key(rsa_pub_key_bytes, backend=default_backend())
else:
key = serialization.load_der_public_key(rsa_pub_key_bytes, backend=default_backend())
return key.encrypt(data, OAEP(MGF1(SHA1()), SHA1(), label=None))
def rsa_decrypt(data, rsa_priv_key_bytes):
"""
When given some `data` and an RSA private key, decrypt the data
"""
if isinstance(data, text_type):
data = data.encode('utf-8')
if isinstance(rsa_priv_key_bytes, text_type):
rsa_priv_key_bytes = rsa_priv_key_bytes.encode('utf-8')
if rsa_priv_key_bytes.startswith(b'-----'):
key = serialization.load_pem_private_key(rsa_priv_key_bytes, password=None, backend=default_backend())
else:
key = serialization.load_der_private_key(rsa_priv_key_bytes, password=None, backend=default_backend())
return key.decrypt(data, OAEP(MGF1(SHA1()), SHA1(), label=None))
def has_valid_signature(method, headers_dict, body_dict, access_key, secret_key):
"""
Given a message (either request or response), say whether it has a valid
signature or not.
"""
_, expected_signature, _ = generate_signed_message(
method, headers_dict, body_dict, access_key, secret_key
)
authorization = headers_dict["Authorization"]
auth_token, post_signature = authorization.split(":")
_, post_access_key = auth_token.split()
if post_access_key != access_key:
log.error("Posted access key does not match ours")
log.debug(u"Their access: %s; Our access: %s", post_access_key, access_key)
return False
if post_signature != expected_signature:
log.error("Posted signature does not match expected")
log.debug(u"Their sig: %s; Expected: %s", post_signature, expected_signature)
return False
return True
def generate_signed_message(method, headers_dict, body_dict, access_key, secret_key):
"""
Returns a (message, signature) pair.
"""
message = signing_format_message(method, headers_dict, body_dict)
# hmac needs a byte string for it's starting key, can't be unicode.
hashed = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), sha256)
signature = binascii.b2a_base64(hashed.digest()).rstrip(b'\n').decode('utf-8')
authorization_header = u"SSI {}:{}".format(access_key, signature)
message += '\n'
return message, signature, authorization_header
def signing_format_message(method, headers_dict, body_dict):
"""
Given a dictionary of headers and a dictionary of the JSON for the body,
will return a str that represents the normalized version of this messsage
that will be used to generate a signature.
"""
headers_str = "{}\n\n{}".format(method, header_string(headers_dict))
body_str = body_string(body_dict)
message = headers_str + body_str
return message
def header_string(headers_dict):
"""Given a dictionary of headers, return a canonical string representation."""
header_list = []
if 'Content-Type' in headers_dict:
header_list.append(headers_dict['Content-Type'] + "\n")
if 'Date' in headers_dict:
header_list.append(headers_dict['Date'] + "\n")
if 'Content-MD5' in headers_dict:
header_list.append(headers_dict['Content-MD5'] + "\n")
return "".join(header_list) # Note that trailing \n's are important
def body_string(body_dict, prefix=""):
"""
Return a canonical string representation of the body of a JSON request or
response. This canonical representation will be used as an input to the
hashing used to generate a signature.
"""
body_list = []
for key, value in sorted(body_dict.items()):
if isinstance(value, (list, tuple)):
for i, arr in enumerate(value):
if isinstance(arr, dict):
body_list.append(body_string(arr, u"{}.{}.".format(key, i)))
else:
body_list.append(u"{}.{}:{}\n".format(key, i, arr))
elif isinstance(value, dict):
body_list.append(body_string(value, key + ":"))
else:
if value is None:
value = "null"
body_list.append(u"{}{}:{}\n".format(prefix, key, value))
return "".join(body_list) # Note that trailing \n's are important
| agpl-3.0 |
ChanduERP/odoo | addons/account_asset/account_asset_invoice.py | 141 | 3088 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 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/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_invoice(osv.osv):
_inherit = 'account.invoice'
def action_number(self, cr, uid, ids, *args, **kargs):
result = super(account_invoice, self).action_number(cr, uid, ids, *args, **kargs)
for inv in self.browse(cr, uid, ids):
self.pool.get('account.invoice.line').asset_create(cr, uid, inv.invoice_line)
return result
def line_get_convert(self, cr, uid, x, part, date, context=None):
res = super(account_invoice, self).line_get_convert(cr, uid, x, part, date, context=context)
res['asset_id'] = x.get('asset_id', False)
return res
class account_invoice_line(osv.osv):
_inherit = 'account.invoice.line'
_columns = {
'asset_category_id': fields.many2one('account.asset.category', 'Asset Category'),
}
def asset_create(self, cr, uid, lines, context=None):
context = context or {}
asset_obj = self.pool.get('account.asset.asset')
for line in lines:
if line.asset_category_id:
vals = {
'name': line.name,
'code': line.invoice_id.number or False,
'category_id': line.asset_category_id.id,
'purchase_value': line.price_subtotal,
'period_id': line.invoice_id.period_id.id,
'partner_id': line.invoice_id.partner_id.id,
'company_id': line.invoice_id.company_id.id,
'currency_id': line.invoice_id.currency_id.id,
'purchase_date' : line.invoice_id.date_invoice,
}
changed_vals = asset_obj.onchange_category_id(cr, uid, [], vals['category_id'], context=context)
vals.update(changed_vals['value'])
asset_id = asset_obj.create(cr, uid, vals, context=context)
if line.asset_category_id.open_asset:
asset_obj.validate(cr, uid, [asset_id], context=context)
return True
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
smartfile/django-1.4 | tests/modeltests/select_related/tests.py | 26 | 6535 | from __future__ import with_statement, absolute_import
from django.test import TestCase
from .models import Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species
class SelectRelatedTests(TestCase):
def create_tree(self, stringtree):
"""
Helper to create a complete tree.
"""
names = stringtree.split()
models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species]
assert len(names) == len(models), (names, models)
parent = None
for name, model in zip(names, models):
try:
obj = model.objects.get(name=name)
except model.DoesNotExist:
obj = model(name=name)
if parent:
setattr(obj, parent.__class__.__name__.lower(), parent)
obj.save()
parent = obj
def create_base_data(self):
self.create_tree("Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila melanogaster")
self.create_tree("Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens")
self.create_tree("Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum sativum")
self.create_tree("Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae Amanita muscaria")
def setUp(self):
# The test runner sets settings.DEBUG to False, but we want to gather
# queries so we'll set it to True here and reset it at the end of the
# test case.
self.create_base_data()
def test_access_fks_without_select_related(self):
"""
Normally, accessing FKs doesn't fill in related objects
"""
with self.assertNumQueries(8):
fly = Species.objects.get(name="melanogaster")
domain = fly.genus.family.order.klass.phylum.kingdom.domain
self.assertEqual(domain.name, 'Eukaryota')
def test_access_fks_with_select_related(self):
"""
A select_related() call will fill in those related objects without any
extra queries
"""
with self.assertNumQueries(1):
person = Species.objects.select_related(depth=10).get(name="sapiens")
domain = person.genus.family.order.klass.phylum.kingdom.domain
self.assertEqual(domain.name, 'Eukaryota')
def test_list_without_select_related(self):
"""
select_related() also of course applies to entire lists, not just
items. This test verifies the expected behavior without select_related.
"""
with self.assertNumQueries(9):
world = Species.objects.all()
families = [o.genus.family.name for o in world]
self.assertEqual(sorted(families), [
'Amanitacae',
'Drosophilidae',
'Fabaceae',
'Hominidae',
])
def test_list_with_select_related(self):
"""
select_related() also of course applies to entire lists, not just
items. This test verifies the expected behavior with select_related.
"""
with self.assertNumQueries(1):
world = Species.objects.all().select_related()
families = [o.genus.family.name for o in world]
self.assertEqual(sorted(families), [
'Amanitacae',
'Drosophilidae',
'Fabaceae',
'Hominidae',
])
def test_depth(self, depth=1, expected=7):
"""
The "depth" argument to select_related() will stop the descent at a
particular level.
"""
# Notice: one fewer queries than above because of depth=1
with self.assertNumQueries(expected):
pea = Species.objects.select_related(depth=depth).get(name="sativum")
self.assertEqual(
pea.genus.family.order.klass.phylum.kingdom.domain.name,
'Eukaryota'
)
def test_larger_depth(self):
"""
The "depth" argument to select_related() will stop the descent at a
particular level. This tests a larger depth value.
"""
self.test_depth(depth=5, expected=3)
def test_list_with_depth(self):
"""
The "depth" argument to select_related() will stop the descent at a
particular level. This can be used on lists as well.
"""
with self.assertNumQueries(5):
world = Species.objects.all().select_related(depth=2)
orders = [o.genus.family.order.name for o in world]
self.assertEqual(sorted(orders),
['Agaricales', 'Diptera', 'Fabales', 'Primates'])
def test_select_related_with_extra(self):
s = Species.objects.all().select_related(depth=1)\
.extra(select={'a': 'select_related_species.id + 10'})[0]
self.assertEqual(s.id + 10, s.a)
def test_certain_fields(self):
"""
The optional fields passed to select_related() control which related
models we pull in. This allows for smaller queries and can act as an
alternative (or, in addition to) the depth parameter.
In this case, we explicitly say to select the 'genus' and
'genus.family' models, leading to the same number of queries as before.
"""
with self.assertNumQueries(1):
world = Species.objects.select_related('genus__family')
families = [o.genus.family.name for o in world]
self.assertEqual(sorted(families),
['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae'])
def test_more_certain_fields(self):
"""
In this case, we explicitly say to select the 'genus' and
'genus.family' models, leading to the same number of queries as before.
"""
with self.assertNumQueries(2):
world = Species.objects.filter(genus__name='Amanita')\
.select_related('genus__family')
orders = [o.genus.family.order.name for o in world]
self.assertEqual(orders, [u'Agaricales'])
def test_field_traversal(self):
with self.assertNumQueries(1):
s = Species.objects.all().select_related('genus__family__order'
).order_by('id')[0:1].get().genus.family.order.name
self.assertEqual(s, u'Diptera')
def test_depth_fields_fails(self):
self.assertRaises(TypeError,
Species.objects.select_related,
'genus__family__order', depth=4
)
| bsd-3-clause |
gmartinvela/RoMIE | robot_control/views.py | 1 | 10330 | import sys
import time
import os
import subprocess
import webbrowser
import threading
import traceback
from django.http import HttpResponse
from django.shortcuts import render
from robot_control.models import Category, Question, Response
from django.core.mail import send_mail
import json
MAX_TIME = 180 # seconds
PORT = '8000'
GLOBAL_LOCK = threading.Lock()
tag = None
try:
from robot_app.joystick_handler import get_event
Joystick=True
except:
Joystick=False
print 'The joystick is not working'
# ############ - Bluetooth Initialization - ###############
try:
import bluetooth #For GNU/Linux using PyBluez
#import lightblue #For Mac OS X using lightblue
#sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC') #For Mac OS X using lightblue
BT_name = "linvor"
BT_address = '00:12:02:09:05:16'
#nearby_devices = bluetooth.discover_devices()
BT_port = 1
#Client Socket
client_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) #For GNU/Linux using PyBluez
#client_sock = lightblue.socket()
port = client_sock.connect((BT_address, BT_port))
BT_available=True
except:
BT_available=False
print 'No Bluetooth device is available'
def wait_ack(client_sock):
total_received = ""
while 'ACK' not in total_received and 'NAK' not in total_received:
total_received += client_sock.recv(1024)
if 'NAK' in total_received:
global popen
popen.kill()
#TODO BOMBAAAAAAAAAAA!!!!
print repr(total_received)
return total_received
def forward(request):
if request.META.get('REMOTE_ADDR') not in ('127.0.0.1', 'localhost', '::1', '127.0.1.1'):
return HttpResponse("INVALID_CLIENT_ADDRESS")
client_sock.send('F')
response = wait_ack(client_sock)
return HttpResponse(response)
def turn_left(request):
if request.META.get('REMOTE_ADDR') not in ('127.0.0.1', 'localhost', '::1', '127.0.1.1'):
return HttpResponse("INVALID_CLIENT_ADDRESS")
client_sock.send('L')
response = wait_ack(client_sock)
return HttpResponse(response)
def turn_right(request):
if request.META.get('REMOTE_ADDR') not in ('127.0.0.1', 'localhost', '::1', '127.0.1.1'):
return HttpResponse("INVALID_CLIENT_ADDRESS")
client_sock.send('R')
response = wait_ack(client_sock)
print response
return HttpResponse(response)
def sensor_wall(request):
if request.META.get('REMOTE_ADDR') not in ('127.0.0.1', 'localhost', '::1', '127.0.1.1'):
return HttpResponse("INVALID_CLIENT_ADDRESS")
client_sock.send('S')
response = client_sock.recv(1024)
#TODO: recibir lectura del sensor
#return HttpResponse(response)
print "response ",response
return HttpResponse(response)
HEADER_CODE = """
import urllib2
OPENER = urllib2.build_opener(urllib2.ProxyHandler({}))
def forward():
return OPENER.open("http://localhost:%(port)s/RoMIE/movements/forward").read()
def turn_left():
return OPENER.open("http://localhost:%(port)s/RoMIE/movements/turn_left").read()
def turn_right():
return OPENER.open("http://localhost:%(port)s/RoMIE/movements/turn_right").read()
def sensor_wall():
response = OPENER.open("http://localhost:%(port)s/RoMIE/movements/sensor_wall").read()
print "response second: ",response
if "1" in response:
return True
else:
return False
#return response
#return OPENER.open("http://localhost:%(port)s/RoMIE/movements/sensor_wall").read()
""" % { 'port' : PORT }
def move(direction):
client_sock.send(direction)
response = client_sock.recv(1024)
# #print "direction: %s" % direction
# #print "response: %s" % response
string_tag_position = response.find("Tag")
if string_tag_position != -1:
in_tag_position = string_tag_position + 5
out_tag_position = in_tag_position + 15
tag = response[in_tag_position:out_tag_position]
tag_full = tag.replace(" ", "")
print tag_full
if tag_full:
global tag
tag= tag_full
print "Tengo el TAG: ",tag
# # os.chdir("/home/gustavo/Desktop")
# # if tag_full == "4F005687C4":
# # global tag
# # tag= tag_full
# print "Tengo el TAG: ",tag
# if tag_full == "4F00569F08":
# global tag
# tag = tag_full
# # #webbrowser.open("http://127.0.0.1:8000/RoMIE/question_son_goku/", new = 0)
# # subprocess.call(["java","-jar","Pregunton.jar","1"])
# elif tag_full == "4F0088ABCB":
# global tag
# tag = tag_full
# # #webbrowser.open("http://127.0.0.1:8000/RoMIE/question_one_piece/", new = 0)
# # subprocess.call(["java","-jar","Pregunton.jar","2"])
# elif tag_full == "50008967FC":
# global tag
# tag = tag_full
# # #webbrowser.open("http://127.0.0.1:8000/RoMIE/question_digimon/", new = 0)
# # subprocess.call(["java","-jar","Pregunton.jar","3"])
# elif tag_full == "4F00568090":
# global tag
# tag = tag_full
# # #webbrowser.open("http://127.0.0.1:8000/RoMIE/question_naruto/", new = 0)
# # subprocess.call(["java","-jar","Pregunton.jar","4"])
# # # # return tag
# # ############################################################
def select_random_questions():
#categories_dict = {'Science':3, 'History':4, 'Sport':1, 'Culture':2, 'Entertainment':5, 'Geography':6}
categories_dict = {'Sport':1, 'Culture':2}
# SCIENCE
#filtered_questions_science = Question.objects.filter(category = categories_dict['Science'])
#science_question = filtered_questions_science.order_by('?')[:1]
# HISTORY
#filtered_questions_history = Question.objects.filter(category = categories_dict['History'])
#history_question = filtered_questions_history.order_by('?')[:1]
# SPORT
filtered_questions_sport = Question.objects.filter(category = categories_dict['Sport'])
sport_question = filtered_questions_sport.order_by('?')[:1]
# HUMANITIES
filtered_questions_culture = Question.objects.filter(category = categories_dict['Culture'])
culture_question = filtered_questions_culture.order_by('?')[:1]
# ENTERTAINMENT
#filtered_questions_entertainment = Question.objects.filter(category = categories_dict['Entertainment'])
#entertainment_question = filtered_questions_entertainment.order_by('?')[:1]
# GEOGRAPHY
#filtered_questions_geography = Question.objects.filter(category = categories_dict['Geography'])
#geography_question = filtered_questions_geography.order_by('?')[:1]
#return science_question, history_question, sport_question, humanities_question, entertainment_question, geography_question
return sport_question, culture_question
#questions_enabled = [1,0,0,0,1,1]
#science_question, history_question, sport_question, humanities_question, entertainment_question, geography_question = select_random_questions()
sport_question, culture_question = select_random_questions()
def index(request):
if request.method == 'GET':
# Selection of 2 questions randomly
print "SPORT: ", sport_question
print "CULTURE: ", culture_question
#global tag
#tag = "4F005687C4"
return render(request, 'robot_control/index.html', {'sport_question': sport_question, 'culture_question': culture_question,})
elif request.method == 'POST':
received_command = request.REQUEST["command"]
#print received_command
if BT_available==True:
move(received_command)
else:
print 'Cannot send command to the robot.'
#tag = move(received_command)
#if tag:
# print tag
return HttpResponse("POST OK")
def joystick_status(request):
if Joystick==True:
return HttpResponse(json.dumps(get_event()))
else:
return HttpResponse('No Joystick')
def RFID_status(request):
#send_mail('RFID-status Access', 'In this moment RoMIE is accessing to the URL: /RFID-status', 'RoMIE@weblab.deusto.es',['gustavo.martin@opendeusto.es'])
mail_admins('RFID-status Access', 'In this moment RoMIE is accessing to the URL: /RFID-status', fail_silently=False, connection=None, html_message=None)
global tag
print "TAG: ",tag
if tag:
current_tag = tag
tag = None
return HttpResponse(current_tag)
else:
return HttpResponse('No RFID')
def tutorial(request):
return render(request, 'robot_control/tutorial.html')
def blockly(request):
if request.method == 'GET':
return render(request, 'robot_control/blockly.html')
elif request.method == 'POST':
block_code = request.REQUEST["code"]
if block_code == "stop":
global popen
popen.kill()
else:
launch_in_background(block_code)
return render(request, 'robot_control/blockly.html')
def launch_in_background(block_code):
global t
t = threading.Thread(target=exec_code, args = (block_code,))
t.start()
def exec_code(code):
final_code = HEADER_CODE + code
try:
with GLOBAL_LOCK:
#print final_code
#exec final_code
open("executable.py", "w").write(final_code)
#print "final_code ",final_code
global popen
popen = subprocess.Popen([sys.executable, "executable.py"])
print "subprocess: ",popen.pid
initial_time = time.time()
while time.time() < (initial_time + MAX_TIME):
if popen.poll() is not None:
break
time.sleep(1)
if popen.poll() is None:
print "Killing in the name of", (time.time() - initial_time)
sys.stdout.flush()
popen.terminate()
popen.kill()
except:
traceback.print_exc()
return HttpResponse("OH, FUCK")
def quiz(request):
return render(request, 'robot_control/quiz.html')
#######################################################################################################################################
| mit |
liuycsd/bypy | bypy/requester.py | 1 | 3844 | #!/usr/bin/env python
# encoding: utf-8
# PYTHON_ARGCOMPLETE_OK
# from __future__ imports must occur at the beginning of the file
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import sys
import logging
import json
from functools import partial
import requests
# unify Python 2 and 3
if sys.version_info[0] == 2:
import urllib2 as ulr
import httplib
import cPickle as pickle
pickleload = pickle.load
elif sys.version_info[0] == 3:
import urllib.request as ulr
import http.client as httplib
import pickle
unicode = str
basestring = str
long = int
raw_input = input
pickleload = partial(pickle.load, encoding="bytes")
from . import const
from .printer import (perr)
from .util import (formatex)
# the object returned from your Requester should have the following members
# may be used for mocking / testing in the future
class RequesterResponse(object):
def __init__(self, url, text, status_code):
super(RequesterResponse, self).__init__()
self.text = text
self.url = url
self.status_code = status_code
self.headers = {}
def json(self):
json.loads(self.text)
# NOT in use, replacing the requests library is not trivial
class UrllibRequester(object):
def __init__(self):
super(UrllibRequester, self).__init__()
@classmethod
def setoptions(cls, options):
pass
@classmethod
def request(cls, method, url, **kwargs):
"""
:type method: str
"""
methodupper = method.upper()
hasdata = 'data' in kwargs
if methodupper == 'GET':
if hasdata:
print("ERROR: Can't do HTTP GET when the 'data' parameter presents")
assert False
resp = ulr.urlopen(url, **kwargs)
elif methodupper == 'POST':
if hasdata:
resp = ulr.urlopen(url, **kwargs)
else:
resp = ulr.urlopen(url, data = '', **kwargs)
else:
raise NotImplementedError()
return resp
@classmethod
def set_logging_level(cls, level):
pass
@classmethod
def disable_warnings(cls):
pass
# extracting this class out would make it easier to test / mock
class RequestsRequester(object):
options = {}
def __init__(self):
super(RequestsRequester, self).__init__()
@classmethod
def setoptions(cls, options):
cls.options = options
@classmethod
def request(cls, method, url, **kwargs):
for k,v in cls.options.items():
kwargs.setdefault(k, v)
return requests.request(method, url, **kwargs)
@classmethod
def disable_warnings(cls):
try:
import requests.packages.urllib3 as ul3
#ul3.disable_warnings(ul3.exceptions.InsecureRequestWarning)
#ul3.disable_warnings(ul3.exceptions.InsecurePlatformWarning)
ul3.disable_warnings()
except:
try:
import urllib3 as ul3
ul3.disable_warnings()
except Exception as ex:
perr("Failed to disable warnings for Urllib3.\n"
"Possibly the requests library is out of date?\n"
"You can upgrade it by running '{}'.\n{}".format(
const.PipUpgradeCommand, formatex(ex)))
# i don't know why under Ubuntu, 'pip install requests' doesn't install the requests.packages.* packages
pass
# only if user specifies '-ddd' or more 'd's, the following
# debugging information will be shown, as it's very talkative.
# it enables debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
@classmethod
def set_logging_level(cls, level):
if level >= 3:
httplib.HTTPConnection.debuglevel = 1
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
| mit |
sdgdsffdsfff/simpleMon | nbNet/nbNet.py | 4 | 7022 | #!/usr/bin/python
#-*- coding:utf-8 -*-
import socket, select, logging, errno
import os, sys, json
def cmdRunner(input):
import commands
cmd_ret = commands.getstatusoutput(input)
return json.dumps({'ret':cmd_ret[0], 'out':cmd_ret[1]}, separators=(',', ':'))
class _State:
def __init__(self):
self.state = "read"
self.have_read = 0
self.need_read = 10
self.have_write = 0
self.need_write = 0
self.data = ""
__all__ = ['nbNet','sendData']
class nbNet:
def __init__(self, host, port, logic):
self.host = host
self.port = port
self.logic = logic
self.sm = {
"read":self.aread,
"write":self.awrite,
"process":self.aprocess,
"closing":self.aclose,
}
def run(self):
try:
self.listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
except socket.error, msg:
print("create socket failed")
try:
self.listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error, msg:
print("setsocketopt SO_REUSEADDR failed")
try:
self.listen_fd.bind((self.host, self.port))
except socket.error, msg:
print("bind failed")
try:
self.listen_fd.listen(10)
except socket.error, msg:
print(msg)
try:
self.epoll_fd = select.epoll()
# 向 epoll 句柄中注册 新来socket链接,监听可读事件
self.epoll_fd.register(self.listen_fd.fileno(), select.EPOLLET | select.EPOLLIN )
except select.error, msg:
print(msg)
self.STATE = {}
while True:
print self.STATE
# epoll 进行 fd 扫描的地方 -- 未指定超时时间[毫秒]则为阻塞等待
epoll_list = self.epoll_fd.poll()
for fd, events in epoll_list:
if select.EPOLLHUP & events:
print 'EPOLLHUP'
self.STATE[fd][2].state = "closing"
elif select.EPOLLERR & events:
print 'EPOLLERR'
self.STATE[fd][2].state = "closing"
self.state_machine(fd)
def state_machine(self, fd):
if fd == self.listen_fd.fileno():
print "state_machine fd %s accept" % fd
# fd与初始监听的fd一致,新创建一个连接
conn, addr = self.listen_fd.accept()
# 设置为非阻塞
conn.setblocking(0)
self.STATE[conn.fileno()] = [conn, addr, _State()]
# 将新的链接注册在epoll句柄中,监听可读事件
self.epoll_fd.register(conn.fileno(), select.EPOLLET | select.EPOLLIN )
else:
# 否则为历史已存在的fd,调用对应的状态方法
print "state_machine fd %s %s" % (fd,self.STATE[fd][2].state)
stat = self.STATE[fd][2].state
self.sm[stat](fd)
def aread(self, fd):
try:
# 接收当前fd的可读事件中的数据
one_read = self.STATE[fd][0].recv(self.STATE[fd][2].need_read)
if len(one_read) == 0:
# 接收错误改变状态为关闭
self.STATE[fd][2].state = "closing"
self.state_machine(fd)
return
# 将历史接收的数据叠加
self.STATE[fd][2].data += one_read
self.STATE[fd][2].have_read += len(one_read)
self.STATE[fd][2].need_read -= len(one_read)
# 接收协议的10个字符
if self.STATE[fd][2].have_read == 10:
# 通过10个字符得知下次应该具体接收多少字节,存入状态字典中
self.STATE[fd][2].need_read += int(self.STATE[fd][2].data)
self.STATE[fd][2].data = ''
# 调用状态机重新处理
self.state_machine(fd)
elif self.STATE[fd][2].need_read == 0:
# 当接全部收完毕,改变状态,去执行具体服务
self.STATE[fd][2].state = 'process'
self.state_machine(fd)
except socket.error, msg:
self.STATE[fd][2].state = "closing"
print(msg)
self.state_machine(fd)
return
def aprocess(self, fd):
# 执行具体执行方法 cmdRunner 得到符合传输协议的返回结果
response = self.logic(self.STATE[fd][2].data)
self.STATE[fd][2].data = "%010d%s"%(len(response), response)
self.STATE[fd][2].need_write = len(self.STATE[fd][2].data)
# 改变为写的状态
self.STATE[fd][2].state = 'write'
# 改变监听事件为写
self.epoll_fd.modify(fd, select.EPOLLET | select.EPOLLOUT)
self.state_machine(fd)
def awrite(self, fd):
try:
last_have_send = self.STATE[fd][2].have_write
# 发送返回给客户端的数据
have_send = self.STATE[fd][0].send(self.STATE[fd][2].data[last_have_send:])
self.STATE[fd][2].have_write += have_send
self.STATE[fd][2].need_write -= have_send
if self.STATE[fd][2].need_write == 0 and self.STATE[fd][2].have_write != 0:
# 发送完成,重新初始化状态,并将监听写事件改回读事件
self.STATE[fd][2] = _State()
self.epoll_fd.modify(fd, select.EPOLLET | select.EPOLLIN)
except socket.error, msg:
self.STATE[fd][2].state = "closing"
self.state_machine(fd)
print(msg)
return
def aclose(self, fd):
try:
print 'Error: %s:%d' %(self.STATE[fd][1][0] ,self.STATE[fd][1][1])
# 取消fd的事件监听
self.epoll_fd.unregister(fd)
# 关闭异常链接
self.STATE[fd][0].close()
# 删除fd的状态信息
self.STATE.pop(fd)
except:
print 'Close the abnormal'
def sendData(sock_l, host, port, data):
retry = 0
while retry < 3:
try:
if sock_l[0] == None:
sock_l[0] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_l[0].connect((host, port))
print "connecting"
d = data
sock_l[0].sendall("%010d%s"%(len(d), d))
print "%010d%s"%(len(d), d)
count = sock_l[0].recv(10)
if not count:
raise Exception("recv error", "recv error")
count = int(count)
buf = sock_l[0].recv(count)
print buf
if buf[:2] == "OK":
retry = 0
break
except:
sock_l[0].close()
sock_l[0] = None
retry += 1
if __name__ == "__main__":
HOST = '0.0.0.0'
PORT = 50005
nb = nbNet(HOST, PORT, cmdRunner)
nb.run()
| apache-2.0 |
eadgarchen/tensorflow | tensorflow/contrib/learn/python/learn/estimators/estimator_test_utils.py | 81 | 2065 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utils for Estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.util import tf_inspect
def assert_estimator_contract(tester, estimator_class):
"""Asserts whether given estimator satisfies the expected contract.
This doesn't check every details of contract. This test is used for that a
function is not forgotten to implement in a precanned Estimator.
Args:
tester: A tf.test.TestCase.
estimator_class: 'type' object of pre-canned estimator.
"""
attributes = tf_inspect.getmembers(estimator_class)
attribute_names = [a[0] for a in attributes]
tester.assertTrue('config' in attribute_names)
tester.assertTrue('evaluate' in attribute_names)
tester.assertTrue('export' in attribute_names)
tester.assertTrue('fit' in attribute_names)
tester.assertTrue('get_variable_names' in attribute_names)
tester.assertTrue('get_variable_value' in attribute_names)
tester.assertTrue('model_dir' in attribute_names)
tester.assertTrue('predict' in attribute_names)
def assert_in_range(min_value, max_value, key, metrics):
actual_value = metrics[key]
if actual_value < min_value:
raise ValueError('%s: %s < %s.' % (key, actual_value, min_value))
if actual_value > max_value:
raise ValueError('%s: %s > %s.' % (key, actual_value, max_value))
| apache-2.0 |
niceguydave/cmsplugin-filer | cmsplugin_filer_file/migrations/0001_initial.py | 17 | 11958 |
from south.db import db
from django.db import models
from cmsplugin_filer_file.models import *
class Migration:
depends_on = (
("filer", "0008_polymorphic__del_field_file__file_type_plugin_name"),
)
def forwards(self, orm):
# Adding model 'FilerFile'
db.create_table('cmsplugin_filerfile', (
('cmsplugin_ptr', orm['cmsplugin_filer_file.FilerFile:cmsplugin_ptr']),
('file', orm['cmsplugin_filer_file.FilerFile:file']),
('title', orm['cmsplugin_filer_file.FilerFile:title']),
))
db.send_create_signal('cmsplugin_filer_file', ['FilerFile'])
def backwards(self, orm):
# Deleting model 'FilerFile'
db.delete_table('cmsplugin_filerfile')
models = {
'auth.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']", 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)"},
'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': {
'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']", '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']", 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'cms.cmsplugin': {
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '5', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True', 'blank': 'True'}),
'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.CMSPlugin']"}),
'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.page': {
'changed_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}),
'created_by': ('django.db.models.fields.CharField', [], {'max_length': '70'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True', 'blank': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'menu_login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'moderator_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'blank': 'True'}),
'navigation_extenders': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}),
'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'publication_end_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'published': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True', 'blank': 'True'}),
'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}),
'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'reverse_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}),
'template': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cmsplugin_filer_file.filerfile': {
'Meta': {'db_table': "'cmsplugin_filerfile'"},
'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'file': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", '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'})
},
'filer.file': {
'_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'_file_type_plugin_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'file_field': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}),
'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': "orm['auth.User']"}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.folder': {
'Meta': {'unique_together': "(('parent', 'name'),)"},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_folders'", 'null': 'True', 'to': "orm['auth.User']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'sites.site': {
'Meta': {'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 = ['cmsplugin_filer_file']
| bsd-3-clause |
DarkFenX/Pyfa | gui/fitCommands/gui/fitSystemSecurity.py | 2 | 1237 | import wx
from service.fit import Fit
import eos.db
import gui.mainFrame
from gui import globalEvents as GE
from gui.fitCommands.helpers import InternalCommandHistory
from gui.fitCommands.calc.fitSystemSecurity import CalcChangeFitSystemSecurityCommand
class GuiChangeFitSystemSecurityCommand(wx.Command):
def __init__(self, fitID, secStatus):
wx.Command.__init__(self, True, 'Change Fit System Security')
self.internalHistory = InternalCommandHistory()
self.fitID = fitID
self.secStatus = secStatus
def Do(self):
cmd = CalcChangeFitSystemSecurityCommand(fitID=self.fitID, secStatus=self.secStatus)
success = self.internalHistory.submit(cmd)
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
eos.db.commit()
wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)))
return success
def Undo(self):
success = self.internalHistory.undoAll()
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
eos.db.commit()
wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)))
return success
| gpl-3.0 |
yannh/ansible-modules-core | network/basics/slurp.py | 134 | 2115 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: slurp
version_added: historical
short_description: Slurps a file from remote nodes
description:
- This module works like M(fetch). It is used for fetching a base64-
encoded blob containing the data in a remote file.
options:
src:
description:
- The file on the remote system to fetch. This I(must) be a file, not a
directory.
required: true
default: null
aliases: []
notes:
- "See also: M(fetch)"
requirements: []
author:
- "Ansible Core Team"
- "Michael DeHaan"
'''
EXAMPLES = '''
ansible host -m slurp -a 'src=/tmp/xx'
host | success >> {
"content": "aGVsbG8gQW5zaWJsZSB3b3JsZAo=",
"encoding": "base64"
}
'''
import base64
def main():
module = AnsibleModule(
argument_spec = dict(
src = dict(required=True, aliases=['path']),
),
supports_check_mode=True
)
source = os.path.expanduser(module.params['src'])
if not os.path.exists(source):
module.fail_json(msg="file not found: %s" % source)
if not os.access(source, os.R_OK):
module.fail_json(msg="file is not readable: %s" % source)
data = base64.b64encode(file(source).read())
module.exit_json(content=data, source=source, encoding='base64')
# import module snippets
from ansible.module_utils.basic import *
main()
| gpl-3.0 |
LihanHA/opencademy-project | opencademy/model/openacademy_session.py | 1 | 4454 | # -*- coding: utf-8 -*-
from datetime import timedelta
from openerp import api, exceptions, fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date(default=fields.Date.today)
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor",
domain=['|',
("instructor", "=", True),
("category_id.name", "ilike", "Teacher"),
])
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
taken_seats = fields.Float(string="Taken seats", compute='_taken_seats')
active = fields.Boolean(default=True)
end_date = fields.Date(string="End Date", store=True,
compute='_get_end_date', inverse='_set_end_date')
hours = fields.Float(string="Duration in hours",
compute='_get_hours', inverse='_set_hours')
attendees_count = fields.Integer(
string="Attendees count", compute='_get_attendees_count', store=True)
color = fields.Integer()
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('done', 'Done'),
], default='draft', readonly=True)
@api.one
@api.depends('seats', 'attendee_ids')
def _taken_seats(self):
if not self.seats:
self.taken_seats = 0
else:
self.taken_seats = 100.0 * len(self.attendee_ids) / self.seats
@api.onchange('seats', 'attendee_ids')
def _verify_valid_seats(self):
print "_verifying valid seats"
if self.seats < 0:
return {
'warning': {
'title': "Incorrect 'seats' value",
'message': "The number of available seats may not be negative",
},
}
if self.seats < len(self.attendee_ids):
return {
'warning': {
'title': "Too many attendees",
'message': "Increase seats or remove excess attendees",
},
}
@api.one
@api.constrains('instructor_id', 'attendee_ids')
def _check_instructor_not_in_attendees(self):
if self.instructor_id and self.instructor_id in self.attendee_ids:
raise exceptions.ValidationError("A session's instructor can't be an attendee")
@api.one
@api.depends('duration','start_date')
def _get_end_date(self):
print "_get_end_date------------------------------------------"
if not (self.start_date and self.duration):
self.end_date = self.start_date
return
# Add duration to start_date, but: Monday + 5 days = Saturday, so
# subtract one second to get on Friday instead
start = fields.Datetime.from_string(self.start_date)
duration = timedelta(days=self.duration, seconds=-1)
self.end_date = start + duration
@api.one
def _set_end_date(self):
if not (self.start_date and self.end_date):
return
print "_set_end_date_-----------------------------------------------------"
# Compute the difference between dates, but: Friday - Monday = 4 days,
# so add one day to get 5 days instead
start_date = fields.Datetime.from_string(self.start_date)
end_date = fields.Datetime.from_string(self.end_date)
self.duration = (end_date - start_date).days + 1
@api.one
@api.depends('duration')
def _get_hours(self):
self.hours = self.duration * 24
@api.one
def _set_hours(self):
self.duration = self.hours / 24
@api.one
@api.depends('attendee_ids')
def _get_attendees_count(self):
self.attendees_count = len(self.attendee_ids)
@api.one
def action_draft(self):
self.state = 'draft'
@api.one
def action_confirm(self):
self.state = 'confirmed'
@api.one
def action_done(self):
self.state = 'done'
# vim :expandtab:smart indent: tabstop=4:softtabstop=4:shifwidth=4;
| apache-2.0 |
LS80/script.module.livestreamer | lib/livestreamer/plugins/beattv.py | 34 | 10334 | import re
from collections import namedtuple
from io import BytesIO
try:
from Crypto.Cipher import AES
CAN_DECRYPT = True
except ImportError:
CAN_DECRYPT = False
from livestreamer.compat import range
from livestreamer.exceptions import StreamError
from livestreamer.packages.flashmedia.tag import (
AACAudioData, AudioData, AVCVideoData, RawData, Tag, VideoData
)
from livestreamer.packages.flashmedia.tag import (
AAC_PACKET_TYPE_RAW, AAC_PACKET_TYPE_SEQUENCE_HEADER,
AUDIO_BIT_RATE_16, AUDIO_CODEC_ID_AAC, AUDIO_RATE_44_KHZ, AUDIO_TYPE_STEREO,
AVC_PACKET_TYPE_NALU, AVC_PACKET_TYPE_SEQUENCE_HEADER,
TAG_TYPE_AUDIO, TAG_TYPE_VIDEO, VIDEO_CODEC_ID_AVC,
VIDEO_FRAME_TYPE_INTER_FRAME, VIDEO_FRAME_TYPE_KEY_FRAME
)
from livestreamer.packages.flashmedia.types import U8, U16BE, U32BE
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import Stream, StreamIOIterWrapper
from livestreamer.stream.flvconcat import FLVTagConcat
from livestreamer.stream.segmented import (
SegmentedStreamReader, SegmentedStreamWriter, SegmentedStreamWorker
)
HEADERS = {"User-Agent": "Mozilla/5.0"}
BEAT_PROGRAM = "http://www.be-at.tv/{0}.program"
BEAT_URL = "http://www.be-at.tv/{0}/{1}/{2}.{3}"
QUALITY_MAP = {
"audio_mono": 0,
"audio_stereo": 1,
"mobile_low": 5,
"mobile_medium": 6,
"web_medium": 10,
"web_high": 11,
"web_hd": 12
}
_url_re = re.compile("http(s)?://(\w+\.)?be-at.tv/")
_schema = validate.Schema(
validate.any(
None,
{
"status": int,
"media": [{
"duration": validate.any(float, int),
"offset": validate.any(float, int),
"id": int,
"parts": [{
"duration": validate.any(float, int),
"id": int,
"offset": validate.any(float, int),
validate.optional("recording"): int,
validate.optional("start"): validate.any(float, int)
}]
}]
}
)
)
Chunk = namedtuple("Chunk", "recording quality sequence extension")
class BeatFLVTagConcat(FLVTagConcat):
def __init__(self, *args, **kwargs):
FLVTagConcat.__init__(self, *args, **kwargs)
def decrypt_data(self, key, iv, data):
decryptor = AES.new(key, AES.MODE_CBC, iv)
return decryptor.decrypt(data)
def iter_tags(self, fd=None, buf=None, skip_header=None):
flags = U8.read(fd)
quality = flags & 15
version = flags >> 4
lookup_size = U16BE.read(fd)
enc_table = fd.read(lookup_size)
key = b""
iv = b""
for i in range(16):
key += fd.read(1)
iv += fd.read(1)
if not (key and iv):
return
dec_table = self.decrypt_data(key, iv, enc_table)
dstream = BytesIO(dec_table)
# Decode lookup table (ported from K-S-V BeatConvert.php)
while True:
flags = U8.read(dstream)
if not flags:
break
typ = flags >> 4
encrypted = (flags & 4) > 0
keyframe = (flags & 2) > 0
config = (flags & 1) > 0
time = U32BE.read(dstream)
data_length = U32BE.read(dstream)
if encrypted:
raw_length = U32BE.read(dstream)
else:
raw_length = data_length
# Decrypt encrypted tags
data = fd.read(data_length)
if encrypted:
data = self.decrypt_data(key, iv, data)
data = data[:raw_length]
# Create video tag
if typ == 1:
if version == 2:
if config:
avc = AVCVideoData(AVC_PACKET_TYPE_SEQUENCE_HEADER,
data=data)
else:
avc = AVCVideoData(AVC_PACKET_TYPE_NALU, data=data)
if keyframe:
videodata = VideoData(VIDEO_FRAME_TYPE_KEY_FRAME,
VIDEO_CODEC_ID_AVC, avc)
else:
videodata = VideoData(VIDEO_FRAME_TYPE_INTER_FRAME,
VIDEO_CODEC_ID_AVC, avc)
else:
videodata = RawData(data)
yield Tag(TAG_TYPE_VIDEO, time, videodata)
# Create audio tag
if typ == 2:
if version == 2:
if config:
aac = AACAudioData(AAC_PACKET_TYPE_SEQUENCE_HEADER,
data)
else:
aac = AACAudioData(AAC_PACKET_TYPE_RAW, data)
audiodata = AudioData(codec=AUDIO_CODEC_ID_AAC,
rate=AUDIO_RATE_44_KHZ,
bits=AUDIO_BIT_RATE_16,
type=AUDIO_TYPE_STEREO,
data=aac)
else:
audiodata = RawData(data)
yield Tag(TAG_TYPE_AUDIO, time, audiodata)
class BeatStreamWriter(SegmentedStreamWriter):
def __init__(self, *args, **kwargs):
SegmentedStreamWriter.__init__(self, *args, **kwargs)
self.concater = BeatFLVTagConcat(flatten_timestamps=True)
def fetch(self, chunk, retries=None):
if self.closed or not retries:
return
try:
url = BEAT_URL.format(chunk.recording,
chunk.quality,
chunk.sequence,
chunk.extension)
return self.session.http.get(url,
headers=HEADERS,
timeout=self.timeout,
exception=StreamError)
except StreamError as err:
self.logger.error(
"Failed to open chunk {0}/{1}/{2}: {3}",
chunk.recording, chunk.quality, chunk.sequence, err
)
return self.fetch(chunk, retries - 1)
def write(self, chunk, res, chunk_size=8192):
try:
fd = StreamIOIterWrapper(res.iter_content(chunk_size))
for data in self.concater.iter_chunks(fd=fd, skip_header=True):
self.reader.buffer.write(data)
if self.closed:
return
self.logger.debug("Download of chunk {0}/{1}/{2} complete",
chunk.recording,
chunk.quality,
chunk.sequence)
except IOError as err:
self.logger.error("Failed to read chunk {0}/{1}/{2}: {3}",
chunk.recording,
chunk.quality,
chunk.sequence, err)
class BeatStreamWorker(SegmentedStreamWorker):
def __init__(self, *args, **kwargs):
SegmentedStreamWorker.__init__(self, *args, **kwargs)
def iter_segments(self):
quality = QUALITY_MAP[self.stream.quality]
for part in self.stream.parts:
duration = part["duration"]
if not part.get("recording"):
recording = part["id"]
extension = "part"
else:
recording = part["recording"]
extension = "rec"
chunks = int(duration / 12) + 1
start = int(part.get("start", 0) / 12)
for sequence in range(start, chunks + start):
if self.closed:
return
self.logger.debug("Adding chunk {0}/{1}/{2} to queue",
recording, quality, sequence)
yield Chunk(recording, quality, sequence, extension)
class BeatStreamReader(SegmentedStreamReader):
__worker__ = BeatStreamWorker
__writer__ = BeatStreamWriter
def __init__(self, stream, *args, **kwargs):
self.logger = stream.session.logger.new_module("stream.beat")
SegmentedStreamReader.__init__(self, stream, *args, **kwargs)
class BeatStream(Stream):
__shortname__ = "beat"
def __init__(self, session, parts, quality):
Stream.__init__(self, session)
self.parts = parts
self.quality = quality
def __repr__(self):
return ("<BeatStream({0!r}, {1!r}>").format(len(self.parts),
self.quality)
def __json__(self):
return dict(parts=self.parts, quality=self.quality,
**Stream.__json__(self))
def open(self):
if not CAN_DECRYPT:
raise StreamError(
"pyCrypto needs to be installed to decrypt this stream"
)
reader = BeatStreamReader(self)
reader.open()
return reader
class BeatTV(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
@classmethod
def stream_weight(cls, key):
weight = QUALITY_MAP.get(key)
if weight:
return weight, "beat"
return Plugin.stream_weight(key)
def _get_stream_info(self, url):
res = http.get(url, headers=HEADERS)
match = re.search("embed.swf\?p=(\d+)", res.text)
if not match:
return
program = match.group(1)
res = http.get(BEAT_PROGRAM.format(program), headers=HEADERS)
return http.json(res, schema=_schema)
def _get_streams(self):
info = self._get_stream_info(self.url)
if not info or info["status"] == 0:
return
parts = []
for media in info["media"]:
if not media["id"]:
continue
for part in media["parts"]:
if not part["duration"]:
continue
parts.append(part)
if not parts:
return
streams = {}
for quality in QUALITY_MAP:
streams[quality] = BeatStream(self.session, parts, quality)
return streams
__plugin__ = BeatTV
| bsd-2-clause |
mSenyor/sl4a | python/src/Lib/lib2to3/fixes/fix_print.py | 53 | 2957 | # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for print.
Change:
'print' into 'print()'
'print ...' into 'print(...)'
'print ... ,' into 'print(..., end=" ")'
'print >>x, ...' into 'print(..., file=x)'
No changes are applied if print_function is imported from __future__
"""
# Local imports
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String, is_tuple
parend_expr = patcomp.compile_pattern(
"""atom< '(' [atom|STRING|NAME] ')' >"""
)
class FixPrint(fixer_base.ConditionalFix):
PATTERN = """
simple_stmt< any* bare='print' any* > | print_stmt
"""
skip_on = '__future__.print_function'
def transform(self, node, results):
assert results
if self.should_skip(node):
return
bare_print = results.get("bare")
if bare_print:
# Special-case print all by itself
bare_print.replace(Call(Name("print"), [],
prefix=bare_print.get_prefix()))
return
assert node.children[0] == Name("print")
args = node.children[1:]
if len(args) == 1 and parend_expr.match(args[0]):
# We don't want to keep sticking parens around an
# already-parenthesised expression.
return
sep = end = file = None
if args and args[-1] == Comma():
args = args[:-1]
end = " "
if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
assert len(args) >= 2
file = args[1].clone()
args = args[3:] # Strip a possible comma after the file expression
# Now synthesize a print(args, sep=..., end=..., file=...) node.
l_args = [arg.clone() for arg in args]
if l_args:
l_args[0].set_prefix("")
if sep is not None or end is not None or file is not None:
if sep is not None:
self.add_kwarg(l_args, "sep", String(repr(sep)))
if end is not None:
self.add_kwarg(l_args, "end", String(repr(end)))
if file is not None:
self.add_kwarg(l_args, "file", file)
n_stmt = Call(Name("print"), l_args)
n_stmt.set_prefix(node.get_prefix())
return n_stmt
def add_kwarg(self, l_nodes, s_kwd, n_expr):
# XXX All this prefix-setting may lose comments (though rarely)
n_expr.set_prefix("")
n_argument = pytree.Node(self.syms.argument,
(Name(s_kwd),
pytree.Leaf(token.EQUAL, "="),
n_expr))
if l_nodes:
l_nodes.append(Comma())
n_argument.set_prefix(" ")
l_nodes.append(n_argument)
| apache-2.0 |
denniszollo/libsbp | python/sbp/observation.py | 2 | 5567 | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Fergus Noble <fergus@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
from construct import *
from sbp import SBP
from sbp.utils import fmt_repr
# Automatically generated from piksi/yaml/swiftnav/sbp/observation.yaml
# with generate.py at 2015-03-24 09:47:42.317363. Please do not hand edit!
class ObsGPSTime(object):
"""ObsGPSTime.
A wire-appropriate GPS time, defined as the number of
milliseconds since beginning of the week on the Saturday/Sunday
transition.
Parameters
----------
tow : int
Milliseconds since start of GPS week
wn : int
GPS week number
"""
_parser = Struct("ObsGPSTime",
ULInt32('tow'),
ULInt16('wn'),)
def __init__(self, payload):
self.from_binary(payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = ObsGPSTime._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return ObsGPSTime.build(self.__dict__)
class CarrierPhase(object):
"""CarrierPhase.
Carrier phase measurement in cycles represented as a 40-bit
fixed point number with Q32.8 layout, i.e. 32-bits of whole
cycles and 8-bits of fractional cycles.
Parameters
----------
i : int
Carrier phase whole cycles.
f : int
Carrier phase fractional part.
"""
_parser = Struct("CarrierPhase",
SLInt32('i'),
ULInt8('f'),)
def __init__(self, payload):
self.from_binary(payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = CarrierPhase._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return CarrierPhase.build(self.__dict__)
class ObservationHeader(object):
"""ObservationHeader.
Header of a GPS observation message
Parameters
----------
t : ObsGPSTime
GPS time of this observation.
n_obs : int
Total number of observations. First nibble is the size
of the sequence (n), second nibble is the zero-indexed
counter (ith packet of n)
"""
_parser = Struct("ObservationHeader",
Struct('t', ObsGPSTime._parser),
ULInt8('n_obs'),)
def __init__(self, payload):
self.from_binary(payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = ObservationHeader._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return ObservationHeader.build(self.__dict__)
class PackedObsContent(object):
"""PackedObsContent.
GPS observations for a particular satellite signal.
Parameters
----------
P : int
Pseudorange observation.
L : CarrierPhase
Carrier phase observation.
cn0 : int
Carrier-to-Noise density
lock : int
Lock indicator. This value changes whenever a satellite
signal has lost and regained lock, indicating that the
carrier phase ambiguity may have changed. There is no
significance to the value of the lock indicator.
prn : int
PRN identifier of the satellite signal
"""
_parser = Struct("PackedObsContent",
ULInt32('P'),
Struct('L', CarrierPhase._parser),
ULInt8('cn0'),
ULInt16('lock'),
ULInt8('prn'),)
def __init__(self, payload):
self.from_binary(payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = PackedObsContent._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return PackedObsContent.build(self.__dict__)
SBP_MSG_OBS = 0x0045
class MsgObs(SBP):
"""SBP class for message MSG_OBS (0x0045).
Parameters
----------
header : ObservationHeader
Header of a GPS observation message
obs : array
Observations
"""
_parser = Struct("MsgObs",
Struct('header', ObservationHeader._parser),
Struct('obs', OptionalGreedyRange(PackedObsContent._parser)),)
def __init__(self, sbp):
self.__dict__.update(sbp.__dict__)
self.from_binary(sbp.payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = MsgObs._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return MsgObs.build(self.__dict__)
SBP_MSG_BASE_POS = 0x0044
class MsgBasePos(SBP):
"""SBP class for message MSG_BASE_POS (0x0044).
Parameters
----------
lat : double
Latitude
lon : double
Longitude
height : double
Height
"""
_parser = Struct("MsgBasePos",
LFloat64('lat'),
LFloat64('lon'),
LFloat64('height'),)
def __init__(self, sbp):
self.__dict__.update(sbp.__dict__)
self.from_binary(sbp.payload)
def __repr__(self):
return fmt_repr(self)
def from_binary(self, d):
p = MsgBasePos._parser.parse(d)
self.__dict__.update(dict(p.viewitems()))
def to_binary(self):
return MsgBasePos.build(self.__dict__)
msg_classes = {
0x0045: MsgObs,
0x0044: MsgBasePos,
}
def sbp_decode(t, d):
return msg_classes[t](d) | lgpl-3.0 |
robovm/robovm-studio | python/lib/Lib/email/test/test_email.py | 84 | 118877 | # Copyright (C) 2001-2007 Python Software Foundation
# Contact: email-sig@python.org
# email package unit tests
import os
import sys
import time
import base64
import difflib
import unittest
import warnings
from cStringIO import StringIO
import email
from email.Charset import Charset
from email.Header import Header, decode_header, make_header
from email.Parser import Parser, HeaderParser
from email.Generator import Generator, DecodedGenerator
from email.Message import Message
from email.MIMEAudio import MIMEAudio
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email.MIMEMessage import MIMEMessage
from email.MIMEMultipart import MIMEMultipart
from email import Utils
from email import Errors
from email import Encoders
from email import Iterators
from email import base64MIME
from email import quopriMIME
from test.test_support import findfile, run_unittest
from email.test import __file__ as landmark
NL = '\n'
EMPTYSTRING = ''
SPACE = ' '
def openfile(filename, mode='r'):
path = os.path.join(os.path.dirname(landmark), 'data', filename)
return open(path, mode)
# Base test class
class TestEmailBase(unittest.TestCase):
def ndiffAssertEqual(self, first, second):
"""Like failUnlessEqual except use ndiff for readable output."""
if first <> second:
sfirst = str(first)
ssecond = str(second)
diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
fp = StringIO()
print >> fp, NL, NL.join(diff)
raise self.failureException, fp.getvalue()
def _msgobj(self, filename):
fp = openfile(findfile(filename))
try:
msg = email.message_from_file(fp)
finally:
fp.close()
return msg
# Test various aspects of the Message class's API
class TestMessageAPI(TestEmailBase):
def test_get_all(self):
eq = self.assertEqual
msg = self._msgobj('msg_20.txt')
eq(msg.get_all('cc'), ['ccc@zzz.org', 'ddd@zzz.org', 'eee@zzz.org'])
eq(msg.get_all('xx', 'n/a'), 'n/a')
def test_getset_charset(self):
eq = self.assertEqual
msg = Message()
eq(msg.get_charset(), None)
charset = Charset('iso-8859-1')
msg.set_charset(charset)
eq(msg['mime-version'], '1.0')
eq(msg.get_content_type(), 'text/plain')
eq(msg['content-type'], 'text/plain; charset="iso-8859-1"')
eq(msg.get_param('charset'), 'iso-8859-1')
eq(msg['content-transfer-encoding'], 'quoted-printable')
eq(msg.get_charset().input_charset, 'iso-8859-1')
# Remove the charset
msg.set_charset(None)
eq(msg.get_charset(), None)
eq(msg['content-type'], 'text/plain')
# Try adding a charset when there's already MIME headers present
msg = Message()
msg['MIME-Version'] = '2.0'
msg['Content-Type'] = 'text/x-weird'
msg['Content-Transfer-Encoding'] = 'quinted-puntable'
msg.set_charset(charset)
eq(msg['mime-version'], '2.0')
eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"')
eq(msg['content-transfer-encoding'], 'quinted-puntable')
def test_set_charset_from_string(self):
eq = self.assertEqual
msg = Message()
msg.set_charset('us-ascii')
eq(msg.get_charset().input_charset, 'us-ascii')
eq(msg['content-type'], 'text/plain; charset="us-ascii"')
def test_set_payload_with_charset(self):
msg = Message()
charset = Charset('iso-8859-1')
msg.set_payload('This is a string payload', charset)
self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1')
def test_get_charsets(self):
eq = self.assertEqual
msg = self._msgobj('msg_08.txt')
charsets = msg.get_charsets()
eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r'])
msg = self._msgobj('msg_09.txt')
charsets = msg.get_charsets('dingbat')
eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat',
'koi8-r'])
msg = self._msgobj('msg_12.txt')
charsets = msg.get_charsets()
eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2',
'iso-8859-3', 'us-ascii', 'koi8-r'])
def test_get_filename(self):
eq = self.assertEqual
msg = self._msgobj('msg_04.txt')
filenames = [p.get_filename() for p in msg.get_payload()]
eq(filenames, ['msg.txt', 'msg.txt'])
msg = self._msgobj('msg_07.txt')
subpart = msg.get_payload(1)
eq(subpart.get_filename(), 'dingusfish.gif')
def test_get_filename_with_name_parameter(self):
eq = self.assertEqual
msg = self._msgobj('msg_44.txt')
filenames = [p.get_filename() for p in msg.get_payload()]
eq(filenames, ['msg.txt', 'msg.txt'])
def test_get_boundary(self):
eq = self.assertEqual
msg = self._msgobj('msg_07.txt')
# No quotes!
eq(msg.get_boundary(), 'BOUNDARY')
def test_set_boundary(self):
eq = self.assertEqual
# This one has no existing boundary parameter, but the Content-Type:
# header appears fifth.
msg = self._msgobj('msg_01.txt')
msg.set_boundary('BOUNDARY')
header, value = msg.items()[4]
eq(header.lower(), 'content-type')
eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"')
# This one has a Content-Type: header, with a boundary, stuck in the
# middle of its headers. Make sure the order is preserved; it should
# be fifth.
msg = self._msgobj('msg_04.txt')
msg.set_boundary('BOUNDARY')
header, value = msg.items()[4]
eq(header.lower(), 'content-type')
eq(value, 'multipart/mixed; boundary="BOUNDARY"')
# And this one has no Content-Type: header at all.
msg = self._msgobj('msg_03.txt')
self.assertRaises(Errors.HeaderParseError,
msg.set_boundary, 'BOUNDARY')
def test_get_decoded_payload(self):
eq = self.assertEqual
msg = self._msgobj('msg_10.txt')
# The outer message is a multipart
eq(msg.get_payload(decode=True), None)
# Subpart 1 is 7bit encoded
eq(msg.get_payload(0).get_payload(decode=True),
'This is a 7bit encoded message.\n')
# Subpart 2 is quopri
eq(msg.get_payload(1).get_payload(decode=True),
'\xa1This is a Quoted Printable encoded message!\n')
# Subpart 3 is base64
eq(msg.get_payload(2).get_payload(decode=True),
'This is a Base64 encoded message.')
# Subpart 4 has no Content-Transfer-Encoding: header.
eq(msg.get_payload(3).get_payload(decode=True),
'This has no Content-Transfer-Encoding: header.\n')
def test_get_decoded_uu_payload(self):
eq = self.assertEqual
msg = Message()
msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n')
for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
msg['content-transfer-encoding'] = cte
eq(msg.get_payload(decode=True), 'hello world')
# Now try some bogus data
msg.set_payload('foo')
eq(msg.get_payload(decode=True), 'foo')
def test_decode_bogus_uu_payload_quietly(self):
msg = Message()
msg.set_payload('begin 664 foo.txt\n%<W1F=0000H \n \nend\n')
msg['Content-Transfer-Encoding'] = 'x-uuencode'
old_stderr = sys.stderr
try:
sys.stderr = sfp = StringIO()
# We don't care about the payload
msg.get_payload(decode=True)
finally:
sys.stderr = old_stderr
self.assertEqual(sfp.getvalue(), '')
def test_decoded_generator(self):
eq = self.assertEqual
msg = self._msgobj('msg_07.txt')
fp = openfile('msg_17.txt')
try:
text = fp.read()
finally:
fp.close()
s = StringIO()
g = DecodedGenerator(s)
g.flatten(msg)
eq(s.getvalue(), text)
def test__contains__(self):
msg = Message()
msg['From'] = 'Me'
msg['to'] = 'You'
# Check for case insensitivity
self.failUnless('from' in msg)
self.failUnless('From' in msg)
self.failUnless('FROM' in msg)
self.failUnless('to' in msg)
self.failUnless('To' in msg)
self.failUnless('TO' in msg)
def test_as_string(self):
eq = self.assertEqual
msg = self._msgobj('msg_01.txt')
fp = openfile('msg_01.txt')
try:
text = fp.read()
finally:
fp.close()
eq(text, msg.as_string())
fullrepr = str(msg)
lines = fullrepr.split('\n')
self.failUnless(lines[0].startswith('From '))
eq(text, NL.join(lines[1:]))
def test_bad_param(self):
msg = email.message_from_string("Content-Type: blarg; baz; boo\n")
self.assertEqual(msg.get_param('baz'), '')
def test_missing_filename(self):
msg = email.message_from_string("From: foo\n")
self.assertEqual(msg.get_filename(), None)
def test_bogus_filename(self):
msg = email.message_from_string(
"Content-Disposition: blarg; filename\n")
self.assertEqual(msg.get_filename(), '')
def test_missing_boundary(self):
msg = email.message_from_string("From: foo\n")
self.assertEqual(msg.get_boundary(), None)
def test_get_params(self):
eq = self.assertEqual
msg = email.message_from_string(
'X-Header: foo=one; bar=two; baz=three\n')
eq(msg.get_params(header='x-header'),
[('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
msg = email.message_from_string(
'X-Header: foo; bar=one; baz=two\n')
eq(msg.get_params(header='x-header'),
[('foo', ''), ('bar', 'one'), ('baz', 'two')])
eq(msg.get_params(), None)
msg = email.message_from_string(
'X-Header: foo; bar="one"; baz=two\n')
eq(msg.get_params(header='x-header'),
[('foo', ''), ('bar', 'one'), ('baz', 'two')])
def test_get_param_liberal(self):
msg = Message()
msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"'
self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG')
def test_get_param(self):
eq = self.assertEqual
msg = email.message_from_string(
"X-Header: foo=one; bar=two; baz=three\n")
eq(msg.get_param('bar', header='x-header'), 'two')
eq(msg.get_param('quuz', header='x-header'), None)
eq(msg.get_param('quuz'), None)
msg = email.message_from_string(
'X-Header: foo; bar="one"; baz=two\n')
eq(msg.get_param('foo', header='x-header'), '')
eq(msg.get_param('bar', header='x-header'), 'one')
eq(msg.get_param('baz', header='x-header'), 'two')
# XXX: We are not RFC-2045 compliant! We cannot parse:
# msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
# msg.get_param("weird")
# yet.
def test_get_param_funky_continuation_lines(self):
msg = self._msgobj('msg_22.txt')
self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG')
def test_get_param_with_semis_in_quotes(self):
msg = email.message_from_string(
'Content-Type: image/pjpeg; name="Jim&&Jill"\n')
self.assertEqual(msg.get_param('name'), 'Jim&&Jill')
self.assertEqual(msg.get_param('name', unquote=False),
'"Jim&&Jill"')
def test_has_key(self):
msg = email.message_from_string('Header: exists')
self.failUnless(msg.has_key('header'))
self.failUnless(msg.has_key('Header'))
self.failUnless(msg.has_key('HEADER'))
self.failIf(msg.has_key('headeri'))
def test_set_param(self):
eq = self.assertEqual
msg = Message()
msg.set_param('charset', 'iso-2022-jp')
eq(msg.get_param('charset'), 'iso-2022-jp')
msg.set_param('importance', 'high value')
eq(msg.get_param('importance'), 'high value')
eq(msg.get_param('importance', unquote=False), '"high value"')
eq(msg.get_params(), [('text/plain', ''),
('charset', 'iso-2022-jp'),
('importance', 'high value')])
eq(msg.get_params(unquote=False), [('text/plain', ''),
('charset', '"iso-2022-jp"'),
('importance', '"high value"')])
msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy')
eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
def test_del_param(self):
eq = self.assertEqual
msg = self._msgobj('msg_05.txt')
eq(msg.get_params(),
[('multipart/report', ''), ('report-type', 'delivery-status'),
('boundary', 'D1690A7AC1.996856090/mail.example.com')])
old_val = msg.get_param("report-type")
msg.del_param("report-type")
eq(msg.get_params(),
[('multipart/report', ''),
('boundary', 'D1690A7AC1.996856090/mail.example.com')])
msg.set_param("report-type", old_val)
eq(msg.get_params(),
[('multipart/report', ''),
('boundary', 'D1690A7AC1.996856090/mail.example.com'),
('report-type', old_val)])
def test_del_param_on_other_header(self):
msg = Message()
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
msg.del_param('filename', 'content-disposition')
self.assertEqual(msg['content-disposition'], 'attachment')
def test_set_type(self):
eq = self.assertEqual
msg = Message()
self.assertRaises(ValueError, msg.set_type, 'text')
msg.set_type('text/plain')
eq(msg['content-type'], 'text/plain')
msg.set_param('charset', 'us-ascii')
eq(msg['content-type'], 'text/plain; charset="us-ascii"')
msg.set_type('text/html')
eq(msg['content-type'], 'text/html; charset="us-ascii"')
def test_set_type_on_other_header(self):
msg = Message()
msg['X-Content-Type'] = 'text/plain'
msg.set_type('application/octet-stream', 'X-Content-Type')
self.assertEqual(msg['x-content-type'], 'application/octet-stream')
def test_get_content_type_missing(self):
msg = Message()
self.assertEqual(msg.get_content_type(), 'text/plain')
def test_get_content_type_missing_with_default_type(self):
msg = Message()
msg.set_default_type('message/rfc822')
self.assertEqual(msg.get_content_type(), 'message/rfc822')
def test_get_content_type_from_message_implicit(self):
msg = self._msgobj('msg_30.txt')
self.assertEqual(msg.get_payload(0).get_content_type(),
'message/rfc822')
def test_get_content_type_from_message_explicit(self):
msg = self._msgobj('msg_28.txt')
self.assertEqual(msg.get_payload(0).get_content_type(),
'message/rfc822')
def test_get_content_type_from_message_text_plain_implicit(self):
msg = self._msgobj('msg_03.txt')
self.assertEqual(msg.get_content_type(), 'text/plain')
def test_get_content_type_from_message_text_plain_explicit(self):
msg = self._msgobj('msg_01.txt')
self.assertEqual(msg.get_content_type(), 'text/plain')
def test_get_content_maintype_missing(self):
msg = Message()
self.assertEqual(msg.get_content_maintype(), 'text')
def test_get_content_maintype_missing_with_default_type(self):
msg = Message()
msg.set_default_type('message/rfc822')
self.assertEqual(msg.get_content_maintype(), 'message')
def test_get_content_maintype_from_message_implicit(self):
msg = self._msgobj('msg_30.txt')
self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
def test_get_content_maintype_from_message_explicit(self):
msg = self._msgobj('msg_28.txt')
self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
def test_get_content_maintype_from_message_text_plain_implicit(self):
msg = self._msgobj('msg_03.txt')
self.assertEqual(msg.get_content_maintype(), 'text')
def test_get_content_maintype_from_message_text_plain_explicit(self):
msg = self._msgobj('msg_01.txt')
self.assertEqual(msg.get_content_maintype(), 'text')
def test_get_content_subtype_missing(self):
msg = Message()
self.assertEqual(msg.get_content_subtype(), 'plain')
def test_get_content_subtype_missing_with_default_type(self):
msg = Message()
msg.set_default_type('message/rfc822')
self.assertEqual(msg.get_content_subtype(), 'rfc822')
def test_get_content_subtype_from_message_implicit(self):
msg = self._msgobj('msg_30.txt')
self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
def test_get_content_subtype_from_message_explicit(self):
msg = self._msgobj('msg_28.txt')
self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
def test_get_content_subtype_from_message_text_plain_implicit(self):
msg = self._msgobj('msg_03.txt')
self.assertEqual(msg.get_content_subtype(), 'plain')
def test_get_content_subtype_from_message_text_plain_explicit(self):
msg = self._msgobj('msg_01.txt')
self.assertEqual(msg.get_content_subtype(), 'plain')
def test_get_content_maintype_error(self):
msg = Message()
msg['Content-Type'] = 'no-slash-in-this-string'
self.assertEqual(msg.get_content_maintype(), 'text')
def test_get_content_subtype_error(self):
msg = Message()
msg['Content-Type'] = 'no-slash-in-this-string'
self.assertEqual(msg.get_content_subtype(), 'plain')
def test_replace_header(self):
eq = self.assertEqual
msg = Message()
msg.add_header('First', 'One')
msg.add_header('Second', 'Two')
msg.add_header('Third', 'Three')
eq(msg.keys(), ['First', 'Second', 'Third'])
eq(msg.values(), ['One', 'Two', 'Three'])
msg.replace_header('Second', 'Twenty')
eq(msg.keys(), ['First', 'Second', 'Third'])
eq(msg.values(), ['One', 'Twenty', 'Three'])
msg.add_header('First', 'Eleven')
msg.replace_header('First', 'One Hundred')
eq(msg.keys(), ['First', 'Second', 'Third', 'First'])
eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven'])
self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
def test_broken_base64_payload(self):
x = 'AwDp0P7//y6LwKEAcPa/6Q=9'
msg = Message()
msg['content-type'] = 'audio/x-midi'
msg['content-transfer-encoding'] = 'base64'
msg.set_payload(x)
self.assertEqual(msg.get_payload(decode=True), x)
def test_get_content_charset(self):
msg = Message()
msg.set_charset('us-ascii')
self.assertEqual('us-ascii', msg.get_content_charset())
msg.set_charset(u'us-ascii')
self.assertEqual('us-ascii', msg.get_content_charset())
# Test the email.Encoders module
class TestEncoders(unittest.TestCase):
def test_encode_empty_payload(self):
eq = self.assertEqual
msg = Message()
msg.set_charset('us-ascii')
eq(msg['content-transfer-encoding'], '7bit')
def test_default_cte(self):
eq = self.assertEqual
msg = MIMEText('hello world')
eq(msg['content-transfer-encoding'], '7bit')
def test_default_cte(self):
eq = self.assertEqual
# With no explicit _charset its us-ascii, and all are 7-bit
msg = MIMEText('hello world')
eq(msg['content-transfer-encoding'], '7bit')
# Similar, but with 8-bit data
msg = MIMEText('hello \xf8 world')
eq(msg['content-transfer-encoding'], '8bit')
# And now with a different charset
msg = MIMEText('hello \xf8 world', _charset='iso-8859-1')
eq(msg['content-transfer-encoding'], 'quoted-printable')
# Test long header wrapping
class TestLongHeaders(TestEmailBase):
def test_split_long_continuation(self):
eq = self.ndiffAssertEqual
msg = email.message_from_string("""\
Subject: bug demonstration
\t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
\tmore text
test
""")
sfp = StringIO()
g = Generator(sfp)
g.flatten(msg)
eq(sfp.getvalue(), """\
Subject: bug demonstration
\t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
\tmore text
test
""")
def test_another_long_almost_unsplittable_header(self):
eq = self.ndiffAssertEqual
hstr = """\
bug demonstration
\t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
\tmore text"""
h = Header(hstr, continuation_ws='\t')
eq(h.encode(), """\
bug demonstration
\t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
\tmore text""")
h = Header(hstr)
eq(h.encode(), """\
bug demonstration
12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
more text""")
def test_long_nonstring(self):
eq = self.ndiffAssertEqual
g = Charset("iso-8859-1")
cz = Charset("iso-8859-2")
utf8 = Charset("utf-8")
g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
h = Header(g_head, g, header_name='Subject')
h.append(cz_head, cz)
h.append(utf8_head, utf8)
msg = Message()
msg['Subject'] = h
sfp = StringIO()
g = Generator(sfp)
g.flatten(msg)
eq(sfp.getvalue(), """\
Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
=?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
=?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
=?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
=?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
=?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
=?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
=?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
=?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
=?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
=?utf-8?b?44Gm44GE44G+44GZ44CC?=
""")
eq(h.encode(), """\
=?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
=?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
=?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
=?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
=?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
=?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
=?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
=?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
=?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
=?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
=?utf-8?b?44Gm44GE44G+44GZ44CC?=""")
def test_long_header_encode(self):
eq = self.ndiffAssertEqual
h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
header_name='X-Foobar-Spoink-Defrobnit')
eq(h.encode(), '''\
wasnipoop; giraffes="very-long-necked-animals";
spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
def test_long_header_encode_with_tab_continuation(self):
eq = self.ndiffAssertEqual
h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
header_name='X-Foobar-Spoink-Defrobnit',
continuation_ws='\t')
eq(h.encode(), '''\
wasnipoop; giraffes="very-long-necked-animals";
\tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
def test_header_splitter(self):
eq = self.ndiffAssertEqual
msg = MIMEText('')
# It'd be great if we could use add_header() here, but that doesn't
# guarantee an order of the parameters.
msg['X-Foobar-Spoink-Defrobnit'] = (
'wasnipoop; giraffes="very-long-necked-animals"; '
'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"')
sfp = StringIO()
g = Generator(sfp)
g.flatten(msg)
eq(sfp.getvalue(), '''\
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals";
\tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"
''')
def test_no_semis_header_splitter(self):
eq = self.ndiffAssertEqual
msg = Message()
msg['From'] = 'test@dom.ain'
msg['References'] = SPACE.join(['<%d@dom.ain>' % i for i in range(10)])
msg.set_payload('Test')
sfp = StringIO()
g = Generator(sfp)
g.flatten(msg)
eq(sfp.getvalue(), """\
From: test@dom.ain
References: <0@dom.ain> <1@dom.ain> <2@dom.ain> <3@dom.ain> <4@dom.ain>
\t<5@dom.ain> <6@dom.ain> <7@dom.ain> <8@dom.ain> <9@dom.ain>
Test""")
def test_no_split_long_header(self):
eq = self.ndiffAssertEqual
hstr = 'References: ' + 'x' * 80
h = Header(hstr, continuation_ws='\t')
eq(h.encode(), """\
References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""")
def test_splitting_multiple_long_lines(self):
eq = self.ndiffAssertEqual
hstr = """\
from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
"""
h = Header(hstr, continuation_ws='\t')
eq(h.encode(), """\
from babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)""")
def test_splitting_first_line_only_is_long(self):
eq = self.ndiffAssertEqual
hstr = """\
from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca)
\tby kronos.mems-exchange.org with esmtp (Exim 4.05)
\tid 17k4h5-00034i-00
\tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400"""
h = Header(hstr, maxlinelen=78, header_name='Received',
continuation_ws='\t')
eq(h.encode(), """\
from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93]
\thelo=cthulhu.gerg.ca)
\tby kronos.mems-exchange.org with esmtp (Exim 4.05)
\tid 17k4h5-00034i-00
\tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400""")
def test_long_8bit_header(self):
eq = self.ndiffAssertEqual
msg = Message()
h = Header('Britische Regierung gibt', 'iso-8859-1',
header_name='Subject')
h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte')
msg['Subject'] = h
eq(msg.as_string(), """\
Subject: =?iso-8859-1?q?Britische_Regierung_gibt?= =?iso-8859-1?q?gr=FCnes?=
=?iso-8859-1?q?_Licht_f=FCr_Offshore-Windkraftprojekte?=
""")
def test_long_8bit_header_no_charset(self):
eq = self.ndiffAssertEqual
msg = Message()
msg['Reply-To'] = 'Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>'
eq(msg.as_string(), """\
Reply-To: Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>
""")
def test_long_to_header(self):
eq = self.ndiffAssertEqual
to = '"Someone Test #A" <someone@eecs.umich.edu>,<someone@eecs.umich.edu>,"Someone Test #B" <someone@umich.edu>, "Someone Test #C" <someone@eecs.umich.edu>, "Someone Test #D" <someone@eecs.umich.edu>'
msg = Message()
msg['To'] = to
eq(msg.as_string(0), '''\
To: "Someone Test #A" <someone@eecs.umich.edu>, <someone@eecs.umich.edu>,
\t"Someone Test #B" <someone@umich.edu>,
\t"Someone Test #C" <someone@eecs.umich.edu>,
\t"Someone Test #D" <someone@eecs.umich.edu>
''')
def test_long_line_after_append(self):
eq = self.ndiffAssertEqual
s = 'This is an example of string which has almost the limit of header length.'
h = Header(s)
h.append('Add another line.')
eq(h.encode(), """\
This is an example of string which has almost the limit of header length.
Add another line.""")
def test_shorter_line_with_append(self):
eq = self.ndiffAssertEqual
s = 'This is a shorter line.'
h = Header(s)
h.append('Add another sentence. (Surprise?)')
eq(h.encode(),
'This is a shorter line. Add another sentence. (Surprise?)')
def test_long_field_name(self):
eq = self.ndiffAssertEqual
fn = 'X-Very-Very-Very-Long-Header-Name'
gs = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
h = Header(gs, 'iso-8859-1', header_name=fn)
# BAW: this seems broken because the first line is too long
eq(h.encode(), """\
=?iso-8859-1?q?Die_Mieter_treten_hier_?=
=?iso-8859-1?q?ein_werden_mit_einem_Foerderband_komfortabel_den_Korridor_?=
=?iso-8859-1?q?entlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_g?=
=?iso-8859-1?q?egen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")
def test_long_received_header(self):
h = 'from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; Wed, 05 Mar 2003 18:10:18 -0700'
msg = Message()
msg['Received-1'] = Header(h, continuation_ws='\t')
msg['Received-2'] = h
self.assertEqual(msg.as_string(), """\
Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
\throthgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
\tWed, 05 Mar 2003 18:10:18 -0700
Received-2: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
\throthgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
\tWed, 05 Mar 2003 18:10:18 -0700
""")
def test_string_headerinst_eq(self):
h = '<15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner\'s message of "Thu, 6 Mar 2003 13:58:21 +0100")'
msg = Message()
msg['Received-1'] = Header(h, header_name='Received-1',
continuation_ws='\t')
msg['Received-2'] = h
self.assertEqual(msg.as_string(), """\
Received-1: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
\t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
Received-2: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
\t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
""")
def test_long_unbreakable_lines_with_continuation(self):
eq = self.ndiffAssertEqual
msg = Message()
t = """\
iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp"""
msg['Face-1'] = t
msg['Face-2'] = Header(t, header_name='Face-2')
eq(msg.as_string(), """\
Face-1: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
\tlocQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
Face-2: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
""")
def test_another_long_multiline_header(self):
eq = self.ndiffAssertEqual
m = '''\
Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with Microsoft SMTPSVC(5.0.2195.4905);
\tWed, 16 Oct 2002 07:41:11 -0700'''
msg = email.message_from_string(m)
eq(msg.as_string(), '''\
Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with
\tMicrosoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700
''')
def test_long_lines_with_different_header(self):
eq = self.ndiffAssertEqual
h = """\
List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
msg = Message()
msg['List'] = h
msg['List'] = Header(h, header_name='List')
eq(msg.as_string(), """\
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
\t<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
""")
# Test mangling of "From " lines in the body of a message
class TestFromMangling(unittest.TestCase):
def setUp(self):
self.msg = Message()
self.msg['From'] = 'aaa@bbb.org'
self.msg.set_payload("""\
From the desk of A.A.A.:
Blah blah blah
""")
def test_mangled_from(self):
s = StringIO()
g = Generator(s, mangle_from_=True)
g.flatten(self.msg)
self.assertEqual(s.getvalue(), """\
From: aaa@bbb.org
>From the desk of A.A.A.:
Blah blah blah
""")
def test_dont_mangle_from(self):
s = StringIO()
g = Generator(s, mangle_from_=False)
g.flatten(self.msg)
self.assertEqual(s.getvalue(), """\
From: aaa@bbb.org
From the desk of A.A.A.:
Blah blah blah
""")
# Test the basic MIMEAudio class
class TestMIMEAudio(unittest.TestCase):
def setUp(self):
# Make sure we pick up the audiotest.au that lives in email/test/data.
# In Python, there's an audiotest.au living in Lib/test but that isn't
# included in some binary distros that don't include the test
# package. The trailing empty string on the .join() is significant
# since findfile() will do a dirname().
datadir = os.path.join(os.path.dirname(landmark), 'data', '')
fp = open(findfile('audiotest.au', datadir), 'rb')
try:
self._audiodata = fp.read()
finally:
fp.close()
self._au = MIMEAudio(self._audiodata)
def test_guess_minor_type(self):
self.assertEqual(self._au.get_content_type(), 'audio/basic')
def test_encoding(self):
payload = self._au.get_payload()
self.assertEqual(base64.decodestring(payload), self._audiodata)
def test_checkSetMinor(self):
au = MIMEAudio(self._audiodata, 'fish')
self.assertEqual(au.get_content_type(), 'audio/fish')
def test_add_header(self):
eq = self.assertEqual
unless = self.failUnless
self._au.add_header('Content-Disposition', 'attachment',
filename='audiotest.au')
eq(self._au['content-disposition'],
'attachment; filename="audiotest.au"')
eq(self._au.get_params(header='content-disposition'),
[('attachment', ''), ('filename', 'audiotest.au')])
eq(self._au.get_param('filename', header='content-disposition'),
'audiotest.au')
missing = []
eq(self._au.get_param('attachment', header='content-disposition'), '')
unless(self._au.get_param('foo', failobj=missing,
header='content-disposition') is missing)
# Try some missing stuff
unless(self._au.get_param('foobar', missing) is missing)
unless(self._au.get_param('attachment', missing,
header='foobar') is missing)
# Test the basic MIMEImage class
class TestMIMEImage(unittest.TestCase):
def setUp(self):
fp = openfile('PyBanner048.gif')
try:
self._imgdata = fp.read()
finally:
fp.close()
self._im = MIMEImage(self._imgdata)
def test_guess_minor_type(self):
self.assertEqual(self._im.get_content_type(), 'image/gif')
def test_encoding(self):
payload = self._im.get_payload()
self.assertEqual(base64.decodestring(payload), self._imgdata)
def test_checkSetMinor(self):
im = MIMEImage(self._imgdata, 'fish')
self.assertEqual(im.get_content_type(), 'image/fish')
def test_add_header(self):
eq = self.assertEqual
unless = self.failUnless
self._im.add_header('Content-Disposition', 'attachment',
filename='dingusfish.gif')
eq(self._im['content-disposition'],
'attachment; filename="dingusfish.gif"')
eq(self._im.get_params(header='content-disposition'),
[('attachment', ''), ('filename', 'dingusfish.gif')])
eq(self._im.get_param('filename', header='content-disposition'),
'dingusfish.gif')
missing = []
eq(self._im.get_param('attachment', header='content-disposition'), '')
unless(self._im.get_param('foo', failobj=missing,
header='content-disposition') is missing)
# Try some missing stuff
unless(self._im.get_param('foobar', missing) is missing)
unless(self._im.get_param('attachment', missing,
header='foobar') is missing)
# Test the basic MIMEText class
class TestMIMEText(unittest.TestCase):
def setUp(self):
self._msg = MIMEText('hello there')
def test_types(self):
eq = self.assertEqual
unless = self.failUnless
eq(self._msg.get_content_type(), 'text/plain')
eq(self._msg.get_param('charset'), 'us-ascii')
missing = []
unless(self._msg.get_param('foobar', missing) is missing)
unless(self._msg.get_param('charset', missing, header='foobar')
is missing)
def test_payload(self):
self.assertEqual(self._msg.get_payload(), 'hello there')
self.failUnless(not self._msg.is_multipart())
def test_charset(self):
eq = self.assertEqual
msg = MIMEText('hello there', _charset='us-ascii')
eq(msg.get_charset().input_charset, 'us-ascii')
eq(msg['content-type'], 'text/plain; charset="us-ascii"')
# Test complicated multipart/* messages
class TestMultipart(TestEmailBase):
def setUp(self):
fp = openfile('PyBanner048.gif')
try:
data = fp.read()
finally:
fp.close()
container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
image = MIMEImage(data, name='dingusfish.gif')
image.add_header('content-disposition', 'attachment',
filename='dingusfish.gif')
intro = MIMEText('''\
Hi there,
This is the dingus fish.
''')
container.attach(intro)
container.attach(image)
container['From'] = 'Barry <barry@digicool.com>'
container['To'] = 'Dingus Lovers <cravindogs@cravindogs.com>'
container['Subject'] = 'Here is your dingus fish'
now = 987809702.54848599
timetuple = time.localtime(now)
if timetuple[-1] == 0:
tzsecs = time.timezone
else:
tzsecs = time.altzone
if tzsecs > 0:
sign = '-'
else:
sign = '+'
tzoffset = ' %s%04d' % (sign, tzsecs / 36)
container['Date'] = time.strftime(
'%a, %d %b %Y %H:%M:%S',
time.localtime(now)) + tzoffset
self._msg = container
self._im = image
self._txt = intro
def test_hierarchy(self):
# convenience
eq = self.assertEqual
unless = self.failUnless
raises = self.assertRaises
# tests
m = self._msg
unless(m.is_multipart())
eq(m.get_content_type(), 'multipart/mixed')
eq(len(m.get_payload()), 2)
raises(IndexError, m.get_payload, 2)
m0 = m.get_payload(0)
m1 = m.get_payload(1)
unless(m0 is self._txt)
unless(m1 is self._im)
eq(m.get_payload(), [m0, m1])
unless(not m0.is_multipart())
unless(not m1.is_multipart())
def test_empty_multipart_idempotent(self):
text = """\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
--BOUNDARY--
"""
msg = Parser().parsestr(text)
self.ndiffAssertEqual(text, msg.as_string())
def test_no_parts_in_a_multipart_with_none_epilogue(self):
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.set_boundary('BOUNDARY')
self.ndiffAssertEqual(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
--BOUNDARY--''')
def test_no_parts_in_a_multipart_with_empty_epilogue(self):
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.preamble = ''
outer.epilogue = ''
outer.set_boundary('BOUNDARY')
self.ndiffAssertEqual(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
--BOUNDARY--
''')
def test_one_part_in_a_multipart(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.set_boundary('BOUNDARY')
msg = MIMEText('hello world')
outer.attach(msg)
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--''')
def test_seq_parts_in_a_multipart_with_empty_preamble(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.preamble = ''
msg = MIMEText('hello world')
outer.attach(msg)
outer.set_boundary('BOUNDARY')
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--''')
def test_seq_parts_in_a_multipart_with_none_preamble(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.preamble = None
msg = MIMEText('hello world')
outer.attach(msg)
outer.set_boundary('BOUNDARY')
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--''')
def test_seq_parts_in_a_multipart_with_none_epilogue(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.epilogue = None
msg = MIMEText('hello world')
outer.attach(msg)
outer.set_boundary('BOUNDARY')
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--''')
def test_seq_parts_in_a_multipart_with_empty_epilogue(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.epilogue = ''
msg = MIMEText('hello world')
outer.attach(msg)
outer.set_boundary('BOUNDARY')
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--
''')
def test_seq_parts_in_a_multipart_with_nl_epilogue(self):
eq = self.ndiffAssertEqual
outer = MIMEBase('multipart', 'mixed')
outer['Subject'] = 'A subject'
outer['To'] = 'aperson@dom.ain'
outer['From'] = 'bperson@dom.ain'
outer.epilogue = '\n'
msg = MIMEText('hello world')
outer.attach(msg)
outer.set_boundary('BOUNDARY')
eq(outer.as_string(), '''\
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME-Version: 1.0
Subject: A subject
To: aperson@dom.ain
From: bperson@dom.ain
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
hello world
--BOUNDARY--
''')
def test_message_external_body(self):
eq = self.assertEqual
msg = self._msgobj('msg_36.txt')
eq(len(msg.get_payload()), 2)
msg1 = msg.get_payload(1)
eq(msg1.get_content_type(), 'multipart/alternative')
eq(len(msg1.get_payload()), 2)
for subpart in msg1.get_payload():
eq(subpart.get_content_type(), 'message/external-body')
eq(len(subpart.get_payload()), 1)
subsubpart = subpart.get_payload(0)
eq(subsubpart.get_content_type(), 'text/plain')
def test_double_boundary(self):
# msg_37.txt is a multipart that contains two dash-boundary's in a
# row. Our interpretation of RFC 2046 calls for ignoring the second
# and subsequent boundaries.
msg = self._msgobj('msg_37.txt')
self.assertEqual(len(msg.get_payload()), 3)
def test_nested_inner_contains_outer_boundary(self):
eq = self.ndiffAssertEqual
# msg_38.txt has an inner part that contains outer boundaries. My
# interpretation of RFC 2046 (based on sections 5.1 and 5.1.2) say
# these are illegal and should be interpreted as unterminated inner
# parts.
msg = self._msgobj('msg_38.txt')
sfp = StringIO()
Iterators._structure(msg, sfp)
eq(sfp.getvalue(), """\
multipart/mixed
multipart/mixed
multipart/alternative
text/plain
text/plain
text/plain
text/plain
""")
def test_nested_with_same_boundary(self):
eq = self.ndiffAssertEqual
# msg 39.txt is similarly evil in that it's got inner parts that use
# the same boundary as outer parts. Again, I believe the way this is
# parsed is closest to the spirit of RFC 2046
msg = self._msgobj('msg_39.txt')
sfp = StringIO()
Iterators._structure(msg, sfp)
eq(sfp.getvalue(), """\
multipart/mixed
multipart/mixed
multipart/alternative
application/octet-stream
application/octet-stream
text/plain
""")
def test_boundary_in_non_multipart(self):
msg = self._msgobj('msg_40.txt')
self.assertEqual(msg.as_string(), '''\
MIME-Version: 1.0
Content-Type: text/html; boundary="--961284236552522269"
----961284236552522269
Content-Type: text/html;
Content-Transfer-Encoding: 7Bit
<html></html>
----961284236552522269--
''')
def test_boundary_with_leading_space(self):
eq = self.assertEqual
msg = email.message_from_string('''\
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=" XXXX"
-- XXXX
Content-Type: text/plain
-- XXXX
Content-Type: text/plain
-- XXXX--
''')
self.failUnless(msg.is_multipart())
eq(msg.get_boundary(), ' XXXX')
eq(len(msg.get_payload()), 2)
def test_boundary_without_trailing_newline(self):
m = Parser().parsestr("""\
Content-Type: multipart/mixed; boundary="===============0012394164=="
MIME-Version: 1.0
--===============0012394164==
Content-Type: image/file1.jpg
MIME-Version: 1.0
Content-Transfer-Encoding: base64
YXNkZg==
--===============0012394164==--""")
self.assertEquals(m.get_payload(0).get_payload(), 'YXNkZg==')
# Test some badly formatted messages
class TestNonConformant(TestEmailBase):
def test_parse_missing_minor_type(self):
eq = self.assertEqual
msg = self._msgobj('msg_14.txt')
eq(msg.get_content_type(), 'text/plain')
eq(msg.get_content_maintype(), 'text')
eq(msg.get_content_subtype(), 'plain')
def test_same_boundary_inner_outer(self):
unless = self.failUnless
msg = self._msgobj('msg_15.txt')
# XXX We can probably eventually do better
inner = msg.get_payload(0)
unless(hasattr(inner, 'defects'))
self.assertEqual(len(inner.defects), 1)
unless(isinstance(inner.defects[0],
Errors.StartBoundaryNotFoundDefect))
def test_multipart_no_boundary(self):
unless = self.failUnless
msg = self._msgobj('msg_25.txt')
unless(isinstance(msg.get_payload(), str))
self.assertEqual(len(msg.defects), 2)
unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect))
unless(isinstance(msg.defects[1],
Errors.MultipartInvariantViolationDefect))
def test_invalid_content_type(self):
eq = self.assertEqual
neq = self.ndiffAssertEqual
msg = Message()
# RFC 2045, $5.2 says invalid yields text/plain
msg['Content-Type'] = 'text'
eq(msg.get_content_maintype(), 'text')
eq(msg.get_content_subtype(), 'plain')
eq(msg.get_content_type(), 'text/plain')
# Clear the old value and try something /really/ invalid
del msg['content-type']
msg['Content-Type'] = 'foo'
eq(msg.get_content_maintype(), 'text')
eq(msg.get_content_subtype(), 'plain')
eq(msg.get_content_type(), 'text/plain')
# Still, make sure that the message is idempotently generated
s = StringIO()
g = Generator(s)
g.flatten(msg)
neq(s.getvalue(), 'Content-Type: foo\n\n')
def test_no_start_boundary(self):
eq = self.ndiffAssertEqual
msg = self._msgobj('msg_31.txt')
eq(msg.get_payload(), """\
--BOUNDARY
Content-Type: text/plain
message 1
--BOUNDARY
Content-Type: text/plain
message 2
--BOUNDARY--
""")
def test_no_separating_blank_line(self):
eq = self.ndiffAssertEqual
msg = self._msgobj('msg_35.txt')
eq(msg.as_string(), """\
From: aperson@dom.ain
To: bperson@dom.ain
Subject: here's something interesting
counter to RFC 2822, there's no separating newline here
""")
def test_lying_multipart(self):
unless = self.failUnless
msg = self._msgobj('msg_41.txt')
unless(hasattr(msg, 'defects'))
self.assertEqual(len(msg.defects), 2)
unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect))
unless(isinstance(msg.defects[1],
Errors.MultipartInvariantViolationDefect))
def test_missing_start_boundary(self):
outer = self._msgobj('msg_42.txt')
# The message structure is:
#
# multipart/mixed
# text/plain
# message/rfc822
# multipart/mixed [*]
#
# [*] This message is missing its start boundary
bad = outer.get_payload(1).get_payload(0)
self.assertEqual(len(bad.defects), 1)
self.failUnless(isinstance(bad.defects[0],
Errors.StartBoundaryNotFoundDefect))
def test_first_line_is_continuation_header(self):
eq = self.assertEqual
m = ' Line 1\nLine 2\nLine 3'
msg = email.message_from_string(m)
eq(msg.keys(), [])
eq(msg.get_payload(), 'Line 2\nLine 3')
eq(len(msg.defects), 1)
self.failUnless(isinstance(msg.defects[0],
Errors.FirstHeaderLineIsContinuationDefect))
eq(msg.defects[0].line, ' Line 1\n')
# Test RFC 2047 header encoding and decoding
class TestRFC2047(unittest.TestCase):
def test_rfc2047_multiline(self):
eq = self.assertEqual
s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz
foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?="""
dh = decode_header(s)
eq(dh, [
('Re:', None),
('r\x8aksm\x9arg\x8cs', 'mac-iceland'),
('baz foo bar', None),
('r\x8aksm\x9arg\x8cs', 'mac-iceland')])
eq(str(make_header(dh)),
"""Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar
=?mac-iceland?q?r=8Aksm=9Arg=8Cs?=""")
def test_whitespace_eater_unicode(self):
eq = self.assertEqual
s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <pirard@dom.ain>'
dh = decode_header(s)
eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard <pirard@dom.ain>', None)])
hu = unicode(make_header(dh)).encode('latin-1')
eq(hu, 'Andr\xe9 Pirard <pirard@dom.ain>')
def test_whitespace_eater_unicode_2(self):
eq = self.assertEqual
s = 'The =?iso-8859-1?b?cXVpY2sgYnJvd24gZm94?= jumped over the =?iso-8859-1?b?bGF6eSBkb2c=?='
dh = decode_header(s)
eq(dh, [('The', None), ('quick brown fox', 'iso-8859-1'),
('jumped over the', None), ('lazy dog', 'iso-8859-1')])
hu = make_header(dh).__unicode__()
eq(hu, u'The quick brown fox jumped over the lazy dog')
def test_rfc2047_without_whitespace(self):
s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
dh = decode_header(s)
self.assertEqual(dh, [(s, None)])
def test_rfc2047_with_whitespace(self):
s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
dh = decode_header(s)
self.assertEqual(dh, [('Sm', None), ('\xf6', 'iso-8859-1'),
('rg', None), ('\xe5', 'iso-8859-1'),
('sbord', None)])
# Test the MIMEMessage class
class TestMIMEMessage(TestEmailBase):
def setUp(self):
fp = openfile('msg_11.txt')
try:
self._text = fp.read()
finally:
fp.close()
def test_type_error(self):
self.assertRaises(TypeError, MIMEMessage, 'a plain string')
def test_valid_argument(self):
eq = self.assertEqual
unless = self.failUnless
subject = 'A sub-message'
m = Message()
m['Subject'] = subject
r = MIMEMessage(m)
eq(r.get_content_type(), 'message/rfc822')
payload = r.get_payload()
unless(isinstance(payload, list))
eq(len(payload), 1)
subpart = payload[0]
unless(subpart is m)
eq(subpart['subject'], subject)
def test_bad_multipart(self):
eq = self.assertEqual
msg1 = Message()
msg1['Subject'] = 'subpart 1'
msg2 = Message()
msg2['Subject'] = 'subpart 2'
r = MIMEMessage(msg1)
self.assertRaises(Errors.MultipartConversionError, r.attach, msg2)
def test_generate(self):
# First craft the message to be encapsulated
m = Message()
m['Subject'] = 'An enclosed message'
m.set_payload('Here is the body of the message.\n')
r = MIMEMessage(m)
r['Subject'] = 'The enclosing message'
s = StringIO()
g = Generator(s)
g.flatten(r)
self.assertEqual(s.getvalue(), """\
Content-Type: message/rfc822
MIME-Version: 1.0
Subject: The enclosing message
Subject: An enclosed message
Here is the body of the message.
""")
def test_parse_message_rfc822(self):
eq = self.assertEqual
unless = self.failUnless
msg = self._msgobj('msg_11.txt')
eq(msg.get_content_type(), 'message/rfc822')
payload = msg.get_payload()
unless(isinstance(payload, list))
eq(len(payload), 1)
submsg = payload[0]
self.failUnless(isinstance(submsg, Message))
eq(submsg['subject'], 'An enclosed message')
eq(submsg.get_payload(), 'Here is the body of the message.\n')
def test_dsn(self):
eq = self.assertEqual
unless = self.failUnless
# msg 16 is a Delivery Status Notification, see RFC 1894
msg = self._msgobj('msg_16.txt')
eq(msg.get_content_type(), 'multipart/report')
unless(msg.is_multipart())
eq(len(msg.get_payload()), 3)
# Subpart 1 is a text/plain, human readable section
subpart = msg.get_payload(0)
eq(subpart.get_content_type(), 'text/plain')
eq(subpart.get_payload(), """\
This report relates to a message you sent with the following header fields:
Message-id: <002001c144a6$8752e060$56104586@oxy.edu>
Date: Sun, 23 Sep 2001 20:10:55 -0700
From: "Ian T. Henry" <henryi@oxy.edu>
To: SoCal Raves <scr@socal-raves.org>
Subject: [scr] yeah for Ians!!
Your message cannot be delivered to the following recipients:
Recipient address: jangel1@cougar.noc.ucla.edu
Reason: recipient reached disk quota
""")
# Subpart 2 contains the machine parsable DSN information. It
# consists of two blocks of headers, represented by two nested Message
# objects.
subpart = msg.get_payload(1)
eq(subpart.get_content_type(), 'message/delivery-status')
eq(len(subpart.get_payload()), 2)
# message/delivery-status should treat each block as a bunch of
# headers, i.e. a bunch of Message objects.
dsn1 = subpart.get_payload(0)
unless(isinstance(dsn1, Message))
eq(dsn1['original-envelope-id'], '0GK500B4HD0888@cougar.noc.ucla.edu')
eq(dsn1.get_param('dns', header='reporting-mta'), '')
# Try a missing one <wink>
eq(dsn1.get_param('nsd', header='reporting-mta'), None)
dsn2 = subpart.get_payload(1)
unless(isinstance(dsn2, Message))
eq(dsn2['action'], 'failed')
eq(dsn2.get_params(header='original-recipient'),
[('rfc822', ''), ('jangel1@cougar.noc.ucla.edu', '')])
eq(dsn2.get_param('rfc822', header='final-recipient'), '')
# Subpart 3 is the original message
subpart = msg.get_payload(2)
eq(subpart.get_content_type(), 'message/rfc822')
payload = subpart.get_payload()
unless(isinstance(payload, list))
eq(len(payload), 1)
subsubpart = payload[0]
unless(isinstance(subsubpart, Message))
eq(subsubpart.get_content_type(), 'text/plain')
eq(subsubpart['message-id'],
'<002001c144a6$8752e060$56104586@oxy.edu>')
def test_epilogue(self):
eq = self.ndiffAssertEqual
fp = openfile('msg_21.txt')
try:
text = fp.read()
finally:
fp.close()
msg = Message()
msg['From'] = 'aperson@dom.ain'
msg['To'] = 'bperson@dom.ain'
msg['Subject'] = 'Test'
msg.preamble = 'MIME message'
msg.epilogue = 'End of MIME message\n'
msg1 = MIMEText('One')
msg2 = MIMEText('Two')
msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
msg.attach(msg1)
msg.attach(msg2)
sfp = StringIO()
g = Generator(sfp)
g.flatten(msg)
eq(sfp.getvalue(), text)
def test_no_nl_preamble(self):
eq = self.ndiffAssertEqual
msg = Message()
msg['From'] = 'aperson@dom.ain'
msg['To'] = 'bperson@dom.ain'
msg['Subject'] = 'Test'
msg.preamble = 'MIME message'
msg.epilogue = ''
msg1 = MIMEText('One')
msg2 = MIMEText('Two')
msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
msg.attach(msg1)
msg.attach(msg2)
eq(msg.as_string(), """\
From: aperson@dom.ain
To: bperson@dom.ain
Subject: Test
Content-Type: multipart/mixed; boundary="BOUNDARY"
MIME message
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
One
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Two
--BOUNDARY--
""")
def test_default_type(self):
eq = self.assertEqual
fp = openfile('msg_30.txt')
try:
msg = email.message_from_file(fp)
finally:
fp.close()
container1 = msg.get_payload(0)
eq(container1.get_default_type(), 'message/rfc822')
eq(container1.get_content_type(), 'message/rfc822')
container2 = msg.get_payload(1)
eq(container2.get_default_type(), 'message/rfc822')
eq(container2.get_content_type(), 'message/rfc822')
container1a = container1.get_payload(0)
eq(container1a.get_default_type(), 'text/plain')
eq(container1a.get_content_type(), 'text/plain')
container2a = container2.get_payload(0)
eq(container2a.get_default_type(), 'text/plain')
eq(container2a.get_content_type(), 'text/plain')
def test_default_type_with_explicit_container_type(self):
eq = self.assertEqual
fp = openfile('msg_28.txt')
try:
msg = email.message_from_file(fp)
finally:
fp.close()
container1 = msg.get_payload(0)
eq(container1.get_default_type(), 'message/rfc822')
eq(container1.get_content_type(), 'message/rfc822')
container2 = msg.get_payload(1)
eq(container2.get_default_type(), 'message/rfc822')
eq(container2.get_content_type(), 'message/rfc822')
container1a = container1.get_payload(0)
eq(container1a.get_default_type(), 'text/plain')
eq(container1a.get_content_type(), 'text/plain')
container2a = container2.get_payload(0)
eq(container2a.get_default_type(), 'text/plain')
eq(container2a.get_content_type(), 'text/plain')
def test_default_type_non_parsed(self):
eq = self.assertEqual
neq = self.ndiffAssertEqual
# Set up container
container = MIMEMultipart('digest', 'BOUNDARY')
container.epilogue = ''
# Set up subparts
subpart1a = MIMEText('message 1\n')
subpart2a = MIMEText('message 2\n')
subpart1 = MIMEMessage(subpart1a)
subpart2 = MIMEMessage(subpart2a)
container.attach(subpart1)
container.attach(subpart2)
eq(subpart1.get_content_type(), 'message/rfc822')
eq(subpart1.get_default_type(), 'message/rfc822')
eq(subpart2.get_content_type(), 'message/rfc822')
eq(subpart2.get_default_type(), 'message/rfc822')
neq(container.as_string(0), '''\
Content-Type: multipart/digest; boundary="BOUNDARY"
MIME-Version: 1.0
--BOUNDARY
Content-Type: message/rfc822
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
message 1
--BOUNDARY
Content-Type: message/rfc822
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
message 2
--BOUNDARY--
''')
del subpart1['content-type']
del subpart1['mime-version']
del subpart2['content-type']
del subpart2['mime-version']
eq(subpart1.get_content_type(), 'message/rfc822')
eq(subpart1.get_default_type(), 'message/rfc822')
eq(subpart2.get_content_type(), 'message/rfc822')
eq(subpart2.get_default_type(), 'message/rfc822')
neq(container.as_string(0), '''\
Content-Type: multipart/digest; boundary="BOUNDARY"
MIME-Version: 1.0
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
message 1
--BOUNDARY
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
message 2
--BOUNDARY--
''')
def test_mime_attachments_in_constructor(self):
eq = self.assertEqual
text1 = MIMEText('')
text2 = MIMEText('')
msg = MIMEMultipart(_subparts=(text1, text2))
eq(len(msg.get_payload()), 2)
eq(msg.get_payload(0), text1)
eq(msg.get_payload(1), text2)
# A general test of parser->model->generator idempotency. IOW, read a message
# in, parse it into a message object tree, then without touching the tree,
# regenerate the plain text. The original text and the transformed text
# should be identical. Note: that we ignore the Unix-From since that may
# contain a changed date.
class TestIdempotent(TestEmailBase):
def _msgobj(self, filename):
fp = openfile(filename)
try:
data = fp.read()
finally:
fp.close()
msg = email.message_from_string(data)
return msg, data
def _idempotent(self, msg, text):
eq = self.ndiffAssertEqual
s = StringIO()
g = Generator(s, maxheaderlen=0)
g.flatten(msg)
eq(text, s.getvalue())
def test_parse_text_message(self):
eq = self.assertEquals
msg, text = self._msgobj('msg_01.txt')
eq(msg.get_content_type(), 'text/plain')
eq(msg.get_content_maintype(), 'text')
eq(msg.get_content_subtype(), 'plain')
eq(msg.get_params()[1], ('charset', 'us-ascii'))
eq(msg.get_param('charset'), 'us-ascii')
eq(msg.preamble, None)
eq(msg.epilogue, None)
self._idempotent(msg, text)
def test_parse_untyped_message(self):
eq = self.assertEquals
msg, text = self._msgobj('msg_03.txt')
eq(msg.get_content_type(), 'text/plain')
eq(msg.get_params(), None)
eq(msg.get_param('charset'), None)
self._idempotent(msg, text)
def test_simple_multipart(self):
msg, text = self._msgobj('msg_04.txt')
self._idempotent(msg, text)
def test_MIME_digest(self):
msg, text = self._msgobj('msg_02.txt')
self._idempotent(msg, text)
def test_long_header(self):
msg, text = self._msgobj('msg_27.txt')
self._idempotent(msg, text)
def test_MIME_digest_with_part_headers(self):
msg, text = self._msgobj('msg_28.txt')
self._idempotent(msg, text)
def test_mixed_with_image(self):
msg, text = self._msgobj('msg_06.txt')
self._idempotent(msg, text)
def test_multipart_report(self):
msg, text = self._msgobj('msg_05.txt')
self._idempotent(msg, text)
def test_dsn(self):
msg, text = self._msgobj('msg_16.txt')
self._idempotent(msg, text)
def test_preamble_epilogue(self):
msg, text = self._msgobj('msg_21.txt')
self._idempotent(msg, text)
def test_multipart_one_part(self):
msg, text = self._msgobj('msg_23.txt')
self._idempotent(msg, text)
def test_multipart_no_parts(self):
msg, text = self._msgobj('msg_24.txt')
self._idempotent(msg, text)
def test_no_start_boundary(self):
msg, text = self._msgobj('msg_31.txt')
self._idempotent(msg, text)
def test_rfc2231_charset(self):
msg, text = self._msgobj('msg_32.txt')
self._idempotent(msg, text)
def test_more_rfc2231_parameters(self):
msg, text = self._msgobj('msg_33.txt')
self._idempotent(msg, text)
def test_text_plain_in_a_multipart_digest(self):
msg, text = self._msgobj('msg_34.txt')
self._idempotent(msg, text)
def test_nested_multipart_mixeds(self):
msg, text = self._msgobj('msg_12a.txt')
self._idempotent(msg, text)
def test_message_external_body_idempotent(self):
msg, text = self._msgobj('msg_36.txt')
self._idempotent(msg, text)
def test_content_type(self):
eq = self.assertEquals
unless = self.failUnless
# Get a message object and reset the seek pointer for other tests
msg, text = self._msgobj('msg_05.txt')
eq(msg.get_content_type(), 'multipart/report')
# Test the Content-Type: parameters
params = {}
for pk, pv in msg.get_params():
params[pk] = pv
eq(params['report-type'], 'delivery-status')
eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com')
eq(msg.preamble, 'This is a MIME-encapsulated message.\n')
eq(msg.epilogue, '\n')
eq(len(msg.get_payload()), 3)
# Make sure the subparts are what we expect
msg1 = msg.get_payload(0)
eq(msg1.get_content_type(), 'text/plain')
eq(msg1.get_payload(), 'Yadda yadda yadda\n')
msg2 = msg.get_payload(1)
eq(msg2.get_content_type(), 'text/plain')
eq(msg2.get_payload(), 'Yadda yadda yadda\n')
msg3 = msg.get_payload(2)
eq(msg3.get_content_type(), 'message/rfc822')
self.failUnless(isinstance(msg3, Message))
payload = msg3.get_payload()
unless(isinstance(payload, list))
eq(len(payload), 1)
msg4 = payload[0]
unless(isinstance(msg4, Message))
eq(msg4.get_payload(), 'Yadda yadda yadda\n')
def test_parser(self):
eq = self.assertEquals
unless = self.failUnless
msg, text = self._msgobj('msg_06.txt')
# Check some of the outer headers
eq(msg.get_content_type(), 'message/rfc822')
# Make sure the payload is a list of exactly one sub-Message, and that
# that submessage has a type of text/plain
payload = msg.get_payload()
unless(isinstance(payload, list))
eq(len(payload), 1)
msg1 = payload[0]
self.failUnless(isinstance(msg1, Message))
eq(msg1.get_content_type(), 'text/plain')
self.failUnless(isinstance(msg1.get_payload(), str))
eq(msg1.get_payload(), '\n')
# Test various other bits of the package's functionality
class TestMiscellaneous(TestEmailBase):
def test_message_from_string(self):
fp = openfile('msg_01.txt')
try:
text = fp.read()
finally:
fp.close()
msg = email.message_from_string(text)
s = StringIO()
# Don't wrap/continue long headers since we're trying to test
# idempotency.
g = Generator(s, maxheaderlen=0)
g.flatten(msg)
self.assertEqual(text, s.getvalue())
def test_message_from_file(self):
fp = openfile('msg_01.txt')
try:
text = fp.read()
fp.seek(0)
msg = email.message_from_file(fp)
s = StringIO()
# Don't wrap/continue long headers since we're trying to test
# idempotency.
g = Generator(s, maxheaderlen=0)
g.flatten(msg)
self.assertEqual(text, s.getvalue())
finally:
fp.close()
def test_message_from_string_with_class(self):
unless = self.failUnless
fp = openfile('msg_01.txt')
try:
text = fp.read()
finally:
fp.close()
# Create a subclass
class MyMessage(Message):
pass
msg = email.message_from_string(text, MyMessage)
unless(isinstance(msg, MyMessage))
# Try something more complicated
fp = openfile('msg_02.txt')
try:
text = fp.read()
finally:
fp.close()
msg = email.message_from_string(text, MyMessage)
for subpart in msg.walk():
unless(isinstance(subpart, MyMessage))
def test_message_from_file_with_class(self):
unless = self.failUnless
# Create a subclass
class MyMessage(Message):
pass
fp = openfile('msg_01.txt')
try:
msg = email.message_from_file(fp, MyMessage)
finally:
fp.close()
unless(isinstance(msg, MyMessage))
# Try something more complicated
fp = openfile('msg_02.txt')
try:
msg = email.message_from_file(fp, MyMessage)
finally:
fp.close()
for subpart in msg.walk():
unless(isinstance(subpart, MyMessage))
def test__all__(self):
module = __import__('email')
all = module.__all__
all.sort()
self.assertEqual(all, [
# Old names
'Charset', 'Encoders', 'Errors', 'Generator',
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
'MIMENonMultipart', 'MIMEText', 'Message',
'Parser', 'Utils', 'base64MIME',
# new names
'base64mime', 'charset', 'encoders', 'errors', 'generator',
'header', 'iterators', 'message', 'message_from_file',
'message_from_string', 'mime', 'parser',
'quopriMIME', 'quoprimime', 'utils',
])
def test_formatdate(self):
now = time.time()
self.assertEqual(Utils.parsedate(Utils.formatdate(now))[:6],
time.gmtime(now)[:6])
def test_formatdate_localtime(self):
now = time.time()
self.assertEqual(
Utils.parsedate(Utils.formatdate(now, localtime=True))[:6],
time.localtime(now)[:6])
def test_formatdate_usegmt(self):
now = time.time()
self.assertEqual(
Utils.formatdate(now, localtime=False),
time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
self.assertEqual(
Utils.formatdate(now, localtime=False, usegmt=True),
time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now)))
def test_parsedate_none(self):
self.assertEqual(Utils.parsedate(''), None)
def test_parsedate_compact(self):
# The FWS after the comma is optional
self.assertEqual(Utils.parsedate('Wed,3 Apr 2002 14:58:26 +0800'),
Utils.parsedate('Wed, 3 Apr 2002 14:58:26 +0800'))
def test_parsedate_no_dayofweek(self):
eq = self.assertEqual
eq(Utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'),
(2003, 2, 25, 13, 47, 26, 0, 1, -1, -28800))
def test_parsedate_compact_no_dayofweek(self):
eq = self.assertEqual
eq(Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'),
(2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
def test_parsedate_acceptable_to_time_functions(self):
eq = self.assertEqual
timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800')
t = int(time.mktime(timetup))
eq(time.localtime(t)[:6], timetup[:6])
eq(int(time.strftime('%Y', timetup)), 2003)
timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
t = int(time.mktime(timetup[:9]))
eq(time.localtime(t)[:6], timetup[:6])
eq(int(time.strftime('%Y', timetup[:9])), 2003)
def test_parseaddr_empty(self):
self.assertEqual(Utils.parseaddr('<>'), ('', ''))
self.assertEqual(Utils.formataddr(Utils.parseaddr('<>')), '')
def test_noquote_dump(self):
self.assertEqual(
Utils.formataddr(('A Silly Person', 'person@dom.ain')),
'A Silly Person <person@dom.ain>')
def test_escape_dump(self):
self.assertEqual(
Utils.formataddr(('A (Very) Silly Person', 'person@dom.ain')),
r'"A \(Very\) Silly Person" <person@dom.ain>')
a = r'A \(Special\) Person'
b = 'person@dom.ain'
self.assertEqual(Utils.parseaddr(Utils.formataddr((a, b))), (a, b))
def test_escape_backslashes(self):
self.assertEqual(
Utils.formataddr(('Arthur \Backslash\ Foobar', 'person@dom.ain')),
r'"Arthur \\Backslash\\ Foobar" <person@dom.ain>')
a = r'Arthur \Backslash\ Foobar'
b = 'person@dom.ain'
self.assertEqual(Utils.parseaddr(Utils.formataddr((a, b))), (a, b))
def test_name_with_dot(self):
x = 'John X. Doe <jxd@example.com>'
y = '"John X. Doe" <jxd@example.com>'
a, b = ('John X. Doe', 'jxd@example.com')
self.assertEqual(Utils.parseaddr(x), (a, b))
self.assertEqual(Utils.parseaddr(y), (a, b))
# formataddr() quotes the name if there's a dot in it
self.assertEqual(Utils.formataddr((a, b)), y)
def test_multiline_from_comment(self):
x = """\
Foo
\tBar <foo@example.com>"""
self.assertEqual(Utils.parseaddr(x), ('Foo Bar', 'foo@example.com'))
def test_quote_dump(self):
self.assertEqual(
Utils.formataddr(('A Silly; Person', 'person@dom.ain')),
r'"A Silly; Person" <person@dom.ain>')
def test_fix_eols(self):
eq = self.assertEqual
eq(Utils.fix_eols('hello'), 'hello')
eq(Utils.fix_eols('hello\n'), 'hello\r\n')
eq(Utils.fix_eols('hello\r'), 'hello\r\n')
eq(Utils.fix_eols('hello\r\n'), 'hello\r\n')
eq(Utils.fix_eols('hello\n\r'), 'hello\r\n\r\n')
def test_charset_richcomparisons(self):
eq = self.assertEqual
ne = self.failIfEqual
cset1 = Charset()
cset2 = Charset()
eq(cset1, 'us-ascii')
eq(cset1, 'US-ASCII')
eq(cset1, 'Us-AsCiI')
eq('us-ascii', cset1)
eq('US-ASCII', cset1)
eq('Us-AsCiI', cset1)
ne(cset1, 'usascii')
ne(cset1, 'USASCII')
ne(cset1, 'UsAsCiI')
ne('usascii', cset1)
ne('USASCII', cset1)
ne('UsAsCiI', cset1)
eq(cset1, cset2)
eq(cset2, cset1)
def test_getaddresses(self):
eq = self.assertEqual
eq(Utils.getaddresses(['aperson@dom.ain (Al Person)',
'Bud Person <bperson@dom.ain>']),
[('Al Person', 'aperson@dom.ain'),
('Bud Person', 'bperson@dom.ain')])
def test_getaddresses_nasty(self):
eq = self.assertEqual
eq(Utils.getaddresses(['foo: ;']), [('', '')])
eq(Utils.getaddresses(
['[]*-- =~$']),
[('', ''), ('', ''), ('', '*--')])
eq(Utils.getaddresses(
['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
[('', ''), ('Jason R. Mastaler', 'jason@dom.ain')])
def test_getaddresses_embedded_comment(self):
"""Test proper handling of a nested comment"""
eq = self.assertEqual
addrs = Utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
eq(addrs[0][1], 'foo@bar.com')
def test_utils_quote_unquote(self):
eq = self.assertEqual
msg = Message()
msg.add_header('content-disposition', 'attachment',
filename='foo\\wacky"name')
eq(msg.get_filename(), 'foo\\wacky"name')
def test_get_body_encoding_with_bogus_charset(self):
charset = Charset('not a charset')
self.assertEqual(charset.get_body_encoding(), 'base64')
def test_get_body_encoding_with_uppercase_charset(self):
eq = self.assertEqual
msg = Message()
msg['Content-Type'] = 'text/plain; charset=UTF-8'
eq(msg['content-type'], 'text/plain; charset=UTF-8')
charsets = msg.get_charsets()
eq(len(charsets), 1)
eq(charsets[0], 'utf-8')
charset = Charset(charsets[0])
eq(charset.get_body_encoding(), 'base64')
msg.set_payload('hello world', charset=charset)
eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n')
eq(msg.get_payload(decode=True), 'hello world')
eq(msg['content-transfer-encoding'], 'base64')
# Try another one
msg = Message()
msg['Content-Type'] = 'text/plain; charset="US-ASCII"'
charsets = msg.get_charsets()
eq(len(charsets), 1)
eq(charsets[0], 'us-ascii')
charset = Charset(charsets[0])
eq(charset.get_body_encoding(), Encoders.encode_7or8bit)
msg.set_payload('hello world', charset=charset)
eq(msg.get_payload(), 'hello world')
eq(msg['content-transfer-encoding'], '7bit')
def test_charsets_case_insensitive(self):
lc = Charset('us-ascii')
uc = Charset('US-ASCII')
self.assertEqual(lc.get_body_encoding(), uc.get_body_encoding())
def test_partial_falls_inside_message_delivery_status(self):
eq = self.ndiffAssertEqual
# The Parser interface provides chunks of data to FeedParser in 8192
# byte gulps. SF bug #1076485 found one of those chunks inside
# message/delivery-status header block, which triggered an
# unreadline() of NeedMoreData.
msg = self._msgobj('msg_43.txt')
sfp = StringIO()
Iterators._structure(msg, sfp)
eq(sfp.getvalue(), """\
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/plain
text/rfc822-headers
""")
# Test the iterator/generators
class TestIterators(TestEmailBase):
def test_body_line_iterator(self):
eq = self.assertEqual
neq = self.ndiffAssertEqual
# First a simple non-multipart message
msg = self._msgobj('msg_01.txt')
it = Iterators.body_line_iterator(msg)
lines = list(it)
eq(len(lines), 6)
neq(EMPTYSTRING.join(lines), msg.get_payload())
# Now a more complicated multipart
msg = self._msgobj('msg_02.txt')
it = Iterators.body_line_iterator(msg)
lines = list(it)
eq(len(lines), 43)
fp = openfile('msg_19.txt')
try:
neq(EMPTYSTRING.join(lines), fp.read())
finally:
fp.close()
def test_typed_subpart_iterator(self):
eq = self.assertEqual
msg = self._msgobj('msg_04.txt')
it = Iterators.typed_subpart_iterator(msg, 'text')
lines = []
subparts = 0
for subpart in it:
subparts += 1
lines.append(subpart.get_payload())
eq(subparts, 2)
eq(EMPTYSTRING.join(lines), """\
a simple kind of mirror
to reflect upon our own
a simple kind of mirror
to reflect upon our own
""")
def test_typed_subpart_iterator_default_type(self):
eq = self.assertEqual
msg = self._msgobj('msg_03.txt')
it = Iterators.typed_subpart_iterator(msg, 'text', 'plain')
lines = []
subparts = 0
for subpart in it:
subparts += 1
lines.append(subpart.get_payload())
eq(subparts, 1)
eq(EMPTYSTRING.join(lines), """\
Hi,
Do you like this message?
-Me
""")
class TestParsers(TestEmailBase):
def test_header_parser(self):
eq = self.assertEqual
# Parse only the headers of a complex multipart MIME document
fp = openfile('msg_02.txt')
try:
msg = HeaderParser().parse(fp)
finally:
fp.close()
eq(msg['from'], 'ppp-request@zzz.org')
eq(msg['to'], 'ppp@zzz.org')
eq(msg.get_content_type(), 'multipart/mixed')
self.failIf(msg.is_multipart())
self.failUnless(isinstance(msg.get_payload(), str))
def test_whitespace_continuation(self):
eq = self.assertEqual
# This message contains a line after the Subject: header that has only
# whitespace, but it is not empty!
msg = email.message_from_string("""\
From: aperson@dom.ain
To: bperson@dom.ain
Subject: the next line has a space on it
\x20
Date: Mon, 8 Apr 2002 15:09:19 -0400
Message-ID: spam
Here's the message body
""")
eq(msg['subject'], 'the next line has a space on it\n ')
eq(msg['message-id'], 'spam')
eq(msg.get_payload(), "Here's the message body\n")
def test_whitespace_continuation_last_header(self):
eq = self.assertEqual
# Like the previous test, but the subject line is the last
# header.
msg = email.message_from_string("""\
From: aperson@dom.ain
To: bperson@dom.ain
Date: Mon, 8 Apr 2002 15:09:19 -0400
Message-ID: spam
Subject: the next line has a space on it
\x20
Here's the message body
""")
eq(msg['subject'], 'the next line has a space on it\n ')
eq(msg['message-id'], 'spam')
eq(msg.get_payload(), "Here's the message body\n")
def test_crlf_separation(self):
eq = self.assertEqual
fp = openfile('msg_26.txt', mode='rb')
try:
msg = Parser().parse(fp)
finally:
fp.close()
eq(len(msg.get_payload()), 2)
part1 = msg.get_payload(0)
eq(part1.get_content_type(), 'text/plain')
eq(part1.get_payload(), 'Simple email with attachment.\r\n\r\n')
part2 = msg.get_payload(1)
eq(part2.get_content_type(), 'application/riscos')
def test_multipart_digest_with_extra_mime_headers(self):
eq = self.assertEqual
neq = self.ndiffAssertEqual
fp = openfile('msg_28.txt')
try:
msg = email.message_from_file(fp)
finally:
fp.close()
# Structure is:
# multipart/digest
# message/rfc822
# text/plain
# message/rfc822
# text/plain
eq(msg.is_multipart(), 1)
eq(len(msg.get_payload()), 2)
part1 = msg.get_payload(0)
eq(part1.get_content_type(), 'message/rfc822')
eq(part1.is_multipart(), 1)
eq(len(part1.get_payload()), 1)
part1a = part1.get_payload(0)
eq(part1a.is_multipart(), 0)
eq(part1a.get_content_type(), 'text/plain')
neq(part1a.get_payload(), 'message 1\n')
# next message/rfc822
part2 = msg.get_payload(1)
eq(part2.get_content_type(), 'message/rfc822')
eq(part2.is_multipart(), 1)
eq(len(part2.get_payload()), 1)
part2a = part2.get_payload(0)
eq(part2a.is_multipart(), 0)
eq(part2a.get_content_type(), 'text/plain')
neq(part2a.get_payload(), 'message 2\n')
def test_three_lines(self):
# A bug report by Andrew McNamara
lines = ['From: Andrew Person <aperson@dom.ain',
'Subject: Test',
'Date: Tue, 20 Aug 2002 16:43:45 +1000']
msg = email.message_from_string(NL.join(lines))
self.assertEqual(msg['date'], 'Tue, 20 Aug 2002 16:43:45 +1000')
def test_strip_line_feed_and_carriage_return_in_headers(self):
eq = self.assertEqual
# For [ 1002475 ] email message parser doesn't handle \r\n correctly
value1 = 'text'
value2 = 'more text'
m = 'Header: %s\r\nNext-Header: %s\r\n\r\nBody\r\n\r\n' % (
value1, value2)
msg = email.message_from_string(m)
eq(msg.get('Header'), value1)
eq(msg.get('Next-Header'), value2)
def test_rfc2822_header_syntax(self):
eq = self.assertEqual
m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
msg = email.message_from_string(m)
eq(len(msg.keys()), 3)
keys = msg.keys()
keys.sort()
eq(keys, ['!"#QUX;~', '>From', 'From'])
eq(msg.get_payload(), 'body')
def test_rfc2822_space_not_allowed_in_header(self):
eq = self.assertEqual
m = '>From foo@example.com 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
msg = email.message_from_string(m)
eq(len(msg.keys()), 0)
def test_rfc2822_one_character_header(self):
eq = self.assertEqual
m = 'A: first header\nB: second header\nCC: third header\n\nbody'
msg = email.message_from_string(m)
headers = msg.keys()
headers.sort()
eq(headers, ['A', 'B', 'CC'])
eq(msg.get_payload(), 'body')
class TestBase64(unittest.TestCase):
def test_len(self):
eq = self.assertEqual
eq(base64MIME.base64_len('hello'),
len(base64MIME.encode('hello', eol='')))
for size in range(15):
if size == 0 : bsize = 0
elif size <= 3 : bsize = 4
elif size <= 6 : bsize = 8
elif size <= 9 : bsize = 12
elif size <= 12: bsize = 16
else : bsize = 20
eq(base64MIME.base64_len('x'*size), bsize)
def test_decode(self):
eq = self.assertEqual
eq(base64MIME.decode(''), '')
eq(base64MIME.decode('aGVsbG8='), 'hello')
eq(base64MIME.decode('aGVsbG8=', 'X'), 'hello')
eq(base64MIME.decode('aGVsbG8NCndvcmxk\n', 'X'), 'helloXworld')
def test_encode(self):
eq = self.assertEqual
eq(base64MIME.encode(''), '')
eq(base64MIME.encode('hello'), 'aGVsbG8=\n')
# Test the binary flag
eq(base64MIME.encode('hello\n'), 'aGVsbG8K\n')
eq(base64MIME.encode('hello\n', 0), 'aGVsbG8NCg==\n')
# Test the maxlinelen arg
eq(base64MIME.encode('xxxx ' * 20, maxlinelen=40), """\
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
eHh4eCB4eHh4IA==
""")
# Test the eol argument
eq(base64MIME.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
eHh4eCB4eHh4IA==\r
""")
def test_header_encode(self):
eq = self.assertEqual
he = base64MIME.header_encode
eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=')
eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=')
# Test the charset option
eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=')
# Test the keep_eols flag
eq(he('hello\nworld', keep_eols=True),
'=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
# Test the maxlinelen argument
eq(he('xxxx ' * 20, maxlinelen=40), """\
=?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=
=?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=
=?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=
=?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=
=?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=
=?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
# Test the eol argument
eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
=?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=\r
=?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=\r
=?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=\r
=?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=\r
=?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=\r
=?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
class TestQuopri(unittest.TestCase):
def setUp(self):
self.hlit = [chr(x) for x in range(ord('a'), ord('z')+1)] + \
[chr(x) for x in range(ord('A'), ord('Z')+1)] + \
[chr(x) for x in range(ord('0'), ord('9')+1)] + \
['!', '*', '+', '-', '/', ' ']
self.hnon = [chr(x) for x in range(256) if chr(x) not in self.hlit]
assert len(self.hlit) + len(self.hnon) == 256
self.blit = [chr(x) for x in range(ord(' '), ord('~')+1)] + ['\t']
self.blit.remove('=')
self.bnon = [chr(x) for x in range(256) if chr(x) not in self.blit]
assert len(self.blit) + len(self.bnon) == 256
def test_header_quopri_check(self):
for c in self.hlit:
self.failIf(quopriMIME.header_quopri_check(c))
for c in self.hnon:
self.failUnless(quopriMIME.header_quopri_check(c))
def test_body_quopri_check(self):
for c in self.blit:
self.failIf(quopriMIME.body_quopri_check(c))
for c in self.bnon:
self.failUnless(quopriMIME.body_quopri_check(c))
def test_header_quopri_len(self):
eq = self.assertEqual
hql = quopriMIME.header_quopri_len
enc = quopriMIME.header_encode
for s in ('hello', 'h@e@l@l@o@'):
# Empty charset and no line-endings. 7 == RFC chrome
eq(hql(s), len(enc(s, charset='', eol=''))-7)
for c in self.hlit:
eq(hql(c), 1)
for c in self.hnon:
eq(hql(c), 3)
def test_body_quopri_len(self):
eq = self.assertEqual
bql = quopriMIME.body_quopri_len
for c in self.blit:
eq(bql(c), 1)
for c in self.bnon:
eq(bql(c), 3)
def test_quote_unquote_idempotent(self):
for x in range(256):
c = chr(x)
self.assertEqual(quopriMIME.unquote(quopriMIME.quote(c)), c)
def test_header_encode(self):
eq = self.assertEqual
he = quopriMIME.header_encode
eq(he('hello'), '=?iso-8859-1?q?hello?=')
eq(he('hello\nworld'), '=?iso-8859-1?q?hello=0D=0Aworld?=')
# Test the charset option
eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?q?hello?=')
# Test the keep_eols flag
eq(he('hello\nworld', keep_eols=True), '=?iso-8859-1?q?hello=0Aworld?=')
# Test a non-ASCII character
eq(he('hello\xc7there'), '=?iso-8859-1?q?hello=C7there?=')
# Test the maxlinelen argument
eq(he('xxxx ' * 20, maxlinelen=40), """\
=?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=
=?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=
=?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=
=?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=
=?iso-8859-1?q?x_xxxx_xxxx_?=""")
# Test the eol argument
eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
=?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=\r
=?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=\r
=?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=\r
=?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=\r
=?iso-8859-1?q?x_xxxx_xxxx_?=""")
def test_decode(self):
eq = self.assertEqual
eq(quopriMIME.decode(''), '')
eq(quopriMIME.decode('hello'), 'hello')
eq(quopriMIME.decode('hello', 'X'), 'hello')
eq(quopriMIME.decode('hello\nworld', 'X'), 'helloXworld')
def test_encode(self):
eq = self.assertEqual
eq(quopriMIME.encode(''), '')
eq(quopriMIME.encode('hello'), 'hello')
# Test the binary flag
eq(quopriMIME.encode('hello\r\nworld'), 'hello\nworld')
eq(quopriMIME.encode('hello\r\nworld', 0), 'hello\nworld')
# Test the maxlinelen arg
eq(quopriMIME.encode('xxxx ' * 20, maxlinelen=40), """\
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=
x xxxx xxxx xxxx xxxx=20""")
# Test the eol argument
eq(quopriMIME.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=\r
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=\r
x xxxx xxxx xxxx xxxx=20""")
eq(quopriMIME.encode("""\
one line
two line"""), """\
one line
two line""")
# Test the Charset class
class TestCharset(unittest.TestCase):
def tearDown(self):
from email import Charset as CharsetModule
try:
del CharsetModule.CHARSETS['fake']
except KeyError:
pass
def test_idempotent(self):
eq = self.assertEqual
# Make sure us-ascii = no Unicode conversion
c = Charset('us-ascii')
s = 'Hello World!'
sp = c.to_splittable(s)
eq(s, c.from_splittable(sp))
# test 8-bit idempotency with us-ascii
s = '\xa4\xa2\xa4\xa4\xa4\xa6\xa4\xa8\xa4\xaa'
sp = c.to_splittable(s)
eq(s, c.from_splittable(sp))
def test_body_encode(self):
eq = self.assertEqual
# Try a charset with QP body encoding
c = Charset('iso-8859-1')
eq('hello w=F6rld', c.body_encode('hello w\xf6rld'))
# Try a charset with Base64 body encoding
c = Charset('utf-8')
eq('aGVsbG8gd29ybGQ=\n', c.body_encode('hello world'))
# Try a charset with None body encoding
c = Charset('us-ascii')
eq('hello world', c.body_encode('hello world'))
# Try the convert argument, where input codec <> output codec
c = Charset('euc-jp')
# With apologies to Tokio Kikuchi ;)
try:
eq('\x1b$B5FCO;~IW\x1b(B',
c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7'))
eq('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7',
c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', False))
except LookupError:
# We probably don't have the Japanese codecs installed
pass
# Testing SF bug #625509, which we have to fake, since there are no
# built-in encodings where the header encoding is QP but the body
# encoding is not.
from email import Charset as CharsetModule
CharsetModule.add_charset('fake', CharsetModule.QP, None)
c = Charset('fake')
eq('hello w\xf6rld', c.body_encode('hello w\xf6rld'))
def test_unicode_charset_name(self):
charset = Charset(u'us-ascii')
self.assertEqual(str(charset), 'us-ascii')
self.assertRaises(Errors.CharsetError, Charset, 'asc\xffii')
# Test multilingual MIME headers.
class TestHeader(TestEmailBase):
def test_simple(self):
eq = self.ndiffAssertEqual
h = Header('Hello World!')
eq(h.encode(), 'Hello World!')
h.append(' Goodbye World!')
eq(h.encode(), 'Hello World! Goodbye World!')
def test_simple_surprise(self):
eq = self.ndiffAssertEqual
h = Header('Hello World!')
eq(h.encode(), 'Hello World!')
h.append('Goodbye World!')
eq(h.encode(), 'Hello World! Goodbye World!')
def test_header_needs_no_decoding(self):
h = 'no decoding needed'
self.assertEqual(decode_header(h), [(h, None)])
def test_long(self):
h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.",
maxlinelen=76)
for l in h.encode(splitchars=' ').split('\n '):
self.failUnless(len(l) <= 76)
def test_multilingual(self):
eq = self.ndiffAssertEqual
g = Charset("iso-8859-1")
cz = Charset("iso-8859-2")
utf8 = Charset("utf-8")
g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
h = Header(g_head, g)
h.append(cz_head, cz)
h.append(utf8_head, utf8)
enc = h.encode()
eq(enc, """\
=?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderband_ko?=
=?iso-8859-1?q?mfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen_Wan?=
=?iso-8859-1?q?dgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef=F6?=
=?iso-8859-1?q?rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hroutily?=
=?iso-8859-2?q?_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?=
=?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC?=
=?utf-8?b?5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn?=
=?utf-8?b?44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFz?=
=?utf-8?q?_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das_Oder_die_Fl?=
=?utf-8?b?aXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBo+OBpuOBhOOBvuOBmQ==?=
=?utf-8?b?44CC?=""")
eq(decode_header(enc),
[(g_head, "iso-8859-1"), (cz_head, "iso-8859-2"),
(utf8_head, "utf-8")])
ustr = unicode(h)
eq(ustr.encode('utf-8'),
'Die Mieter treten hier ein werden mit einem Foerderband '
'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen '
'Wandgem\xc3\xa4lden vorbei, gegen die rotierenden Klingen '
'bef\xc3\xb6rdert. Finan\xc4\x8dni metropole se hroutily pod '
'tlakem jejich d\xc5\xafvtipu.. \xe6\xad\xa3\xe7\xa2\xba\xe3\x81'
'\xab\xe8\xa8\x80\xe3\x81\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3'
'\xe3\x81\xaf\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3'
'\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8\xaa\x9e'
'\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\xe3\x81\x82\xe3'
'\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81\x9f\xe3\x82\x89\xe3\x82'
'\x81\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82\xe5\xae\x9f\xe9\x9a\x9b'
'\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x8cWenn ist das Nunstuck git '
'und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt '
'gersput.\xe3\x80\x8d\xe3\x81\xa8\xe8\xa8\x80\xe3\x81\xa3\xe3\x81'
'\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82')
# Test make_header()
newh = make_header(decode_header(enc))
eq(newh, enc)
def test_header_ctor_default_args(self):
eq = self.ndiffAssertEqual
h = Header()
eq(h, '')
h.append('foo', Charset('iso-8859-1'))
eq(h, '=?iso-8859-1?q?foo?=')
def test_explicit_maxlinelen(self):
eq = self.ndiffAssertEqual
hstr = 'A very long line that must get split to something other than at the 76th character boundary to test the non-default behavior'
h = Header(hstr)
eq(h.encode(), '''\
A very long line that must get split to something other than at the 76th
character boundary to test the non-default behavior''')
h = Header(hstr, header_name='Subject')
eq(h.encode(), '''\
A very long line that must get split to something other than at the
76th character boundary to test the non-default behavior''')
h = Header(hstr, maxlinelen=1024, header_name='Subject')
eq(h.encode(), hstr)
def test_us_ascii_header(self):
eq = self.assertEqual
s = 'hello'
x = decode_header(s)
eq(x, [('hello', None)])
h = make_header(x)
eq(s, h.encode())
def test_string_charset(self):
eq = self.assertEqual
h = Header()
h.append('hello', 'iso-8859-1')
eq(h, '=?iso-8859-1?q?hello?=')
## def test_unicode_error(self):
## raises = self.assertRaises
## raises(UnicodeError, Header, u'[P\xf6stal]', 'us-ascii')
## raises(UnicodeError, Header, '[P\xf6stal]', 'us-ascii')
## h = Header()
## raises(UnicodeError, h.append, u'[P\xf6stal]', 'us-ascii')
## raises(UnicodeError, h.append, '[P\xf6stal]', 'us-ascii')
## raises(UnicodeError, Header, u'\u83ca\u5730\u6642\u592b', 'iso-8859-1')
def test_utf8_shortest(self):
eq = self.assertEqual
h = Header(u'p\xf6stal', 'utf-8')
eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=')
h = Header(u'\u83ca\u5730\u6642\u592b', 'utf-8')
eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=')
def test_bad_8bit_header(self):
raises = self.assertRaises
eq = self.assertEqual
x = 'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
raises(UnicodeError, Header, x)
h = Header()
raises(UnicodeError, h.append, x)
eq(str(Header(x, errors='replace')), x)
h.append(x, errors='replace')
eq(str(h), x)
def test_encoded_adjacent_nonencoded(self):
eq = self.assertEqual
h = Header()
h.append('hello', 'iso-8859-1')
h.append('world')
s = h.encode()
eq(s, '=?iso-8859-1?q?hello?= world')
h = make_header(decode_header(s))
eq(h.encode(), s)
def test_whitespace_eater(self):
eq = self.assertEqual
s = 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztk=?= =?koi8-r?q?=CA?= zz.'
parts = decode_header(s)
eq(parts, [('Subject:', None), ('\xf0\xd2\xcf\xd7\xc5\xd2\xcb\xc1 \xce\xc1 \xc6\xc9\xce\xc1\xcc\xd8\xce\xd9\xca', 'koi8-r'), ('zz.', None)])
hdr = make_header(parts)
eq(hdr.encode(),
'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztnK?= zz.')
def test_broken_base64_header(self):
raises = self.assertRaises
s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3IQ?='
raises(Errors.HeaderParseError, decode_header, s)
# Test RFC 2231 header parameters (en/de)coding
class TestRFC2231(TestEmailBase):
def test_get_param(self):
eq = self.assertEqual
msg = self._msgobj('msg_29.txt')
eq(msg.get_param('title'),
('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
eq(msg.get_param('title', unquote=False),
('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"'))
def test_set_param(self):
eq = self.assertEqual
msg = Message()
msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
charset='us-ascii')
eq(msg.get_param('title'),
('us-ascii', '', 'This is even more ***fun*** isn\'t it!'))
msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
charset='us-ascii', language='en')
eq(msg.get_param('title'),
('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
msg = self._msgobj('msg_01.txt')
msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
charset='us-ascii', language='en')
eq(msg.as_string(), """\
Return-Path: <bbb@zzz.org>
Delivered-To: bbb@zzz.org
Received: by mail.zzz.org (Postfix, from userid 889)
\tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Message-ID: <15090.61304.110929.45684@aaa.zzz.org>
From: bbb@ddd.com (John X. Doe)
To: bbb@zzz.org
Subject: This is a test message
Date: Fri, 4 May 2001 14:05:44 -0400
Content-Type: text/plain; charset=us-ascii;
\ttitle*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
Hi,
Do you like this message?
-Me
""")
def test_del_param(self):
eq = self.ndiffAssertEqual
msg = self._msgobj('msg_01.txt')
msg.set_param('foo', 'bar', charset='us-ascii', language='en')
msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
charset='us-ascii', language='en')
msg.del_param('foo', header='Content-Type')
eq(msg.as_string(), """\
Return-Path: <bbb@zzz.org>
Delivered-To: bbb@zzz.org
Received: by mail.zzz.org (Postfix, from userid 889)
\tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Message-ID: <15090.61304.110929.45684@aaa.zzz.org>
From: bbb@ddd.com (John X. Doe)
To: bbb@zzz.org
Subject: This is a test message
Date: Fri, 4 May 2001 14:05:44 -0400
Content-Type: text/plain; charset="us-ascii";
\ttitle*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
Hi,
Do you like this message?
-Me
""")
def test_rfc2231_get_content_charset(self):
eq = self.assertEqual
msg = self._msgobj('msg_32.txt')
eq(msg.get_content_charset(), 'us-ascii')
def test_rfc2231_no_language_or_charset(self):
m = '''\
Content-Transfer-Encoding: 8bit
Content-Disposition: inline; filename="file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm"
Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm
'''
msg = email.message_from_string(m)
param = msg.get_param('NAME')
self.failIf(isinstance(param, tuple))
self.assertEqual(
param,
'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm')
def test_rfc2231_no_language_or_charset_in_filename(self):
m = '''\
Content-Disposition: inline;
\tfilename*0*="''This%20is%20even%20more%20";
\tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_filename(),
'This is even more ***fun*** is it not.pdf')
def test_rfc2231_no_language_or_charset_in_filename_encoded(self):
m = '''\
Content-Disposition: inline;
\tfilename*0*="''This%20is%20even%20more%20";
\tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_filename(),
'This is even more ***fun*** is it not.pdf')
def test_rfc2231_partly_encoded(self):
m = '''\
Content-Disposition: inline;
\tfilename*0="''This%20is%20even%20more%20";
\tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(
msg.get_filename(),
'This%20is%20even%20more%20***fun*** is it not.pdf')
def test_rfc2231_partly_nonencoded(self):
m = '''\
Content-Disposition: inline;
\tfilename*0="This%20is%20even%20more%20";
\tfilename*1="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(
msg.get_filename(),
'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20is it not.pdf')
def test_rfc2231_no_language_or_charset_in_boundary(self):
m = '''\
Content-Type: multipart/alternative;
\tboundary*0*="''This%20is%20even%20more%20";
\tboundary*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tboundary*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_boundary(),
'This is even more ***fun*** is it not.pdf')
def test_rfc2231_no_language_or_charset_in_charset(self):
# This is a nonsensical charset value, but tests the code anyway
m = '''\
Content-Type: text/plain;
\tcharset*0*="This%20is%20even%20more%20";
\tcharset*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tcharset*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_content_charset(),
'this is even more ***fun*** is it not.pdf')
def test_rfc2231_bad_encoding_in_filename(self):
m = '''\
Content-Disposition: inline;
\tfilename*0*="bogus'xx'This%20is%20even%20more%20";
\tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2="is it not.pdf"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_filename(),
'This is even more ***fun*** is it not.pdf')
def test_rfc2231_bad_encoding_in_charset(self):
m = """\
Content-Type: text/plain; charset*=bogus''utf-8%E2%80%9D
"""
msg = email.message_from_string(m)
# This should return None because non-ascii characters in the charset
# are not allowed.
self.assertEqual(msg.get_content_charset(), None)
def test_rfc2231_bad_character_in_charset(self):
m = """\
Content-Type: text/plain; charset*=ascii''utf-8%E2%80%9D
"""
msg = email.message_from_string(m)
# This should return None because non-ascii characters in the charset
# are not allowed.
self.assertEqual(msg.get_content_charset(), None)
def test_rfc2231_bad_character_in_filename(self):
m = '''\
Content-Disposition: inline;
\tfilename*0*="ascii'xx'This%20is%20even%20more%20";
\tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
\tfilename*2*="is it not.pdf%E2"
'''
msg = email.message_from_string(m)
self.assertEqual(msg.get_filename(),
u'This is even more ***fun*** is it not.pdf\ufffd')
def test_rfc2231_unknown_encoding(self):
m = """\
Content-Transfer-Encoding: 8bit
Content-Disposition: inline; filename*=X-UNKNOWN''myfile.txt
"""
msg = email.message_from_string(m)
self.assertEqual(msg.get_filename(), 'myfile.txt')
def test_rfc2231_single_tick_in_filename_extended(self):
eq = self.assertEqual
m = """\
Content-Type: application/x-foo;
\tname*0*=\"Frank's\"; name*1*=\" Document\"
"""
msg = email.message_from_string(m)
charset, language, s = msg.get_param('name')
eq(charset, None)
eq(language, None)
eq(s, "Frank's Document")
def test_rfc2231_single_tick_in_filename(self):
m = """\
Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\"
"""
msg = email.message_from_string(m)
param = msg.get_param('name')
self.failIf(isinstance(param, tuple))
self.assertEqual(param, "Frank's Document")
def test_rfc2231_tick_attack_extended(self):
eq = self.assertEqual
m = """\
Content-Type: application/x-foo;
\tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\"
"""
msg = email.message_from_string(m)
charset, language, s = msg.get_param('name')
eq(charset, 'us-ascii')
eq(language, 'en-us')
eq(s, "Frank's Document")
def test_rfc2231_tick_attack(self):
m = """\
Content-Type: application/x-foo;
\tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\"
"""
msg = email.message_from_string(m)
param = msg.get_param('name')
self.failIf(isinstance(param, tuple))
self.assertEqual(param, "us-ascii'en-us'Frank's Document")
def test_rfc2231_no_extended_values(self):
eq = self.assertEqual
m = """\
Content-Type: application/x-foo; name=\"Frank's Document\"
"""
msg = email.message_from_string(m)
eq(msg.get_param('name'), "Frank's Document")
def test_rfc2231_encoded_then_unencoded_segments(self):
eq = self.assertEqual
m = """\
Content-Type: application/x-foo;
\tname*0*=\"us-ascii'en-us'My\";
\tname*1=\" Document\";
\tname*2*=\" For You\"
"""
msg = email.message_from_string(m)
charset, language, s = msg.get_param('name')
eq(charset, 'us-ascii')
eq(language, 'en-us')
eq(s, 'My Document For You')
def test_rfc2231_unencoded_then_encoded_segments(self):
eq = self.assertEqual
m = """\
Content-Type: application/x-foo;
\tname*0=\"us-ascii'en-us'My\";
\tname*1*=\" Document\";
\tname*2*=\" For You\"
"""
msg = email.message_from_string(m)
charset, language, s = msg.get_param('name')
eq(charset, 'us-ascii')
eq(language, 'en-us')
eq(s, 'My Document For You')
def _testclasses():
mod = sys.modules[__name__]
return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
def suite():
suite = unittest.TestSuite()
for testclass in _testclasses():
suite.addTest(unittest.makeSuite(testclass))
return suite
def test_main():
for testclass in _testclasses():
run_unittest(testclass)
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| apache-2.0 |
nelmiux/CarnotKE | jyhton/lib-python/2.7/xml/etree/ElementPath.py | 273 | 9475 | #
# ElementTree
# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
#
# limited xpath support for element trees
#
# history:
# 2003-05-23 fl created
# 2003-05-28 fl added support for // etc
# 2003-08-27 fl fixed parsing of periods in element names
# 2007-09-10 fl new selection engine
# 2007-09-12 fl fixed parent selector
# 2007-09-13 fl added iterfind; changed findall to return a list
# 2007-11-30 fl added namespaces support
# 2009-10-30 fl added child element value filter
#
# Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The ElementTree toolkit is
#
# Copyright (c) 1999-2009 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/psf/license for licensing details.
##
# Implementation module for XPath support. There's usually no reason
# to import this module directly; the <b>ElementTree</b> does this for
# you, if needed.
##
import re
xpath_tokenizer_re = re.compile(
"("
"'[^']*'|\"[^\"]*\"|"
"::|"
"//?|"
"\.\.|"
"\(\)|"
"[/.*:\[\]\(\)@=])|"
"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
"\s+"
)
def xpath_tokenizer(pattern, namespaces=None):
for token in xpath_tokenizer_re.findall(pattern):
tag = token[1]
if tag and tag[0] != "{" and ":" in tag:
try:
prefix, uri = tag.split(":", 1)
if not namespaces:
raise KeyError
yield token[0], "{%s}%s" % (namespaces[prefix], uri)
except KeyError:
raise SyntaxError("prefix %r not found in prefix map" % prefix)
else:
yield token
def get_parent_map(context):
parent_map = context.parent_map
if parent_map is None:
context.parent_map = parent_map = {}
for p in context.root.iter():
for e in p:
parent_map[e] = p
return parent_map
def prepare_child(next, token):
tag = token[1]
def select(context, result):
for elem in result:
for e in elem:
if e.tag == tag:
yield e
return select
def prepare_star(next, token):
def select(context, result):
for elem in result:
for e in elem:
yield e
return select
def prepare_self(next, token):
def select(context, result):
for elem in result:
yield elem
return select
def prepare_descendant(next, token):
token = next()
if token[0] == "*":
tag = "*"
elif not token[0]:
tag = token[1]
else:
raise SyntaxError("invalid descendant")
def select(context, result):
for elem in result:
for e in elem.iter(tag):
if e is not elem:
yield e
return select
def prepare_parent(next, token):
def select(context, result):
# FIXME: raise error if .. is applied at toplevel?
parent_map = get_parent_map(context)
result_map = {}
for elem in result:
if elem in parent_map:
parent = parent_map[elem]
if parent not in result_map:
result_map[parent] = None
yield parent
return select
def prepare_predicate(next, token):
# FIXME: replace with real parser!!! refs:
# http://effbot.org/zone/simple-iterator-parser.htm
# http://javascript.crockford.com/tdop/tdop.html
signature = []
predicate = []
while 1:
token = next()
if token[0] == "]":
break
if token[0] and token[0][:1] in "'\"":
token = "'", token[0][1:-1]
signature.append(token[0] or "-")
predicate.append(token[1])
signature = "".join(signature)
# use signature to determine predicate type
if signature == "@-":
# [@attribute] predicate
key = predicate[1]
def select(context, result):
for elem in result:
if elem.get(key) is not None:
yield elem
return select
if signature == "@-='":
# [@attribute='value']
key = predicate[1]
value = predicate[-1]
def select(context, result):
for elem in result:
if elem.get(key) == value:
yield elem
return select
if signature == "-" and not re.match("\d+$", predicate[0]):
# [tag]
tag = predicate[0]
def select(context, result):
for elem in result:
if elem.find(tag) is not None:
yield elem
return select
if signature == "-='" and not re.match("\d+$", predicate[0]):
# [tag='value']
tag = predicate[0]
value = predicate[-1]
def select(context, result):
for elem in result:
for e in elem.findall(tag):
if "".join(e.itertext()) == value:
yield elem
break
return select
if signature == "-" or signature == "-()" or signature == "-()-":
# [index] or [last()] or [last()-index]
if signature == "-":
index = int(predicate[0]) - 1
else:
if predicate[0] != "last":
raise SyntaxError("unsupported function")
if signature == "-()-":
try:
index = int(predicate[2]) - 1
except ValueError:
raise SyntaxError("unsupported expression")
else:
index = -1
def select(context, result):
parent_map = get_parent_map(context)
for elem in result:
try:
parent = parent_map[elem]
# FIXME: what if the selector is "*" ?
elems = list(parent.findall(elem.tag))
if elems[index] is elem:
yield elem
except (IndexError, KeyError):
pass
return select
raise SyntaxError("invalid predicate")
ops = {
"": prepare_child,
"*": prepare_star,
".": prepare_self,
"..": prepare_parent,
"//": prepare_descendant,
"[": prepare_predicate,
}
_cache = {}
class _SelectorContext:
parent_map = None
def __init__(self, root):
self.root = root
# --------------------------------------------------------------------
##
# Generate all matching objects.
def iterfind(elem, path, namespaces=None):
# compile selector pattern
if path[-1:] == "/":
path = path + "*" # implicit all (FIXME: keep this?)
try:
selector = _cache[path]
except KeyError:
if len(_cache) > 100:
_cache.clear()
if path[:1] == "/":
raise SyntaxError("cannot use absolute path on element")
next = iter(xpath_tokenizer(path, namespaces)).next
token = next()
selector = []
while 1:
try:
selector.append(ops[token[0]](next, token))
except StopIteration:
raise SyntaxError("invalid path")
try:
token = next()
if token[0] == "/":
token = next()
except StopIteration:
break
_cache[path] = selector
# execute selector pattern
result = [elem]
context = _SelectorContext(elem)
for select in selector:
result = select(context, result)
return result
##
# Find first matching object.
def find(elem, path, namespaces=None):
try:
return iterfind(elem, path, namespaces).next()
except StopIteration:
return None
##
# Find all matching objects.
def findall(elem, path, namespaces=None):
return list(iterfind(elem, path, namespaces))
##
# Find text for first matching object.
def findtext(elem, path, default=None, namespaces=None):
try:
elem = iterfind(elem, path, namespaces).next()
return elem.text or ""
except StopIteration:
return default
| apache-2.0 |
Lekanich/intellij-community | python/helpers/pydev/third_party/pep8/lib2to3/lib2to3/fixes/fix_raise.py | 327 | 2934 | """Fixer for 'raise E, V, T'
raise -> raise
raise E -> raise E
raise E, V -> raise E(V)
raise E, V, T -> raise E(V).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)
raise (((E, E'), E''), E'''), V -> raise E(V)
raise "foo", V, T -> warns about string exceptions
CAVEATS:
1) "raise E, V" will be incorrectly translated if V is an exception
instance. The correct Python 3 idiom is
raise E from V
but since we can't detect instance-hood by syntax alone and since
any client code would have to be changed as well, we don't automate
this.
"""
# Author: Collin Winter
# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Attr, ArgList, is_tuple
class FixRaise(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
"""
def transform(self, node, results):
syms = self.syms
exc = results["exc"].clone()
if exc.type == token.STRING:
msg = "Python 3 does not support string exceptions"
self.cannot_convert(node, msg)
return
# Python 2 supports
# raise ((((E1, E2), E3), E4), E5), V
# as a synonym for
# raise E1, V
# Since Python 3 will not support this, we recurse down any tuple
# literals, always taking the first element.
if is_tuple(exc):
while is_tuple(exc):
# exc.children[1:-1] is the unparenthesized tuple
# exc.children[1].children[0] is the first element of the tuple
exc = exc.children[1].children[0].clone()
exc.prefix = u" "
if "val" not in results:
# One-argument raise
new = pytree.Node(syms.raise_stmt, [Name(u"raise"), exc])
new.prefix = node.prefix
return new
val = results["val"].clone()
if is_tuple(val):
args = [c.clone() for c in val.children[1:-1]]
else:
val.prefix = u""
args = [val]
if "tb" in results:
tb = results["tb"].clone()
tb.prefix = u""
e = exc
# If there's a traceback and None is passed as the value, then don't
# add a call, since the user probably just wants to add a
# traceback. See issue #9661.
if val.type != token.NAME or val.value != u"None":
e = Call(exc, args)
with_tb = Attr(e, Name(u'with_traceback')) + [ArgList([tb])]
new = pytree.Node(syms.simple_stmt, [Name(u"raise")] + with_tb)
new.prefix = node.prefix
return new
else:
return pytree.Node(syms.raise_stmt,
[Name(u"raise"), Call(exc, args)],
prefix=node.prefix)
| apache-2.0 |
coderbone/SickRage | lib/sqlalchemy/sql/elements.py | 75 | 117708 | # sql/elements.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Core SQL expression elements, including :class:`.ClauseElement`,
:class:`.ColumnElement`, and derived classes.
"""
from __future__ import unicode_literals
from .. import util, exc, inspection
from . import type_api
from . import operators
from .visitors import Visitable, cloned_traverse, traverse
from .annotation import Annotated
import itertools
from .base import Executable, PARSE_AUTOCOMMIT, Immutable, NO_ARG
from .base import _generative, Generative
import re
import operator
def _clone(element, **kw):
return element._clone()
def collate(expression, collation):
"""Return the clause ``expression COLLATE collation``.
e.g.::
collate(mycolumn, 'utf8_bin')
produces::
mycolumn COLLATE utf8_bin
"""
expr = _literal_as_binds(expression)
return BinaryExpression(
expr,
_literal_as_text(collation),
operators.collate, type_=expr.type)
def between(expr, lower_bound, upper_bound):
"""Produce a ``BETWEEN`` predicate clause.
E.g.::
from sqlalchemy import between
stmt = select([users_table]).where(between(users_table.c.id, 5, 7))
Would produce SQL resembling::
SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
The :func:`.between` function is a standalone version of the
:meth:`.ColumnElement.between` method available on all
SQL expressions, as in::
stmt = select([users_table]).where(users_table.c.id.between(5, 7))
All arguments passed to :func:`.between`, including the left side
column expression, are coerced from Python scalar values if a
the value is not a :class:`.ColumnElement` subclass. For example,
three fixed values can be compared as in::
print(between(5, 3, 7))
Which would produce::
:param_1 BETWEEN :param_2 AND :param_3
:param expr: a column expression, typically a :class:`.ColumnElement`
instance or alternatively a Python scalar expression to be coerced
into a column expression, serving as the left side of the ``BETWEEN``
expression.
:param lower_bound: a column or Python scalar expression serving as the lower
bound of the right side of the ``BETWEEN`` expression.
:param upper_bound: a column or Python scalar expression serving as the
upper bound of the right side of the ``BETWEEN`` expression.
.. seealso::
:meth:`.ColumnElement.between`
"""
expr = _literal_as_binds(expr)
return expr.between(lower_bound, upper_bound)
def literal(value, type_=None):
"""Return a literal clause, bound to a bind parameter.
Literal clauses are created automatically when non- :class:`.ClauseElement`
objects (such as strings, ints, dates, etc.) are used in a comparison
operation with a :class:`.ColumnElement`
subclass, such as a :class:`~sqlalchemy.schema.Column` object.
Use this function to force the
generation of a literal clause, which will be created as a
:class:`BindParameter` with a bound value.
:param value: the value to be bound. Can be any Python object supported by
the underlying DB-API, or is translatable via the given type argument.
:param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which
will provide bind-parameter translation for this literal.
"""
return BindParameter(None, value, type_=type_, unique=True)
def type_coerce(expression, type_):
"""Associate a SQL expression with a particular type, without rendering
``CAST``.
E.g.::
from sqlalchemy import type_coerce
stmt = select([type_coerce(log_table.date_string, StringDateTime())])
The above construct will produce SQL that is usually otherwise unaffected
by the :func:`.type_coerce` call::
SELECT date_string FROM log
However, when result rows are fetched, the ``StringDateTime`` type
will be applied to result rows on behalf of the ``date_string`` column.
A type that features bound-value handling will also have that behavior
take effect when literal values or :func:`.bindparam` constructs are
passed to :func:`.type_coerce` as targets.
For example, if a type implements the :meth:`.TypeEngine.bind_expression`
method or :meth:`.TypeEngine.bind_processor` method or equivalent,
these functions will take effect at statement compliation/execution time
when a literal value is passed, as in::
# bound-value handling of MyStringType will be applied to the
# literal value "some string"
stmt = select([type_coerce("some string", MyStringType)])
:func:`.type_coerce` is similar to the :func:`.cast` function,
except that it does not render the ``CAST`` expression in the resulting
statement.
:param expression: A SQL expression, such as a :class:`.ColumnElement` expression
or a Python string which will be coerced into a bound literal value.
:param type_: A :class:`.TypeEngine` class or instance indicating
the type to which the the expression is coerced.
.. seealso::
:func:`.cast`
"""
type_ = type_api.to_instance(type_)
if hasattr(expression, '__clause_element__'):
return type_coerce(expression.__clause_element__(), type_)
elif isinstance(expression, BindParameter):
bp = expression._clone()
bp.type = type_
return bp
elif not isinstance(expression, Visitable):
if expression is None:
return Null()
else:
return literal(expression, type_=type_)
else:
return Label(None, expression, type_=type_)
def outparam(key, type_=None):
"""Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
The ``outparam`` can be used like a regular function parameter.
The "output" value will be available from the
:class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters``
attribute, which returns a dictionary containing the values.
"""
return BindParameter(
key, None, type_=type_, unique=False, isoutparam=True)
def not_(clause):
"""Return a negation of the given clause, i.e. ``NOT(clause)``.
The ``~`` operator is also overloaded on all
:class:`.ColumnElement` subclasses to produce the
same result.
"""
return operators.inv(_literal_as_binds(clause))
@inspection._self_inspects
class ClauseElement(Visitable):
"""Base class for elements of a programmatically constructed SQL
expression.
"""
__visit_name__ = 'clause'
_annotations = {}
supports_execution = False
_from_objects = []
bind = None
_is_clone_of = None
is_selectable = False
is_clause_element = True
_order_by_label_element = None
def _clone(self):
"""Create a shallow copy of this ClauseElement.
This method may be used by a generative API. Its also used as
part of the "deep" copy afforded by a traversal that combines
the _copy_internals() method.
"""
c = self.__class__.__new__(self.__class__)
c.__dict__ = self.__dict__.copy()
ClauseElement._cloned_set._reset(c)
ColumnElement.comparator._reset(c)
# this is a marker that helps to "equate" clauses to each other
# when a Select returns its list of FROM clauses. the cloning
# process leaves around a lot of remnants of the previous clause
# typically in the form of column expressions still attached to the
# old table.
c._is_clone_of = self
return c
@property
def _constructor(self):
"""return the 'constructor' for this ClauseElement.
This is for the purposes for creating a new object of
this type. Usually, its just the element's __class__.
However, the "Annotated" version of the object overrides
to return the class of its proxied element.
"""
return self.__class__
@util.memoized_property
def _cloned_set(self):
"""Return the set consisting all cloned ancestors of this
ClauseElement.
Includes this ClauseElement. This accessor tends to be used for
FromClause objects to identify 'equivalent' FROM clauses, regardless
of transformative operations.
"""
s = util.column_set()
f = self
while f is not None:
s.add(f)
f = f._is_clone_of
return s
def __getstate__(self):
d = self.__dict__.copy()
d.pop('_is_clone_of', None)
return d
def _annotate(self, values):
"""return a copy of this ClauseElement with annotations
updated by the given dictionary.
"""
return Annotated(self, values)
def _with_annotations(self, values):
"""return a copy of this ClauseElement with annotations
replaced by the given dictionary.
"""
return Annotated(self, values)
def _deannotate(self, values=None, clone=False):
"""return a copy of this :class:`.ClauseElement` with annotations
removed.
:param values: optional tuple of individual values
to remove.
"""
if clone:
# clone is used when we are also copying
# the expression for a deep deannotation
return self._clone()
else:
# if no clone, since we have no annotations we return
# self
return self
def _execute_on_connection(self, connection, multiparams, params):
return connection._execute_clauseelement(self, multiparams, params)
def unique_params(self, *optionaldict, **kwargs):
"""Return a copy with :func:`bindparam()` elements replaced.
Same functionality as ``params()``, except adds `unique=True`
to affected bind parameters so that multiple statements can be
used.
"""
return self._params(True, optionaldict, kwargs)
def params(self, *optionaldict, **kwargs):
"""Return a copy with :func:`bindparam()` elements replaced.
Returns a copy of this ClauseElement with :func:`bindparam()`
elements replaced with values taken from the given dictionary::
>>> clause = column('x') + bindparam('foo')
>>> print clause.compile().params
{'foo':None}
>>> print clause.params({'foo':7}).compile().params
{'foo':7}
"""
return self._params(False, optionaldict, kwargs)
def _params(self, unique, optionaldict, kwargs):
if len(optionaldict) == 1:
kwargs.update(optionaldict[0])
elif len(optionaldict) > 1:
raise exc.ArgumentError(
"params() takes zero or one positional dictionary argument")
def visit_bindparam(bind):
if bind.key in kwargs:
bind.value = kwargs[bind.key]
bind.required = False
if unique:
bind._convert_to_unique()
return cloned_traverse(self, {}, {'bindparam': visit_bindparam})
def compare(self, other, **kw):
"""Compare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a
straight identity comparison.
\**kw are arguments consumed by subclass compare() methods and
may be used to modify the criteria for comparison.
(see :class:`.ColumnElement`)
"""
return self is other
def _copy_internals(self, clone=_clone, **kw):
"""Reassign internal elements to be clones of themselves.
Called during a copy-and-traverse operation on newly
shallow-copied elements to create a deep copy.
The given clone function should be used, which may be applying
additional transformations to the element (i.e. replacement
traversal, cloned traversal, annotations).
"""
pass
def get_children(self, **kwargs):
"""Return immediate child elements of this :class:`.ClauseElement`.
This is used for visit traversal.
\**kwargs may contain flags that change the collection that is
returned, for example to return a subset of items in order to
cut down on larger traversals, or to return child items from a
different context (such as schema-level collections instead of
clause-level).
"""
return []
def self_group(self, against=None):
"""Apply a 'grouping' to this :class:`.ClauseElement`.
This method is overridden by subclasses to return a
"grouping" construct, i.e. parenthesis. In particular
it's used by "binary" expressions to provide a grouping
around themselves when placed into a larger expression,
as well as by :func:`.select` constructs when placed into
the FROM clause of another :func:`.select`. (Note that
subqueries should be normally created using the
:meth:`.Select.alias` method, as many platforms require
nested SELECT statements to be named).
As expressions are composed together, the application of
:meth:`self_group` is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy's
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like ``x OR (y AND z)`` - AND takes precedence
over OR.
The base :meth:`self_group` method of :class:`.ClauseElement`
just returns self.
"""
return self
@util.dependencies("sqlalchemy.engine.default")
def compile(self, default, bind=None, dialect=None, **kw):
"""Compile this SQL expression.
The return value is a :class:`~.Compiled` object.
Calling ``str()`` or ``unicode()`` on the returned value will yield a
string representation of the result. The
:class:`~.Compiled` object also can return a
dictionary of bind parameter names and values
using the ``params`` accessor.
:param bind: An ``Engine`` or ``Connection`` from which a
``Compiled`` will be acquired. This argument takes precedence over
this :class:`.ClauseElement`'s bound engine, if any.
:param column_keys: Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If ``None``, all columns from the target table
object are rendered.
:param dialect: A ``Dialect`` instance from which a ``Compiled``
will be acquired. This argument takes precedence over the `bind`
argument as well as this :class:`.ClauseElement`'s bound engine, if
any.
:param inline: Used for INSERT statements, for a dialect which does
not support inline retrieval of newly generated primary key
columns, will force the expression used to create the new primary
key value to be rendered inline within the INSERT statement's
VALUES clause. This typically refers to Sequence execution but may
also refer to any server-side default generation function
associated with a primary key `Column`.
"""
if not dialect:
if bind:
dialect = bind.dialect
elif self.bind:
dialect = self.bind.dialect
bind = self.bind
else:
dialect = default.DefaultDialect()
return self._compiler(dialect, bind=bind, **kw)
def _compiler(self, dialect, **kw):
"""Return a compiler appropriate for this ClauseElement, given a
Dialect."""
return dialect.statement_compiler(dialect, self, **kw)
def __str__(self):
if util.py3k:
return str(self.compile())
else:
return unicode(self.compile()).encode('ascii', 'backslashreplace')
def __and__(self, other):
return and_(self, other)
def __or__(self, other):
return or_(self, other)
def __invert__(self):
if hasattr(self, 'negation_clause'):
return self.negation_clause
else:
return self._negate()
def __bool__(self):
raise TypeError("Boolean value of this clause is not defined")
__nonzero__ = __bool__
def _negate(self):
return UnaryExpression(
self.self_group(against=operators.inv),
operator=operators.inv,
negate=None)
def __repr__(self):
friendly = getattr(self, 'description', None)
if friendly is None:
return object.__repr__(self)
else:
return '<%s.%s at 0x%x; %s>' % (
self.__module__, self.__class__.__name__, id(self), friendly)
class ColumnElement(ClauseElement, operators.ColumnOperators):
"""Represent a column-oriented SQL expression suitable for usage in the
"columns" clause, WHERE clause etc. of a statement.
While the most familiar kind of :class:`.ColumnElement` is the
:class:`.Column` object, :class:`.ColumnElement` serves as the basis
for any unit that may be present in a SQL expression, including
the expressions themselves, SQL functions, bound parameters,
literal expressions, keywords such as ``NULL``, etc.
:class:`.ColumnElement` is the ultimate base class for all such elements.
A wide variety of SQLAlchemy Core functions work at the SQL expression level,
and are intended to accept instances of :class:`.ColumnElement` as arguments.
These functions will typically document that they accept a "SQL expression"
as an argument. What this means in terms of SQLAlchemy usually refers
to an input which is either already in the form of a :class:`.ColumnElement`
object, or a value which can be **coerced** into one. The coercion
rules followed by most, but not all, SQLAlchemy Core functions with regards
to SQL expressions are as follows:
* a literal Python value, such as a string, integer or floating
point value, boolean, datetime, ``Decimal`` object, or virtually
any other Python object, will be coerced into a "literal bound value".
This generally means that a :func:`.bindparam` will be produced
featuring the given value embedded into the construct; the resulting
:class:`.BindParameter` object is an instance of :class:`.ColumnElement`.
The Python value will ultimately be sent to the DBAPI at execution time as a
paramterized argument to the ``execute()`` or ``executemany()`` methods,
after SQLAlchemy type-specific converters (e.g. those provided by
any associated :class:`.TypeEngine` objects) are applied to the value.
* any special object value, typically ORM-level constructs, which feature
a method called ``__clause_element__()``. The Core expression system
looks for this method when an object of otherwise unknown type is passed
to a function that is looking to coerce the argument into a :class:`.ColumnElement`
expression. The ``__clause_element__()`` method, if present, should
return a :class:`.ColumnElement` instance. The primary use of
``__clause_element__()`` within SQLAlchemy is that of class-bound attributes
on ORM-mapped classes; a ``User`` class which contains a mapped attribute
named ``.name`` will have a method ``User.name.__clause_element__()``
which when invoked returns the :class:`.Column` called ``name`` associated
with the mapped table.
* The Python ``None`` value is typically interpreted as ``NULL``, which
in SQLAlchemy Core produces an instance of :func:`.null`.
A :class:`.ColumnElement` provides the ability to generate new
:class:`.ColumnElement`
objects using Python expressions. This means that Python operators
such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations,
and allow the instantiation of further :class:`.ColumnElement` instances
which are composed from other, more fundamental :class:`.ColumnElement`
objects. For example, two :class:`.ColumnClause` objects can be added
together with the addition operator ``+`` to produce
a :class:`.BinaryExpression`.
Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses
of :class:`.ColumnElement`::
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print column('a') + column('b')
a + b
.. seealso::
:class:`.Column`
:func:`.expression.column`
"""
__visit_name__ = 'column'
primary_key = False
foreign_keys = []
_label = None
_key_label = key = None
_alt_names = ()
def self_group(self, against=None):
if against in (operators.and_, operators.or_, operators._asbool) and \
self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
return AsBoolean(self, operators.istrue, operators.isfalse)
else:
return self
def _negate(self):
if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
return AsBoolean(self, operators.isfalse, operators.istrue)
else:
return super(ColumnElement, self)._negate()
@util.memoized_property
def type(self):
return type_api.NULLTYPE
@util.memoized_property
def comparator(self):
return self.type.comparator_factory(self)
def __getattr__(self, key):
try:
return getattr(self.comparator, key)
except AttributeError:
raise AttributeError(
'Neither %r object nor %r object has an attribute %r' % (
type(self).__name__,
type(self.comparator).__name__,
key)
)
def operate(self, op, *other, **kwargs):
return op(self.comparator, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs):
return op(other, self.comparator, **kwargs)
def _bind_param(self, operator, obj):
return BindParameter(None, obj,
_compared_to_operator=operator,
_compared_to_type=self.type, unique=True)
@property
def expression(self):
"""Return a column expression.
Part of the inspection interface; returns self.
"""
return self
@property
def _select_iterable(self):
return (self, )
@util.memoized_property
def base_columns(self):
return util.column_set(c for c in self.proxy_set
if not hasattr(c, '_proxies'))
@util.memoized_property
def proxy_set(self):
s = util.column_set([self])
if hasattr(self, '_proxies'):
for c in self._proxies:
s.update(c.proxy_set)
return s
def shares_lineage(self, othercolumn):
"""Return True if the given :class:`.ColumnElement`
has a common ancestor to this :class:`.ColumnElement`."""
return bool(self.proxy_set.intersection(othercolumn.proxy_set))
def _compare_name_for_result(self, other):
"""Return True if the given column element compares to this one
when targeting within a result row."""
return hasattr(other, 'name') and hasattr(self, 'name') and \
other.name == self.name
def _make_proxy(self, selectable, name=None, name_is_truncatable=False, **kw):
"""Create a new :class:`.ColumnElement` representing this
:class:`.ColumnElement` as it appears in the select list of a
descending selectable.
"""
if name is None:
name = self.anon_label
if self.key:
key = self.key
else:
try:
key = str(self)
except exc.UnsupportedCompilationError:
key = self.anon_label
else:
key = name
co = ColumnClause(
_as_truncated(name) if name_is_truncatable else name,
type_=getattr(self, 'type', None),
_selectable=selectable
)
co._proxies = [self]
if selectable._is_clone_of is not None:
co._is_clone_of = \
selectable._is_clone_of.columns.get(key)
selectable._columns[key] = co
return co
def compare(self, other, use_proxies=False, equivalents=None, **kw):
"""Compare this ColumnElement to another.
Special arguments understood:
:param use_proxies: when True, consider two columns that
share a common base column as equivalent (i.e. shares_lineage())
:param equivalents: a dictionary of columns as keys mapped to sets
of columns. If the given "other" column is present in this
dictionary, if any of the columns in the corresponding set() pass the
comparison test, the result is True. This is used to expand the
comparison to other columns that may be known to be equivalent to
this one via foreign key or other criterion.
"""
to_compare = (other, )
if equivalents and other in equivalents:
to_compare = equivalents[other].union(to_compare)
for oth in to_compare:
if use_proxies and self.shares_lineage(oth):
return True
elif hash(oth) == hash(self):
return True
else:
return False
def label(self, name):
"""Produce a column label, i.e. ``<columnname> AS <name>``.
This is a shortcut to the :func:`~.expression.label` function.
if 'name' is None, an anonymous label name will be generated.
"""
return Label(name, self, self.type)
@util.memoized_property
def anon_label(self):
"""provides a constant 'anonymous label' for this ColumnElement.
This is a label() expression which will be named at compile time.
The same label() is returned each time anon_label is called so
that expressions can reference anon_label multiple times, producing
the same label name at compile time.
the compiler uses this function automatically at compile time
for expressions that are known to be 'unnamed' like binary
expressions and function calls.
"""
return _anonymous_label('%%(%d %s)s' % (id(self), getattr(self,
'name', 'anon')))
class BindParameter(ColumnElement):
"""Represent a "bound expression".
:class:`.BindParameter` is invoked explicitly using the
:func:`.bindparam` function, as in::
from sqlalchemy import bindparam
stmt = select([users_table]).\\
where(users_table.c.name == bindparam('username'))
Detailed discussion of how :class:`.BindParameter` is used is
at :func:`.bindparam`.
.. seealso::
:func:`.bindparam`
"""
__visit_name__ = 'bindparam'
_is_crud = False
def __init__(self, key, value=NO_ARG, type_=None,
unique=False, required=NO_ARG,
quote=None, callable_=None,
isoutparam=False,
_compared_to_operator=None,
_compared_to_type=None):
"""Produce a "bound expression".
The return value is an instance of :class:`.BindParameter`; this
is a :class:`.ColumnElement` subclass which represents a so-called
"placeholder" value in a SQL expression, the value of which is supplied
at the point at which the statement in executed against a database
connection.
In SQLAlchemy, the :func:`.bindparam` construct has
the ability to carry along the actual value that will be ultimately
used at expression time. In this way, it serves not just as
a "placeholder" for eventual population, but also as a means of
representing so-called "unsafe" values which should not be rendered
directly in a SQL statement, but rather should be passed along
to the :term:`DBAPI` as values which need to be correctly escaped
and potentially handled for type-safety.
When using :func:`.bindparam` explicitly, the use case is typically
one of traditional deferment of parameters; the :func:`.bindparam`
construct accepts a name which can then be referred to at execution
time::
from sqlalchemy import bindparam
stmt = select([users_table]).\\
where(users_table.c.name == bindparam('username'))
The above statement, when rendered, will produce SQL similar to::
SELECT id, name FROM user WHERE name = :username
In order to populate the value of ``:username`` above, the value
would typically be applied at execution time to a method
like :meth:`.Connection.execute`::
result = connection.execute(stmt, username='wendy')
Explicit use of :func:`.bindparam` is also common when producing
UPDATE or DELETE statements that are to be invoked multiple times,
where the WHERE criterion of the statement is to change on each
invocation, such as::
stmt = users_table.update().\\
where(user_table.c.name == bindparam('username')).\\
values(fullname=bindparam('fullname'))
connection.execute(stmt, [
{"username": "wendy", "fullname": "Wendy Smith"},
{"username": "jack", "fullname": "Jack Jones"},
])
SQLAlchemy's Core expression system makes wide use of :func:`.bindparam`
in an implicit sense. It is typical that Python literal values passed to
virtually all SQL expression functions are coerced into fixed
:func:`.bindparam` constructs. For example, given a comparison operation
such as::
expr = users_table.c.name == 'Wendy'
The above expression will produce a :class:`.BinaryExpression`
contruct, where the left side is the :class:`.Column` object
representing the ``name`` column, and the right side is a :class:`.BindParameter`
representing the literal value::
print(repr(expr.right))
BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
The expression above will render SQL such as::
user.name = :name_1
Where the ``:name_1`` parameter name is an anonymous name. The
actual string ``Wendy`` is not in the rendered string, but is carried
along where it is later used within statement execution. If we
invoke a statement like the following::
stmt = select([users_table]).where(users_table.c.name == 'Wendy')
result = connection.execute(stmt)
We would see SQL logging output as::
SELECT "user".id, "user".name
FROM "user"
WHERE "user".name = %(name_1)s
{'name_1': 'Wendy'}
Above, we see that ``Wendy`` is passed as a parameter to the database,
while the placeholder ``:name_1`` is rendered in the appropriate form
for the target database, in this case the Postgresql database.
Similarly, :func:`.bindparam` is invoked automatically
when working with :term:`CRUD` statements as far as the "VALUES"
portion is concerned. The :func:`.insert` construct produces an
``INSERT`` expression which will, at statement execution time, generate
bound placeholders based on the arguments passed, as in::
stmt = users_table.insert()
result = connection.execute(stmt, name='Wendy')
The above will produce SQL output as::
INSERT INTO "user" (name) VALUES (%(name)s)
{'name': 'Wendy'}
The :class:`.Insert` construct, at compilation/execution time,
rendered a single :func:`.bindparam` mirroring the column
name ``name`` as a result of the single ``name`` parameter
we passed to the :meth:`.Connection.execute` method.
:param key:
the key (e.g. the name) for this bind param.
Will be used in the generated
SQL statement for dialects that use named parameters. This
value may be modified when part of a compilation operation,
if other :class:`BindParameter` objects exist with the same
key, or if its length is too long and truncation is
required.
:param value:
Initial value for this bind param. Will be used at statement
execution time as the value for this parameter passed to the
DBAPI, if no other value is indicated to the statement execution
method for this particular parameter name. Defaults to ``None``.
:param callable\_:
A callable function that takes the place of "value". The function
will be called at statement execution time to determine the
ultimate value. Used for scenarios where the actual bind
value cannot be determined at the point at which the clause
construct is created, but embedded bind values are still desirable.
:param type\_:
A :class:`.TypeEngine` class or instance representing an optional
datatype for this :func:`.bindparam`. If not passed, a type
may be determined automatically for the bind, based on the given
value; for example, trivial Python types such as ``str``,
``int``, ``bool``
may result in the :class:`.String`, :class:`.Integer` or
:class:`.Boolean` types being autoamtically selected.
The type of a :func:`.bindparam` is significant especially in that
the type will apply pre-processing to the value before it is
passed to the database. For example, a :func:`.bindparam` which
refers to a datetime value, and is specified as holding the
:class:`.DateTime` type, may apply conversion needed to the
value (such as stringification on SQLite) before passing the value
to the database.
:param unique:
if True, the key name of this :class:`.BindParameter` will be
modified if another :class:`.BindParameter` of the same name
already has been located within the containing
expression. This flag is used generally by the internals
when producing so-called "anonymous" bound expressions, it
isn't generally applicable to explicitly-named :func:`.bindparam`
constructs.
:param required:
If ``True``, a value is required at execution time. If not passed,
it defaults to ``True`` if neither :paramref:`.bindparam.value`
or :paramref:`.bindparam.callable` were passed. If either of these
parameters are present, then :paramref:`.bindparam.required` defaults
to ``False``.
.. versionchanged:: 0.8 If the ``required`` flag is not specified,
it will be set automatically to ``True`` or ``False`` depending
on whether or not the ``value`` or ``callable`` parameters
were specified.
:param quote:
True if this parameter name requires quoting and is not
currently known as a SQLAlchemy reserved word; this currently
only applies to the Oracle backend, where bound names must
sometimes be quoted.
:param isoutparam:
if True, the parameter should be treated like a stored procedure
"OUT" parameter. This applies to backends such as Oracle which
support OUT parameters.
.. seealso::
:ref:`coretutorial_bind_param`
:ref:`coretutorial_insert_expressions`
:func:`.outparam`
"""
if isinstance(key, ColumnClause):
type_ = key.type
key = key.name
if required is NO_ARG:
required = (value is NO_ARG and callable_ is None)
if value is NO_ARG:
value = None
if quote is not None:
key = quoted_name(key, quote)
if unique:
self.key = _anonymous_label('%%(%d %s)s' % (id(self), key
or 'param'))
else:
self.key = key or _anonymous_label('%%(%d param)s'
% id(self))
# identifying key that won't change across
# clones, used to identify the bind's logical
# identity
self._identifying_key = self.key
# key that was passed in the first place, used to
# generate new keys
self._orig_key = key or 'param'
self.unique = unique
self.value = value
self.callable = callable_
self.isoutparam = isoutparam
self.required = required
if type_ is None:
if _compared_to_type is not None:
self.type = \
_compared_to_type.coerce_compared_value(
_compared_to_operator, value)
else:
self.type = type_api._type_map.get(type(value),
type_api.NULLTYPE)
elif isinstance(type_, type):
self.type = type_()
else:
self.type = type_
def _with_value(self, value):
"""Return a copy of this :class:`.BindParameter` with the given value set."""
cloned = self._clone()
cloned.value = value
cloned.callable = None
cloned.required = False
if cloned.type is type_api.NULLTYPE:
cloned.type = type_api._type_map.get(type(value),
type_api.NULLTYPE)
return cloned
@property
def effective_value(self):
"""Return the value of this bound parameter,
taking into account if the ``callable`` parameter
was set.
The ``callable`` value will be evaluated
and returned if present, else ``value``.
"""
if self.callable:
return self.callable()
else:
return self.value
def _clone(self):
c = ClauseElement._clone(self)
if self.unique:
c.key = _anonymous_label('%%(%d %s)s' % (id(c), c._orig_key
or 'param'))
return c
def _convert_to_unique(self):
if not self.unique:
self.unique = True
self.key = _anonymous_label('%%(%d %s)s' % (id(self),
self._orig_key or 'param'))
def compare(self, other, **kw):
"""Compare this :class:`BindParameter` to the given
clause."""
return isinstance(other, BindParameter) \
and self.type._compare_type_affinity(other.type) \
and self.value == other.value
def __getstate__(self):
"""execute a deferred value for serialization purposes."""
d = self.__dict__.copy()
v = self.value
if self.callable:
v = self.callable()
d['callable'] = None
d['value'] = v
return d
def __repr__(self):
return 'BindParameter(%r, %r, type_=%r)' % (self.key,
self.value, self.type)
class TypeClause(ClauseElement):
"""Handle a type keyword in a SQL statement.
Used by the ``Case`` statement.
"""
__visit_name__ = 'typeclause'
def __init__(self, type):
self.type = type
class TextClause(Executable, ClauseElement):
"""Represent a literal SQL text fragment.
E.g.::
from sqlalchemy import text
t = text("SELECT * FROM users")
result = connection.execute(t)
The :class:`.Text` construct is produced using the :func:`.text`
function; see that function for full documentation.
.. seealso::
:func:`.text`
"""
__visit_name__ = 'textclause'
_bind_params_regex = re.compile(r'(?<![:\w\x5c]):(\w+)(?!:)', re.UNICODE)
_execution_options = \
Executable._execution_options.union(
{'autocommit': PARSE_AUTOCOMMIT})
@property
def _select_iterable(self):
return (self,)
@property
def selectable(self):
return self
_hide_froms = []
def __init__(
self,
text,
bind=None):
self._bind = bind
self._bindparams = {}
def repl(m):
self._bindparams[m.group(1)] = BindParameter(m.group(1))
return ':%s' % m.group(1)
# scan the string and search for bind parameter names, add them
# to the list of bindparams
self.text = self._bind_params_regex.sub(repl, text)
@classmethod
def _create_text(self, text, bind=None, bindparams=None,
typemap=None, autocommit=None):
"""Construct a new :class:`.TextClause` clause, representing
a textual SQL string directly.
E.g.::
fom sqlalchemy import text
t = text("SELECT * FROM users")
result = connection.execute(t)
The advantages :func:`.text` provides over a plain string are
backend-neutral support for bind parameters, per-statement
execution options, as well as
bind parameter and result-column typing behavior, allowing
SQLAlchemy type constructs to play a role when executing
a statement that is specified literally. The construct can also
be provided with a ``.c`` collection of column elements, allowing
it to be embedded in other SQL expression constructs as a subquery.
Bind parameters are specified by name, using the format ``:name``.
E.g.::
t = text("SELECT * FROM users WHERE id=:user_id")
result = connection.execute(t, user_id=12)
For SQL statements where a colon is required verbatim, as within
an inline string, use a backslash to escape::
t = text("SELECT * FROM users WHERE name='\\:username'")
The :class:`.TextClause` construct includes methods which can
provide information about the bound parameters as well as the column
values which would be returned from the textual statement, assuming
it's an executable SELECT type of statement. The :meth:`.TextClause.bindparams`
method is used to provide bound parameter detail, and
:meth:`.TextClause.columns` method allows specification of
return columns including names and types::
t = text("SELECT * FROM users WHERE id=:user_id").\\
bindparams(user_id=7).\\
columns(id=Integer, name=String)
for id, name in connection.execute(t):
print(id, name)
The :func:`.text` construct is used internally in cases when
a literal string is specified for part of a larger query, such as
when a string is specified to the :meth:`.Select.where` method of
:class:`.Select`. In those cases, the same
bind parameter syntax is applied::
s = select([users.c.id, users.c.name]).where("id=:user_id")
result = connection.execute(s, user_id=12)
Using :func:`.text` explicitly usually implies the construction
of a full, standalone statement. As such, SQLAlchemy refers
to it as an :class:`.Executable` object, and it supports
the :meth:`Executable.execution_options` method. For example,
a :func:`.text` construct that should be subject to "autocommit"
can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit`
option::
t = text("EXEC my_procedural_thing()").\\
execution_options(autocommit=True)
Note that SQLAlchemy's usual "autocommit" behavior applies to
:func:`.text` constructs implicitly - that is, statements which begin
with a phrase such as ``INSERT``, ``UPDATE``, ``DELETE``,
or a variety of other phrases specific to certain backends, will
be eligible for autocommit if no transaction is in progress.
:param text:
the text of the SQL statement to be created. use ``:<param>``
to specify bind parameters; they will be compiled to their
engine-specific format.
:param autocommit:
Deprecated. Use .execution_options(autocommit=<True|False>)
to set the autocommit option.
:param bind:
an optional connection or engine to be used for this text query.
:param bindparams:
Deprecated. A list of :func:`.bindparam` instances used to
provide information about parameters embedded in the statement.
This argument now invokes the :meth:`.TextClause.bindparams`
method on the construct before returning it. E.g.::
stmt = text("SELECT * FROM table WHERE id=:id",
bindparams=[bindparam('id', value=5, type_=Integer)])
Is equivalent to::
stmt = text("SELECT * FROM table WHERE id=:id").\\
bindparams(bindparam('id', value=5, type_=Integer))
.. deprecated:: 0.9.0 the :meth:`.TextClause.bindparams` method
supersedes the ``bindparams`` argument to :func:`.text`.
:param typemap:
Deprecated. A dictionary mapping the names of columns
represented in the columns clause of a ``SELECT`` statement
to type objects,
which will be used to perform post-processing on columns within
the result set. This parameter now invokes the :meth:`.TextClause.columns`
method, which returns a :class:`.TextAsFrom` construct that gains
a ``.c`` collection and can be embedded in other expressions. E.g.::
stmt = text("SELECT * FROM table",
typemap={'id': Integer, 'name': String},
)
Is equivalent to::
stmt = text("SELECT * FROM table").columns(id=Integer, name=String)
Or alternatively::
from sqlalchemy.sql import column
stmt = text("SELECT * FROM table").columns(
column('id', Integer),
column('name', String)
)
.. deprecated:: 0.9.0 the :meth:`.TextClause.columns` method
supersedes the ``typemap`` argument to :func:`.text`.
"""
stmt = TextClause(text, bind=bind)
if bindparams:
stmt = stmt.bindparams(*bindparams)
if typemap:
stmt = stmt.columns(**typemap)
if autocommit is not None:
util.warn_deprecated('autocommit on text() is deprecated. '
'Use .execution_options(autocommit=True)')
stmt = stmt.execution_options(autocommit=autocommit)
return stmt
@_generative
def bindparams(self, *binds, **names_to_values):
"""Establish the values and/or types of bound parameters within
this :class:`.TextClause` construct.
Given a text construct such as::
from sqlalchemy import text
stmt = text("SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp")
the :meth:`.TextClause.bindparams` method can be used to establish
the initial value of ``:name`` and ``:timestamp``,
using simple keyword arguments::
stmt = stmt.bindparams(name='jack',
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
Where above, new :class:`.BindParameter` objects
will be generated with the names ``name`` and ``timestamp``, and
values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,
respectively. The types will be
inferred from the values given, in this case :class:`.String` and
:class:`.DateTime`.
When specific typing behavior is needed, the positional ``*binds``
argument can be used in which to specify :func:`.bindparam` constructs
directly. These constructs must include at least the ``key`` argument,
then an optional value and type::
from sqlalchemy import bindparam
stmt = stmt.bindparams(
bindparam('name', value='jack', type_=String),
bindparam('timestamp', type_=DateTime)
)
Above, we specified the type of :class:`.DateTime` for the ``timestamp``
bind, and the type of :class:`.String` for the ``name`` bind. In
the case of ``name`` we also set the default value of ``"jack"``.
Additional bound parameters can be supplied at statement execution
time, e.g.::
result = connection.execute(stmt,
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
The :meth:`.TextClause.bindparams` method can be called repeatedly, where
it will re-use existing :class:`.BindParameter` objects to add new information.
For example, we can call :meth:`.TextClause.bindparams` first with
typing information, and a second time with value information, and it
will be combined::
stmt = text("SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp")
stmt = stmt.bindparams(
bindparam('name', type_=String),
bindparam('timestamp', type_=DateTime)
)
stmt = stmt.bindparams(
name='jack',
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)
.. versionadded:: 0.9.0 The :meth:`.TextClause.bindparams` method supersedes
the argument ``bindparams`` passed to :func:`~.expression.text`.
"""
self._bindparams = new_params = self._bindparams.copy()
for bind in binds:
try:
existing = new_params[bind.key]
except KeyError:
raise exc.ArgumentError(
"This text() construct doesn't define a "
"bound parameter named %r" % bind.key)
else:
new_params[existing.key] = bind
for key, value in names_to_values.items():
try:
existing = new_params[key]
except KeyError:
raise exc.ArgumentError(
"This text() construct doesn't define a "
"bound parameter named %r" % key)
else:
new_params[key] = existing._with_value(value)
@util.dependencies('sqlalchemy.sql.selectable')
def columns(self, selectable, *cols, **types):
"""Turn this :class:`.TextClause` object into a :class:`.TextAsFrom`
object that can be embedded into another statement.
This function essentially bridges the gap between an entirely
textual SELECT statement and the SQL expression language concept
of a "selectable"::
from sqlalchemy.sql import column, text
stmt = text("SELECT id, name FROM some_table")
stmt = stmt.columns(column('id'), column('name')).alias('st')
stmt = select([mytable]).\\
select_from(
mytable.join(stmt, mytable.c.name == stmt.c.name)
).where(stmt.c.id > 5)
Above, we used untyped :func:`.column` elements. These can also have
types specified, which will impact how the column behaves in expressions
as well as determining result set behavior::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
column('id', Integer),
column('name', Unicode),
column('timestamp', DateTime)
)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
Keyword arguments allow just the names and types of columns to be specified,
where the :func:`.column` elements will be generated automatically::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
id=Integer,
name=Unicode,
timestamp=DateTime
)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
The :meth:`.TextClause.columns` method provides a direct
route to calling :meth:`.FromClause.alias` as well as :meth:`.SelectBase.cte`
against a textual SELECT statement::
stmt = stmt.columns(id=Integer, name=String).cte('st')
stmt = select([sometable]).where(sometable.c.id == stmt.c.id)
.. versionadded:: 0.9.0 :func:`.text` can now be converted into a fully
featured "selectable" construct using the :meth:`.TextClause.columns`
method. This method supersedes the ``typemap`` argument to
:func:`.text`.
"""
input_cols = [
ColumnClause(col.key, types.pop(col.key))
if col.key in types
else col
for col in cols
] + [ColumnClause(key, type_) for key, type_ in types.items()]
return selectable.TextAsFrom(self, input_cols)
@property
def type(self):
return type_api.NULLTYPE
@property
def comparator(self):
return self.type.comparator_factory(self)
def self_group(self, against=None):
if against is operators.in_op:
return Grouping(self)
else:
return self
def _copy_internals(self, clone=_clone, **kw):
self._bindparams = dict((b.key, clone(b, **kw))
for b in self._bindparams.values())
def get_children(self, **kwargs):
return list(self._bindparams.values())
class Null(ColumnElement):
"""Represent the NULL keyword in a SQL statement.
:class:`.Null` is accessed as a constant via the
:func:`.null` function.
"""
__visit_name__ = 'null'
@util.memoized_property
def type(self):
return type_api.NULLTYPE
@classmethod
def _singleton(cls):
"""Return a constant :class:`.Null` construct."""
return NULL
def compare(self, other):
return isinstance(other, Null)
class False_(ColumnElement):
"""Represent the ``false`` keyword, or equivalent, in a SQL statement.
:class:`.False_` is accessed as a constant via the
:func:`.false` function.
"""
__visit_name__ = 'false'
@util.memoized_property
def type(self):
return type_api.BOOLEANTYPE
def _negate(self):
return TRUE
@classmethod
def _singleton(cls):
"""Return a constant :class:`.False_` construct.
E.g.::
>>> from sqlalchemy import false
>>> print select([t.c.x]).where(false())
SELECT x FROM t WHERE false
A backend which does not support true/false constants will render as
an expression against 1 or 0::
>>> print select([t.c.x]).where(false())
SELECT x FROM t WHERE 0 = 1
The :func:`.true` and :func:`.false` constants also feature
"short circuit" operation within an :func:`.and_` or :func:`.or_`
conjunction::
>>> print select([t.c.x]).where(or_(t.c.x > 5, true()))
SELECT x FROM t WHERE true
>>> print select([t.c.x]).where(and_(t.c.x > 5, false()))
SELECT x FROM t WHERE false
.. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
better integrated behavior within conjunctions and on dialects
that don't support true/false constants.
.. seealso::
:func:`.true`
"""
return FALSE
def compare(self, other):
return isinstance(other, False_)
class True_(ColumnElement):
"""Represent the ``true`` keyword, or equivalent, in a SQL statement.
:class:`.True_` is accessed as a constant via the
:func:`.true` function.
"""
__visit_name__ = 'true'
@util.memoized_property
def type(self):
return type_api.BOOLEANTYPE
def _negate(self):
return FALSE
@classmethod
def _ifnone(cls, other):
if other is None:
return cls._singleton()
else:
return other
@classmethod
def _singleton(cls):
"""Return a constant :class:`.True_` construct.
E.g.::
>>> from sqlalchemy import true
>>> print select([t.c.x]).where(true())
SELECT x FROM t WHERE true
A backend which does not support true/false constants will render as
an expression against 1 or 0::
>>> print select([t.c.x]).where(true())
SELECT x FROM t WHERE 1 = 1
The :func:`.true` and :func:`.false` constants also feature
"short circuit" operation within an :func:`.and_` or :func:`.or_`
conjunction::
>>> print select([t.c.x]).where(or_(t.c.x > 5, true()))
SELECT x FROM t WHERE true
>>> print select([t.c.x]).where(and_(t.c.x > 5, false()))
SELECT x FROM t WHERE false
.. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
better integrated behavior within conjunctions and on dialects
that don't support true/false constants.
.. seealso::
:func:`.false`
"""
return TRUE
def compare(self, other):
return isinstance(other, True_)
NULL = Null()
FALSE = False_()
TRUE = True_()
class ClauseList(ClauseElement):
"""Describe a list of clauses, separated by an operator.
By default, is comma-separated, such as a column listing.
"""
__visit_name__ = 'clauselist'
def __init__(self, *clauses, **kwargs):
self.operator = kwargs.pop('operator', operators.comma_op)
self.group = kwargs.pop('group', True)
self.group_contents = kwargs.pop('group_contents', True)
if self.group_contents:
self.clauses = [
_literal_as_text(clause).self_group(against=self.operator)
for clause in clauses]
else:
self.clauses = [
_literal_as_text(clause)
for clause in clauses]
def __iter__(self):
return iter(self.clauses)
def __len__(self):
return len(self.clauses)
@property
def _select_iterable(self):
return iter(self)
def append(self, clause):
if self.group_contents:
self.clauses.append(_literal_as_text(clause).\
self_group(against=self.operator))
else:
self.clauses.append(_literal_as_text(clause))
def _copy_internals(self, clone=_clone, **kw):
self.clauses = [clone(clause, **kw) for clause in self.clauses]
def get_children(self, **kwargs):
return self.clauses
@property
def _from_objects(self):
return list(itertools.chain(*[c._from_objects for c in self.clauses]))
def self_group(self, against=None):
if self.group and operators.is_precedent(self.operator, against):
return Grouping(self)
else:
return self
def compare(self, other, **kw):
"""Compare this :class:`.ClauseList` to the given :class:`.ClauseList`,
including a comparison of all the clause items.
"""
if not isinstance(other, ClauseList) and len(self.clauses) == 1:
return self.clauses[0].compare(other, **kw)
elif isinstance(other, ClauseList) and \
len(self.clauses) == len(other.clauses):
for i in range(0, len(self.clauses)):
if not self.clauses[i].compare(other.clauses[i], **kw):
return False
else:
return self.operator == other.operator
else:
return False
class BooleanClauseList(ClauseList, ColumnElement):
__visit_name__ = 'clauselist'
def __init__(self, *arg, **kw):
raise NotImplementedError(
"BooleanClauseList has a private constructor")
@classmethod
def _construct(cls, operator, continue_on, skip_on, *clauses, **kw):
convert_clauses = []
clauses = util.coerce_generator_arg(clauses)
for clause in clauses:
clause = _literal_as_text(clause)
if isinstance(clause, continue_on):
continue
elif isinstance(clause, skip_on):
return clause.self_group(against=operators._asbool)
convert_clauses.append(clause)
if len(convert_clauses) == 1:
return convert_clauses[0].self_group(against=operators._asbool)
elif not convert_clauses and clauses:
return clauses[0].self_group(against=operators._asbool)
convert_clauses = [c.self_group(against=operator)
for c in convert_clauses]
self = cls.__new__(cls)
self.clauses = convert_clauses
self.group = True
self.operator = operator
self.group_contents = True
self.type = type_api.BOOLEANTYPE
return self
@classmethod
def and_(cls, *clauses):
"""Produce a conjunction of expressions joined by ``AND``.
E.g.::
from sqlalchemy import and_
stmt = select([users_table]).where(
and_(
users_table.c.name == 'wendy',
users_table.c.enrolled == True
)
)
The :func:`.and_` conjunction is also available using the
Python ``&`` operator (though note that compound expressions
need to be parenthesized in order to function with Python
operator precedence behavior)::
stmt = select([users_table]).where(
(users_table.c.name == 'wendy') &
(users_table.c.enrolled == True)
)
The :func:`.and_` operation is also implicit in some cases;
the :meth:`.Select.where` method for example can be invoked multiple
times against a statement, which will have the effect of each
clause being combined using :func:`.and_`::
stmt = select([users_table]).\\
where(users_table.c.name == 'wendy').\\
where(users_table.c.enrolled == True)
.. seealso::
:func:`.or_`
"""
return cls._construct(operators.and_, True_, False_, *clauses)
@classmethod
def or_(cls, *clauses):
"""Produce a conjunction of expressions joined by ``OR``.
E.g.::
from sqlalchemy import or_
stmt = select([users_table]).where(
or_(
users_table.c.name == 'wendy',
users_table.c.name == 'jack'
)
)
The :func:`.or_` conjunction is also available using the
Python ``|`` operator (though note that compound expressions
need to be parenthesized in order to function with Python
operator precedence behavior)::
stmt = select([users_table]).where(
(users_table.c.name == 'wendy') |
(users_table.c.name == 'jack')
)
.. seealso::
:func:`.and_`
"""
return cls._construct(operators.or_, False_, True_, *clauses)
@property
def _select_iterable(self):
return (self, )
def self_group(self, against=None):
if not self.clauses:
return self
else:
return super(BooleanClauseList, self).self_group(against=against)
def _negate(self):
return ClauseList._negate(self)
and_ = BooleanClauseList.and_
or_ = BooleanClauseList.or_
class Tuple(ClauseList, ColumnElement):
"""Represent a SQL tuple."""
def __init__(self, *clauses, **kw):
"""Return a :class:`.Tuple`.
Main usage is to produce a composite IN construct::
from sqlalchemy import tuple_
tuple_(table.c.col1, table.c.col2).in_(
[(1, 2), (5, 12), (10, 19)]
)
.. warning::
The composite IN construct is not supported by all backends,
and is currently known to work on Postgresql and MySQL,
but not SQLite. Unsupported backends will raise
a subclass of :class:`~sqlalchemy.exc.DBAPIError` when such
an expression is invoked.
"""
clauses = [_literal_as_binds(c) for c in clauses]
self._type_tuple = [arg.type for arg in clauses]
self.type = kw.pop('type_', self._type_tuple[0]
if self._type_tuple else type_api.NULLTYPE)
super(Tuple, self).__init__(*clauses, **kw)
@property
def _select_iterable(self):
return (self, )
def _bind_param(self, operator, obj):
return Tuple(*[
BindParameter(None, o, _compared_to_operator=operator,
_compared_to_type=type_, unique=True)
for o, type_ in zip(obj, self._type_tuple)
]).self_group()
class Case(ColumnElement):
"""Represent a ``CASE`` expression.
:class:`.Case` is produced using the :func:`.case` factory function,
as in::
from sqlalchemy import case
stmt = select([users_table]).\\
where(
case(
[
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J')
],
else_='E'
)
)
Details on :class:`.Case` usage is at :func:`.case`.
.. seealso::
:func:`.case`
"""
__visit_name__ = 'case'
def __init__(self, whens, value=None, else_=None):
"""Produce a ``CASE`` expression.
The ``CASE`` construct in SQL is a conditional object that
acts somewhat analogously to an "if/then" construct in other
languages. It returns an instance of :class:`.Case`.
:func:`.case` in its usual form is passed a list of "when"
contructs, that is, a list of conditions and results as tuples::
from sqlalchemy import case
stmt = select([users_table]).\\
where(
case(
[
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J')
],
else_='E'
)
)
The above statement will produce SQL resembling::
SELECT id, name FROM user
WHERE CASE
WHEN (name = :name_1) THEN :param_1
WHEN (name = :name_2) THEN :param_2
ELSE :param_3
END
When simple equality expressions of several values against a single
parent column are needed, :func:`.case` also has a "shorthand" format
used via the
:paramref:`.case.value` parameter, which is passed a column
expression to be compared. In this form, the :paramref:`.case.whens`
parameter is passed as a dictionary containing expressions to be compared
against keyed to result expressions. The statement below is equivalent
to the preceding statement::
stmt = select([users_table]).\\
where(
case(
{"wendy": "W", "jack": "J"},
value=users_table.c.name,
else_='E'
)
)
The values which are accepted as result values in
:paramref:`.case.whens` as well as with :paramref:`.case.else_` are
coerced from Python literals into :func:`.bindparam` constructs.
SQL expressions, e.g. :class:`.ColumnElement` constructs, are accepted
as well. To coerce a literal string expression into a constant
expression rendered inline, use the :func:`.literal_column` construct,
as in::
from sqlalchemy import case, literal_column
case(
[
(
orderline.c.qty > 100,
literal_column("'greaterthan100'")
),
(
orderline.c.qty > 10,
literal_column("'greaterthan10'")
)
],
else_=literal_column("'lessthan10'")
)
The above will render the given constants without using bound
parameters for the result values (but still for the comparison
values), as in::
CASE
WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
ELSE 'lessthan10'
END
:param whens: The criteria to be compared against, :paramref:`.case.whens`
accepts two different forms, based on whether or not :paramref:`.case.value`
is used.
In the first form, it accepts a list of 2-tuples; each 2-tuple consists
of ``(<sql expression>, <value>)``, where the SQL expression is a
boolean expression and "value" is a resulting value, e.g.::
case([
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J')
])
In the second form, it accepts a Python dictionary of comparison values
mapped to a resulting value; this form requires :paramref:`.case.value`
to be present, and values will be compared using the ``==`` operator,
e.g.::
case(
{"wendy": "W", "jack": "J"},
value=users_table.c.name
)
:param value: An optional SQL expression which will be used as a
fixed "comparison point" for candidate values within a dictionary
passed to :paramref:`.case.whens`.
:param else\_: An optional SQL expression which will be the evaluated
result of the ``CASE`` construct if all expressions within
:paramref:`.case.whens` evaluate to false. When omitted, most
databases will produce a result of NULL if none of the "when"
expressions evaulate to true.
"""
try:
whens = util.dictlike_iteritems(whens)
except TypeError:
pass
if value is not None:
whenlist = [
(_literal_as_binds(c).self_group(),
_literal_as_binds(r)) for (c, r) in whens
]
else:
whenlist = [
(_no_literals(c).self_group(),
_literal_as_binds(r)) for (c, r) in whens
]
if whenlist:
type_ = list(whenlist[-1])[-1].type
else:
type_ = None
if value is None:
self.value = None
else:
self.value = _literal_as_binds(value)
self.type = type_
self.whens = whenlist
if else_ is not None:
self.else_ = _literal_as_binds(else_)
else:
self.else_ = None
def _copy_internals(self, clone=_clone, **kw):
if self.value is not None:
self.value = clone(self.value, **kw)
self.whens = [(clone(x, **kw), clone(y, **kw))
for x, y in self.whens]
if self.else_ is not None:
self.else_ = clone(self.else_, **kw)
def get_children(self, **kwargs):
if self.value is not None:
yield self.value
for x, y in self.whens:
yield x
yield y
if self.else_ is not None:
yield self.else_
@property
def _from_objects(self):
return list(itertools.chain(*[x._from_objects for x in
self.get_children()]))
def literal_column(text, type_=None):
"""Return a textual column expression, as would be in the columns
clause of a ``SELECT`` statement.
The object returned supports further expressions in the same way as any
other column object, including comparison, math and string operations.
The type\_ parameter is important to determine proper expression behavior
(such as, '+' means string concatenation or numerical addition based on
the type).
:param text: the text of the expression; can be any SQL expression.
Quoting rules will not be applied. To specify a column-name expression
which should be subject to quoting rules, use the :func:`column`
function.
:param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
object which will
provide result-set translation and additional expression semantics for
this column. If left as None the type will be NullType.
"""
return ColumnClause(text, type_=type_, is_literal=True)
class Cast(ColumnElement):
"""Represent a ``CAST`` expression.
:class:`.Cast` is produced using the :func:`.cast` factory function,
as in::
from sqlalchemy import cast, Numeric
stmt = select([
cast(product_table.c.unit_price, Numeric(10, 4))
])
Details on :class:`.Cast` usage is at :func:`.cast`.
.. seealso::
:func:`.cast`
"""
__visit_name__ = 'cast'
def __init__(self, expression, type_):
"""Produce a ``CAST`` expression.
:func:`.cast` returns an instance of :class:`.Cast`.
E.g.::
from sqlalchemy import cast, Numeric
stmt = select([
cast(product_table.c.unit_price, Numeric(10, 4))
])
The above statement will produce SQL resembling::
SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
The :func:`.cast` function performs two distinct functions when
used. The first is that it renders the ``CAST`` expression within
the resulting SQL string. The second is that it associates the given
type (e.g. :class:`.TypeEngine` class or instance) with the column
expression on the Python side, which means the expression will take
on the expression operator behavior associated with that type,
as well as the bound-value handling and result-row-handling behavior
of the type.
.. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
to the expression such that it takes effect on the bound-value,
e.g. the Python-to-database direction, in addition to the
result handling, e.g. database-to-Python, direction.
An alternative to :func:`.cast` is the :func:`.type_coerce` function.
This function performs the second task of associating an expression
with a specific type, but does not render the ``CAST`` expression
in SQL.
:param expression: A SQL expression, such as a :class:`.ColumnElement`
expression or a Python string which will be coerced into a bound
literal value.
:param type_: A :class:`.TypeEngine` class or instance indicating
the type to which the ``CAST`` should apply.
.. seealso::
:func:`.type_coerce` - Python-side type coercion without emitting
CAST.
"""
self.type = type_api.to_instance(type_)
self.clause = _literal_as_binds(expression, type_=self.type)
self.typeclause = TypeClause(self.type)
def _copy_internals(self, clone=_clone, **kw):
self.clause = clone(self.clause, **kw)
self.typeclause = clone(self.typeclause, **kw)
def get_children(self, **kwargs):
return self.clause, self.typeclause
@property
def _from_objects(self):
return self.clause._from_objects
class Extract(ColumnElement):
"""Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""
__visit_name__ = 'extract'
def __init__(self, field, expr, **kwargs):
"""Return a :class:`.Extract` construct.
This is typically available as :func:`.extract`
as well as ``func.extract`` from the
:data:`.func` namespace.
"""
self.type = type_api.INTEGERTYPE
self.field = field
self.expr = _literal_as_binds(expr, None)
def _copy_internals(self, clone=_clone, **kw):
self.expr = clone(self.expr, **kw)
def get_children(self, **kwargs):
return self.expr,
@property
def _from_objects(self):
return self.expr._from_objects
class UnaryExpression(ColumnElement):
"""Define a 'unary' expression.
A unary expression has a single column expression
and an operator. The operator can be placed on the left
(where it is called the 'operator') or right (where it is called the
'modifier') of the column expression.
:class:`.UnaryExpression` is the basis for several unary operators
including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`,
:func:`.nullsfirst` and :func:`.nullslast`.
"""
__visit_name__ = 'unary'
def __init__(self, element, operator=None, modifier=None,
type_=None, negate=None):
self.operator = operator
self.modifier = modifier
self.element = element.self_group(against=self.operator or self.modifier)
self.type = type_api.to_instance(type_)
self.negate = negate
@classmethod
def _create_nullsfirst(cls, column):
"""Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression.
:func:`.nullsfirst` is intended to modify the expression produced
by :func:`.asc` or :func:`.desc`, and indicates how NULL values
should be handled when they are encountered during ordering::
from sqlalchemy import desc, nullsfirst
stmt = select([users_table]).\\
order_by(nullsfirst(desc(users_table.c.name)))
The SQL expression from the above would resemble::
SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
Like :func:`.asc` and :func:`.desc`, :func:`.nullsfirst` is typically
invoked from the column expression itself using :meth:`.ColumnElement.nullsfirst`,
rather than as its standalone function version, as in::
stmt = select([users_table]).\\
order_by(users_table.c.name.desc().nullsfirst())
.. seealso::
:func:`.asc`
:func:`.desc`
:func:`.nullslast`
:meth:`.Select.order_by`
"""
return UnaryExpression(
_literal_as_text(column), modifier=operators.nullsfirst_op)
@classmethod
def _create_nullslast(cls, column):
"""Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression.
:func:`.nullslast` is intended to modify the expression produced
by :func:`.asc` or :func:`.desc`, and indicates how NULL values
should be handled when they are encountered during ordering::
from sqlalchemy import desc, nullslast
stmt = select([users_table]).\\
order_by(nullslast(desc(users_table.c.name)))
The SQL expression from the above would resemble::
SELECT id, name FROM user ORDER BY name DESC NULLS LAST
Like :func:`.asc` and :func:`.desc`, :func:`.nullslast` is typically
invoked from the column expression itself using :meth:`.ColumnElement.nullslast`,
rather than as its standalone function version, as in::
stmt = select([users_table]).\\
order_by(users_table.c.name.desc().nullslast())
.. seealso::
:func:`.asc`
:func:`.desc`
:func:`.nullsfirst`
:meth:`.Select.order_by`
"""
return UnaryExpression(
_literal_as_text(column), modifier=operators.nullslast_op)
@classmethod
def _create_desc(cls, column):
"""Produce a descending ``ORDER BY`` clause element.
e.g.::
from sqlalchemy import desc
stmt = select([users_table]).order_by(desc(users_table.c.name))
will produce SQL as::
SELECT id, name FROM user ORDER BY name DESC
The :func:`.desc` function is a standalone version of the
:meth:`.ColumnElement.desc` method available on all SQL expressions,
e.g.::
stmt = select([users_table]).order_by(users_table.c.name.desc())
:param column: A :class:`.ColumnElement` (e.g. scalar SQL expression)
with which to apply the :func:`.desc` operation.
.. seealso::
:func:`.asc`
:func:`.nullsfirst`
:func:`.nullslast`
:meth:`.Select.order_by`
"""
return UnaryExpression(
_literal_as_text(column), modifier=operators.desc_op)
@classmethod
def _create_asc(cls, column):
"""Produce an ascending ``ORDER BY`` clause element.
e.g.::
from sqlalchemy import asc
stmt = select([users_table]).order_by(asc(users_table.c.name))
will produce SQL as::
SELECT id, name FROM user ORDER BY name ASC
The :func:`.asc` function is a standalone version of the
:meth:`.ColumnElement.asc` method available on all SQL expressions,
e.g.::
stmt = select([users_table]).order_by(users_table.c.name.asc())
:param column: A :class:`.ColumnElement` (e.g. scalar SQL expression)
with which to apply the :func:`.asc` operation.
.. seealso::
:func:`.desc`
:func:`.nullsfirst`
:func:`.nullslast`
:meth:`.Select.order_by`
"""
return UnaryExpression(
_literal_as_text(column), modifier=operators.asc_op)
@classmethod
def _create_distinct(cls, expr):
"""Produce an column-expression-level unary ``DISTINCT`` clause.
This applies the ``DISTINCT`` keyword to an individual column
expression, and is typically contained within an aggregate function,
as in::
from sqlalchemy import distinct, func
stmt = select([func.count(distinct(users_table.c.name))])
The above would produce an expression resembling::
SELECT COUNT(DISTINCT name) FROM user
The :func:`.distinct` function is also available as a column-level
method, e.g. :meth:`.ColumnElement.distinct`, as in::
stmt = select([func.count(users_table.c.name.distinct())])
The :func:`.distinct` operator is different from the
:meth:`.Select.distinct` method of :class:`.Select`,
which produces a ``SELECT`` statement
with ``DISTINCT`` applied to the result set as a whole,
e.g. a ``SELECT DISTINCT`` expression. See that method for further
information.
.. seealso::
:meth:`.ColumnElement.distinct`
:meth:`.Select.distinct`
:data:`.func`
"""
expr = _literal_as_binds(expr)
return UnaryExpression(expr,
operator=operators.distinct_op, type_=expr.type)
@util.memoized_property
def _order_by_label_element(self):
if self.modifier in (operators.desc_op, operators.asc_op):
return self.element._order_by_label_element
else:
return None
@property
def _from_objects(self):
return self.element._from_objects
def _copy_internals(self, clone=_clone, **kw):
self.element = clone(self.element, **kw)
def get_children(self, **kwargs):
return self.element,
def compare(self, other, **kw):
"""Compare this :class:`UnaryExpression` against the given
:class:`.ClauseElement`."""
return (
isinstance(other, UnaryExpression) and
self.operator == other.operator and
self.modifier == other.modifier and
self.element.compare(other.element, **kw)
)
def _negate(self):
if self.negate is not None:
return UnaryExpression(
self.element,
operator=self.negate,
negate=self.operator,
modifier=self.modifier,
type_=self.type)
else:
return ClauseElement._negate(self)
def self_group(self, against=None):
if self.operator and operators.is_precedent(self.operator, against):
return Grouping(self)
else:
return self
class AsBoolean(UnaryExpression):
def __init__(self, element, operator, negate):
self.element = element
self.type = type_api.BOOLEANTYPE
self.operator = operator
self.negate = negate
self.modifier = None
def self_group(self, against=None):
return self
def _negate(self):
return self.element._negate()
class BinaryExpression(ColumnElement):
"""Represent an expression that is ``LEFT <operator> RIGHT``.
A :class:`.BinaryExpression` is generated automatically
whenever two column expressions are used in a Python binary expresion::
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print column('a') + column('b')
a + b
"""
__visit_name__ = 'binary'
def __init__(self, left, right, operator, type_=None,
negate=None, modifiers=None):
# allow compatibility with libraries that
# refer to BinaryExpression directly and pass strings
if isinstance(operator, util.string_types):
operator = operators.custom_op(operator)
self._orig = (left, right)
self.left = left.self_group(against=operator)
self.right = right.self_group(against=operator)
self.operator = operator
self.type = type_api.to_instance(type_)
self.negate = negate
if modifiers is None:
self.modifiers = {}
else:
self.modifiers = modifiers
def __bool__(self):
if self.operator in (operator.eq, operator.ne):
return self.operator(hash(self._orig[0]), hash(self._orig[1]))
else:
raise TypeError("Boolean value of this clause is not defined")
__nonzero__ = __bool__
@property
def is_comparison(self):
return operators.is_comparison(self.operator)
@property
def _from_objects(self):
return self.left._from_objects + self.right._from_objects
def _copy_internals(self, clone=_clone, **kw):
self.left = clone(self.left, **kw)
self.right = clone(self.right, **kw)
def get_children(self, **kwargs):
return self.left, self.right
def compare(self, other, **kw):
"""Compare this :class:`BinaryExpression` against the
given :class:`BinaryExpression`."""
return (
isinstance(other, BinaryExpression) and
self.operator == other.operator and
(
self.left.compare(other.left, **kw) and
self.right.compare(other.right, **kw) or
(
operators.is_commutative(self.operator) and
self.left.compare(other.right, **kw) and
self.right.compare(other.left, **kw)
)
)
)
def self_group(self, against=None):
if operators.is_precedent(self.operator, against):
return Grouping(self)
else:
return self
def _negate(self):
if self.negate is not None:
return BinaryExpression(
self.left,
self.right,
self.negate,
negate=self.operator,
type_=type_api.BOOLEANTYPE,
modifiers=self.modifiers)
else:
return super(BinaryExpression, self)._negate()
class Grouping(ColumnElement):
"""Represent a grouping within a column expression"""
__visit_name__ = 'grouping'
def __init__(self, element):
self.element = element
self.type = getattr(element, 'type', type_api.NULLTYPE)
def self_group(self, against=None):
return self
@property
def _label(self):
return getattr(self.element, '_label', None) or self.anon_label
def _copy_internals(self, clone=_clone, **kw):
self.element = clone(self.element, **kw)
def get_children(self, **kwargs):
return self.element,
@property
def _from_objects(self):
return self.element._from_objects
def __getattr__(self, attr):
return getattr(self.element, attr)
def __getstate__(self):
return {'element': self.element, 'type': self.type}
def __setstate__(self, state):
self.element = state['element']
self.type = state['type']
def compare(self, other, **kw):
return isinstance(other, Grouping) and \
self.element.compare(other.element)
class Over(ColumnElement):
"""Represent an OVER clause.
This is a special operator against a so-called
"window" function, as well as any aggregate function,
which produces results relative to the result set
itself. It's supported only by certain database
backends.
"""
__visit_name__ = 'over'
order_by = None
partition_by = None
def __init__(self, func, partition_by=None, order_by=None):
"""Produce an :class:`.Over` object against a function.
Used against aggregate or so-called "window" functions,
for database backends that support window functions.
E.g.::
from sqlalchemy import over
over(func.row_number(), order_by='x')
Would produce "ROW_NUMBER() OVER(ORDER BY x)".
:param func: a :class:`.FunctionElement` construct, typically
generated by :data:`~.expression.func`.
:param partition_by: a column element or string, or a list
of such, that will be used as the PARTITION BY clause
of the OVER construct.
:param order_by: a column element or string, or a list
of such, that will be used as the ORDER BY clause
of the OVER construct.
This function is also available from the :data:`~.expression.func`
construct itself via the :meth:`.FunctionElement.over` method.
.. versionadded:: 0.7
"""
self.func = func
if order_by is not None:
self.order_by = ClauseList(*util.to_list(order_by))
if partition_by is not None:
self.partition_by = ClauseList(*util.to_list(partition_by))
@util.memoized_property
def type(self):
return self.func.type
def get_children(self, **kwargs):
return [c for c in
(self.func, self.partition_by, self.order_by)
if c is not None]
def _copy_internals(self, clone=_clone, **kw):
self.func = clone(self.func, **kw)
if self.partition_by is not None:
self.partition_by = clone(self.partition_by, **kw)
if self.order_by is not None:
self.order_by = clone(self.order_by, **kw)
@property
def _from_objects(self):
return list(itertools.chain(
*[c._from_objects for c in
(self.func, self.partition_by, self.order_by)
if c is not None]
))
class Label(ColumnElement):
"""Represents a column label (AS).
Represent a label, as typically applied to any column-level
element using the ``AS`` sql keyword.
"""
__visit_name__ = 'label'
def __init__(self, name, element, type_=None):
"""Return a :class:`Label` object for the
given :class:`.ColumnElement`.
A label changes the name of an element in the columns clause of a
``SELECT`` statement, typically via the ``AS`` SQL keyword.
This functionality is more conveniently available via the
:meth:`.ColumnElement.label` method on :class:`.ColumnElement`.
:param name: label name
:param obj: a :class:`.ColumnElement`.
"""
while isinstance(element, Label):
element = element.element
if name:
self.name = name
else:
self.name = _anonymous_label('%%(%d %s)s' % (id(self),
getattr(element, 'name', 'anon')))
self.key = self._label = self._key_label = self.name
self._element = element
self._type = type_
self._proxies = [element]
def __reduce__(self):
return self.__class__, (self.name, self._element, self._type)
@util.memoized_property
def _order_by_label_element(self):
return self
@util.memoized_property
def type(self):
return type_api.to_instance(
self._type or getattr(self._element, 'type', None)
)
@util.memoized_property
def element(self):
return self._element.self_group(against=operators.as_)
def self_group(self, against=None):
sub_element = self._element.self_group(against=against)
if sub_element is not self._element:
return Label(self.name,
sub_element,
type_=self._type)
else:
return self
@property
def primary_key(self):
return self.element.primary_key
@property
def foreign_keys(self):
return self.element.foreign_keys
def get_children(self, **kwargs):
return self.element,
def _copy_internals(self, clone=_clone, **kw):
self.element = clone(self.element, **kw)
@property
def _from_objects(self):
return self.element._from_objects
def _make_proxy(self, selectable, name=None, **kw):
e = self.element._make_proxy(selectable,
name=name if name else self.name)
e._proxies.append(self)
if self._type is not None:
e.type = self._type
return e
class ColumnClause(Immutable, ColumnElement):
"""Represents a column expression from any textual string.
The :class:`.ColumnClause`, a lightweight analogue to the
:class:`.Column` class, is typically invoked using the
:func:`.column` function, as in::
from sqlalchemy.sql import column
id, name = column("id"), column("name")
stmt = select([id, name]).select_from("user")
The above statement would produce SQL like::
SELECT id, name FROM user
:class:`.ColumnClause` is the immediate superclass of the schema-specific
:class:`.Column` object. While the :class:`.Column` class has all the
same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause`
class is usable by itself in those cases where behavioral requirements
are limited to simple SQL expression generation. The object has none of the
associations with schema-level metadata or with execution-time behavior
that :class:`.Column` does, so in that sense is a "lightweight" version
of :class:`.Column`.
Full details on :class:`.ColumnClause` usage is at :func:`.column`.
.. seealso::
:func:`.column`
:class:`.Column`
"""
__visit_name__ = 'column'
onupdate = default = server_default = server_onupdate = None
_memoized_property = util.group_expirable_memoized_property()
def __init__(self, text, type_=None, is_literal=False, _selectable=None):
"""Produce a :class:`.ColumnClause` object.
The :class:`.ColumnClause` is a lightweight analogue to the
:class:`.Column` class. The :func:`.column` function can
be invoked with just a name alone, as in::
from sqlalchemy.sql import column
id, name = column("id"), column("name")
stmt = select([id, name]).select_from("user")
The above statement would produce SQL like::
SELECT id, name FROM user
Once constructed, :func:`.column` may be used like any other SQL expression
element such as within :func:`.select` constructs::
from sqlalchemy.sql import column
id, name = column("id"), column("name")
stmt = select([id, name]).select_from("user")
The text handled by :func:`.column` is assumed to be handled
like the name of a database column; if the string contains mixed case,
special characters, or matches a known reserved word on the target
backend, the column expression will render using the quoting
behavior determined by the backend. To produce a textual SQL
expression that is rendered exactly without any quoting,
use :func:`.literal_column` instead, or pass ``True`` as the
value of :paramref:`.column.is_literal`. Additionally, full SQL
statements are best handled using the :func:`.text` construct.
:func:`.column` can be used in a table-like
fashion by combining it with the :func:`.table` function
(which is the lightweight analogue to :class:`.Table`) to produce
a working table construct with minimal boilerplate::
from sqlalchemy.sql import table, column
user = table("user",
column("id"),
column("name"),
column("description"),
)
stmt = select([user.c.description]).where(user.c.name == 'wendy')
A :func:`.column` / :func:`.table` construct like that illustrated
above can be created in an
ad-hoc fashion and is not associated with any :class:`.schema.MetaData`,
DDL, or events, unlike its :class:`.Table` counterpart.
:param text: the text of the element.
:param type: :class:`.types.TypeEngine` object which can associate
this :class:`.ColumnClause` with a type.
:param is_literal: if True, the :class:`.ColumnClause` is assumed to
be an exact expression that will be delivered to the output with no
quoting rules applied regardless of case sensitive settings. the
:func:`.literal_column()` function essentially invokes :func:`.column`
while passing ``is_literal=True``.
.. seealso::
:class:`.Column`
:func:`.literal_column`
:func:`.text`
:ref:`metadata_toplevel`
"""
self.key = self.name = text
self.table = _selectable
self.type = type_api.to_instance(type_)
self.is_literal = is_literal
def _compare_name_for_result(self, other):
if self.is_literal or \
self.table is None or self.table._textual or \
not hasattr(other, 'proxy_set') or (
isinstance(other, ColumnClause) and
(other.is_literal or
other.table is None or
other.table._textual)
):
return (hasattr(other, 'name') and self.name == other.name) or \
(hasattr(other, '_label') and self._label == other._label)
else:
return other.proxy_set.intersection(self.proxy_set)
def _get_table(self):
return self.__dict__['table']
def _set_table(self, table):
self._memoized_property.expire_instance(self)
self.__dict__['table'] = table
table = property(_get_table, _set_table)
@_memoized_property
def _from_objects(self):
t = self.table
if t is not None:
return [t]
else:
return []
@util.memoized_property
def description(self):
if util.py3k:
return self.name
else:
return self.name.encode('ascii', 'backslashreplace')
@_memoized_property
def _key_label(self):
if self.key != self.name:
return self._gen_label(self.key)
else:
return self._label
@_memoized_property
def _label(self):
return self._gen_label(self.name)
def _gen_label(self, name):
t = self.table
if self.is_literal:
return None
elif t is not None and t.named_with_column:
if getattr(t, 'schema', None):
label = t.schema.replace('.', '_') + "_" + \
t.name + "_" + name
else:
label = t.name + "_" + name
# propagate name quoting rules for labels.
if getattr(name, "quote", None) is not None:
if isinstance(label, quoted_name):
label.quote = name.quote
else:
label = quoted_name(label, name.quote)
elif getattr(t.name, "quote", None) is not None:
# can't get this situation to occur, so let's
# assert false on it for now
assert not isinstance(label, quoted_name)
label = quoted_name(label, t.name.quote)
# ensure the label name doesn't conflict with that
# of an existing column
if label in t.c:
_label = label
counter = 1
while _label in t.c:
_label = label + "_" + str(counter)
counter += 1
label = _label
return _as_truncated(label)
else:
return name
def _bind_param(self, operator, obj):
return BindParameter(self.name, obj,
_compared_to_operator=operator,
_compared_to_type=self.type,
unique=True)
def _make_proxy(self, selectable, name=None, attach=True,
name_is_truncatable=False, **kw):
# propagate the "is_literal" flag only if we are keeping our name,
# otherwise its considered to be a label
is_literal = self.is_literal and (name is None or name == self.name)
c = self._constructor(
_as_truncated(name or self.name) if \
name_is_truncatable else \
(name or self.name),
type_=self.type,
_selectable=selectable,
is_literal=is_literal
)
if name is None:
c.key = self.key
c._proxies = [self]
if selectable._is_clone_of is not None:
c._is_clone_of = \
selectable._is_clone_of.columns.get(c.key)
if attach:
selectable._columns[c.key] = c
return c
class _IdentifiedClause(Executable, ClauseElement):
__visit_name__ = 'identified'
_execution_options = \
Executable._execution_options.union({'autocommit': False})
def __init__(self, ident):
self.ident = ident
class SavepointClause(_IdentifiedClause):
__visit_name__ = 'savepoint'
class RollbackToSavepointClause(_IdentifiedClause):
__visit_name__ = 'rollback_to_savepoint'
class ReleaseSavepointClause(_IdentifiedClause):
__visit_name__ = 'release_savepoint'
class quoted_name(util.text_type):
"""Represent a SQL identifier combined with quoting preferences.
:class:`.quoted_name` is a Python unicode/str subclass which
represents a particular identifier name along with a
``quote`` flag. This ``quote`` flag, when set to
``True`` or ``False``, overrides automatic quoting behavior
for this identifier in order to either unconditionally quote
or to not quote the name. If left at its default of ``None``,
quoting behavior is applied to the identifier on a per-backend basis
based on an examination of the token itself.
A :class:`.quoted_name` object with ``quote=True`` is also
prevented from being modified in the case of a so-called
"name normalize" option. Certain database backends, such as
Oracle, Firebird, and DB2 "normalize" case-insensitive names
as uppercase. The SQLAlchemy dialects for these backends
convert from SQLAlchemy's lower-case-means-insensitive convention
to the upper-case-means-insensitive conventions of those backends.
The ``quote=True`` flag here will prevent this conversion from occurring
to support an identifier that's quoted as all lower case against
such a backend.
The :class:`.quoted_name` object is normally created automatically
when specifying the name for key schema constructs such as :class:`.Table`,
:class:`.Column`, and others. The class can also be passed explicitly
as the name to any function that receives a name which can be quoted.
Such as to use the :meth:`.Engine.has_table` method with an unconditionally
quoted name::
from sqlaclchemy import create_engine
from sqlalchemy.sql.elements import quoted_name
engine = create_engine("oracle+cx_oracle://some_dsn")
engine.has_table(quoted_name("some_table", True))
The above logic will run the "has table" logic against the Oracle backend,
passing the name exactly as ``"some_table"`` without converting to
upper case.
.. versionadded:: 0.9.0
"""
def __new__(cls, value, quote):
if value is None:
return None
# experimental - don't bother with quoted_name
# if quote flag is None. doesn't seem to make any dent
# in performance however
# elif not sprcls and quote is None:
# return value
elif isinstance(value, cls) and (
quote is None or value.quote == quote
):
return value
self = super(quoted_name, cls).__new__(cls, value)
self.quote = quote
return self
def __reduce__(self):
return quoted_name, (util.text_type(self), self.quote)
@util.memoized_instancemethod
def lower(self):
if self.quote:
return self
else:
return util.text_type(self).lower()
@util.memoized_instancemethod
def upper(self):
if self.quote:
return self
else:
return util.text_type(self).upper()
def __repr__(self):
backslashed = self.encode('ascii', 'backslashreplace')
if not util.py2k:
backslashed = backslashed.decode('ascii')
return "'%s'" % backslashed
class _truncated_label(quoted_name):
"""A unicode subclass used to identify symbolic "
"names that may require truncation."""
def __new__(cls, value, quote=None):
quote = getattr(value, "quote", quote)
#return super(_truncated_label, cls).__new__(cls, value, quote, True)
return super(_truncated_label, cls).__new__(cls, value, quote)
def __reduce__(self):
return self.__class__, (util.text_type(self), self.quote)
def apply_map(self, map_):
return self
# for backwards compatibility in case
# someone is re-implementing the
# _truncated_identifier() sequence in a custom
# compiler
_generated_label = _truncated_label
class _anonymous_label(_truncated_label):
"""A unicode subclass used to identify anonymously
generated names."""
def __add__(self, other):
return _anonymous_label(
quoted_name(
util.text_type.__add__(self, util.text_type(other)),
self.quote)
)
def __radd__(self, other):
return _anonymous_label(
quoted_name(
util.text_type.__add__(util.text_type(other), self),
self.quote)
)
def apply_map(self, map_):
if self.quote is not None:
# preserve quoting only if necessary
return quoted_name(self % map_, self.quote)
else:
# else skip the constructor call
return self % map_
def _as_truncated(value):
"""coerce the given value to :class:`._truncated_label`.
Existing :class:`._truncated_label` and
:class:`._anonymous_label` objects are passed
unchanged.
"""
if isinstance(value, _truncated_label):
return value
else:
return _truncated_label(value)
def _string_or_unprintable(element):
if isinstance(element, util.string_types):
return element
else:
try:
return str(element)
except:
return "unprintable element %r" % element
def _expand_cloned(elements):
"""expand the given set of ClauseElements to be the set of all 'cloned'
predecessors.
"""
return itertools.chain(*[x._cloned_set for x in elements])
def _select_iterables(elements):
"""expand tables into individual columns in the
given list of column expressions.
"""
return itertools.chain(*[c._select_iterable for c in elements])
def _cloned_intersection(a, b):
"""return the intersection of sets a and b, counting
any overlap between 'cloned' predecessors.
The returned set is in terms of the entities present within 'a'.
"""
all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
return set(elem for elem in a
if all_overlap.intersection(elem._cloned_set))
def _cloned_difference(a, b):
all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
return set(elem for elem in a
if not all_overlap.intersection(elem._cloned_set))
def _labeled(element):
if not hasattr(element, 'name'):
return element.label(None)
else:
return element
def _is_column(col):
"""True if ``col`` is an instance of :class:`.ColumnElement`."""
return isinstance(col, ColumnElement)
def _find_columns(clause):
"""locate Column objects within the given expression."""
cols = util.column_set()
traverse(clause, {}, {'column': cols.add})
return cols
# there is some inconsistency here between the usage of
# inspect() vs. checking for Visitable and __clause_element__.
# Ideally all functions here would derive from inspect(),
# however the inspect() versions add significant callcount
# overhead for critical functions like _interpret_as_column_or_from().
# Generally, the column-based functions are more performance critical
# and are fine just checking for __clause_element__(). it's only
# _interpret_as_from() where we'd like to be able to receive ORM entities
# that have no defined namespace, hence inspect() is needed there.
def _column_as_key(element):
if isinstance(element, util.string_types):
return element
if hasattr(element, '__clause_element__'):
element = element.__clause_element__()
try:
return element.key
except AttributeError:
return None
def _clause_element_as_expr(element):
if hasattr(element, '__clause_element__'):
return element.__clause_element__()
else:
return element
def _literal_as_text(element):
if isinstance(element, Visitable):
return element
elif hasattr(element, '__clause_element__'):
return element.__clause_element__()
elif isinstance(element, util.string_types):
return TextClause(util.text_type(element))
elif isinstance(element, (util.NoneType, bool)):
return _const_expr(element)
else:
raise exc.ArgumentError(
"SQL expression object or string expected."
)
def _no_literals(element):
if hasattr(element, '__clause_element__'):
return element.__clause_element__()
elif not isinstance(element, Visitable):
raise exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' "
"function to indicate a SQL expression "
"literal, or 'literal()' to indicate a "
"bound value." % element)
else:
return element
def _is_literal(element):
return not isinstance(element, Visitable) and \
not hasattr(element, '__clause_element__')
def _only_column_elements_or_none(element, name):
if element is None:
return None
else:
return _only_column_elements(element, name)
def _only_column_elements(element, name):
if hasattr(element, '__clause_element__'):
element = element.__clause_element__()
if not isinstance(element, ColumnElement):
raise exc.ArgumentError(
"Column-based expression object expected for argument "
"'%s'; got: '%s', type %s" % (name, element, type(element)))
return element
def _literal_as_binds(element, name=None, type_=None):
if hasattr(element, '__clause_element__'):
return element.__clause_element__()
elif not isinstance(element, Visitable):
if element is None:
return Null()
else:
return BindParameter(name, element, type_=type_, unique=True)
else:
return element
def _interpret_as_column_or_from(element):
if isinstance(element, Visitable):
return element
elif hasattr(element, '__clause_element__'):
return element.__clause_element__()
insp = inspection.inspect(element, raiseerr=False)
if insp is None:
if isinstance(element, (util.NoneType, bool)):
return _const_expr(element)
elif hasattr(insp, "selectable"):
return insp.selectable
return ColumnClause(str(element), is_literal=True)
def _const_expr(element):
if isinstance(element, (Null, False_, True_)):
return element
elif element is None:
return Null()
elif element is False:
return False_()
elif element is True:
return True_()
else:
raise exc.ArgumentError(
"Expected None, False, or True"
)
def _type_from_args(args):
for a in args:
if not a.type._isnull:
return a.type
else:
return type_api.NULLTYPE
def _corresponding_column_or_error(fromclause, column,
require_embedded=False):
c = fromclause.corresponding_column(column,
require_embedded=require_embedded)
if c is None:
raise exc.InvalidRequestError(
"Given column '%s', attached to table '%s', "
"failed to locate a corresponding column from table '%s'"
%
(column,
getattr(column, 'table', None),
fromclause.description)
)
return c
class AnnotatedColumnElement(Annotated):
def __init__(self, element, values):
Annotated.__init__(self, element, values)
ColumnElement.comparator._reset(self)
for attr in ('name', 'key', 'table'):
if self.__dict__.get(attr, False) is None:
self.__dict__.pop(attr)
def _with_annotations(self, values):
clone = super(AnnotatedColumnElement, self)._with_annotations(values)
ColumnElement.comparator._reset(clone)
return clone
@util.memoized_property
def name(self):
"""pull 'name' from parent, if not present"""
return self._Annotated__element.name
@util.memoized_property
def table(self):
"""pull 'table' from parent, if not present"""
return self._Annotated__element.table
@util.memoized_property
def key(self):
"""pull 'key' from parent, if not present"""
return self._Annotated__element.key
@util.memoized_property
def info(self):
return self._Annotated__element.info
| gpl-3.0 |
icoxfog417/music_hack_day_onpasha | scripts/create_photo_to_mood_data.py | 1 | 2393 | import os
from datetime import datetime
from api.bluemix_vision_recognition import VisionRecognizer
from api.echonest import Echonest
def read_file(path):
lines = []
with open(path, "r", encoding="utf-8") as f:
lines = f.readlines()
lines = [ln.strip(os.linesep) for ln in lines]
return lines
def write_file(path, rows, separator="\t"):
with open(path, "wb") as outfile:
for row in rows:
line = ""
if isinstance(row, list) or isinstance(row, tuple):
line = separator.join(row) + os.linesep
else:
line = row + os.linesep
outfile.write(line.encode("utf-8"))
def rekognize(image_url):
vr = VisionRecognizer()
result = vr.recognize(image_url)
tag_and_score = {}
if "images" in result:
labels = result["images"][0]["labels"]
for lb in labels:
tag_and_score[lb["label_name"]] = lb["label_score"]
return tag_and_score
def rekognize_all(line):
tags = []
data = []
for i, ln in enumerate(line):
mood = ln[0]
url = ln[1]
try:
r = rekognize(url)
for k in r:
if k not in tags:
tags.append(k)
data.append((mood, url, r))
print("{0} success.".format(i))
except Exception as ex:
print("{0}: {1}".format(i, ex))
tags.sort()
header = ["mood", "url"] + tags
lines = [header]
for d in data:
mood, url, tag_scores = d
mood_index = -1 if mood not in Echonest.MOOD else Echonest.MOOD.index(mood)
ln = [str(mood_index), url]
for t in tags:
if t in tag_scores:
ln.append(str(tag_scores[t]))
else:
ln.append(str(0))
lines.append(ln)
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
path = os.path.join(os.path.dirname(__file__), "../data/photo_to_mood_{0}.txt".format(timestamp))
write_file(path, lines)
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
path = os.path.join(os.path.dirname(__file__), sys.argv[1])
input_file = read_file(path)
inputs = []
for ln in input_file:
inputs.append(ln.split("\t")[:2])
rekognize_all(inputs)
else:
print("you have to set mood/image_url file.")
| mit |
scue/vim-ycm_win7 | third_party/pythonfutures/setup.py | 65 | 1249 | #!/usr/bin/env python
import sys
extras = {}
try:
from setuptools import setup
extras['zip_safe'] = False
if sys.version_info < (2, 6):
extras['install_requires'] = ['multiprocessing']
except ImportError:
from distutils.core import setup
setup(name='futures',
version='2.1.4',
description='Backport of the concurrent.futures package from Python 3.2',
author='Brian Quinlan',
author_email='brian@sweetapp.com',
maintainer='Alex Gronholm',
maintainer_email='alex.gronholm+pypi@nextday.fi',
url='http://code.google.com/p/pythonfutures',
download_url='http://pypi.python.org/pypi/futures/',
packages=['futures', 'concurrent', 'concurrent.futures'],
license='BSD',
classifiers=['License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1'],
**extras
)
| gpl-3.0 |
Noilednad/BonjourBrowser | mDNSShared/src/main/jni/mDNSPosix/parselog.py | 10 | 10080 | #!/usr/bin/python
# Emacs settings: -*- tab-width: 4 -*-
#
# Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# parselog.py, written and contributed by Kevin Marks
#
# Requires OS X 10.3 Panther or later, for Python and Core Graphics Python APIs
# Invoke from the command line with "parselog.py fname" where fname is a log file made by mDNSNetMonitor
#
# Caveats:
# It expects plain ASCII, and doesn't handle spaces in record names very well right now
# There's a procedure you can follow to 'sanitize' an mDNSNetMonitor log file to make it more paletable to parselog.py:
# 1. Run mDNSNetMonitor in a terminal window.
# When you have enough traffic, type Ctrl-C and save the content of the terminal window to disk.
# Alternatively, you can use "mDNSNetMonitor > logfile" to write the text directly to a file.
# You now have a UTF-8 text file.
# 2. Open the UTF-8 text file using BBEdit or some other text editor.
# (These instructions are for BBEdit, which I highly recommend you use when doing this.)
# 3. Make sure BBEdit correctly interprets the file as UTF-8.
# Either set your "Text Files Opening" preference to "UTF-8 no BOM", and drop the file onto BBEdit,
# or manually open the File using "File -> Open" and make sure the "Read As" setting is set to "UTF-8 no BOM"
# Check in the document pulldown menu in the window toolbar to make sure that it says "Encoding: UTF-8 no BOM"
# 4. Use "Tools -> Convert to ASCII" to replace all special characters with their seven-bit ascii equivalents.
# (e.g. curly quotes are converted to straight quotes)
# 5. Do a grep search and replace. (Cmd-F; make sure Grep checkbox is turned on.)
# Enter this search text : ^(.................\(................\S*) (.* -> .*)$
# Enter this replacement text: \1-\2
# Click "Replace All"
# Press Cmd-Opt-= repeatedly until there are no more instances to be replaced.
# You now have text file with all spaces in names changed to hyphens
# 6. Save the new file. You can save it as "UTF-8 no BOM", or as "Mac Roman". It really doesn't matter which --
# the file now contains only seven-bit ascii, so it's all the same no matter how you save it.
# 7. Run "parselog.py fname"
# 8. Open the resulting fname.pdf file with a PDF viewer like Preview on OS X
#
# Key to what you see:
# Time is on the horizontal axis
# Individual machines are shown on the vertical axis
# Filled red circle: Normal query Hollow red circle: Query requesting unicast reply
# Filled orange circle: Probe (service starting) Hollow orange circle: First probe (requesting unicast reply)
# Filled green circle: Normal answer Hollow green circle: Goodbye message (record going away)
# Hollow blue circle: Legacy query (from old client)
from CoreGraphics import *
import math # for pi
import string
import sys, os
import re
def parselog(inFile):
f = open(inFile)
hunt = 'getTime'
ipList = {}
querySource = {}
plotPoints = []
maxTime=0
minTime = 36*60*60
spaceExp = re.compile(r'\s+')
print "Reading " + inFile
while 1:
lines = f.readlines(100000)
if not lines:
break
for line in lines:
if (hunt == 'skip'):
if (line == '\n' or line == '\r' or line ==''):
hunt = 'getTime'
# else:
# msg = ("skipped" , line)
# print msg
elif (hunt == 'getTime'):
if (line == "^C\n" ):
break
time = line.split(' ')[0].split(':')
if (len(time)<3):
#print "bad time, skipping",time
hunt = 'skip'
else:
hunt = 'getIP'
#print (("getTime:%s" % (line)), time)
elif (hunt == 'getIP'):
ip = line.split(' ',1)
ip = ip[0]
secs=0
for t in time:
secs = secs*60 +float(t)
if (secs>maxTime):
maxTime=secs
if (secs<minTime):
minTime=secs
if (not ip in ipList):
ipList[ip] = [len(ipList), "", ""]
#print (("getIP:%s" % (line)), time, secs)
hunt = 'getQA'
elif (hunt == 'getQA'):
qaList = spaceExp.split(line)
# qaList[0] Source Address
# qaList[1] Operation type (PU/PM/QU/QM/AN etc.)
# qaList[2] Record type (PTR/SRV/TXT etc.)
# For QU/QM/LQ:
# qaList[3] RR name
# For PU/PM/AN/AN+/AD/AD+/KA:
# qaList[3] TTL
# qaList[4] RR name
# qaList[5...] "->" symbol and following rdata
#print qaList
if (qaList[0] == ip):
if (qaList[1] == '(QU)' or qaList[1] == '(LQ)' or qaList[1] == '(PU)'):
plotPoints.append([secs, ipList[ip][0], (qaList[1])[1:-1]])
elif (qaList[1] == '(QM)'):
plotPoints.append([secs, ipList[ip][0], (qaList[1])[1:-1]])
querySource[qaList[3]] = len(plotPoints)-1
elif (qaList[1] == '(PM)'):
plotPoints.append([secs, ipList[ip][0], (qaList[1])[1:-1]])
querySource[qaList[4]] = len(plotPoints)-1
elif (qaList[1] == '(AN)' or qaList[1] == '(AN+)' or qaList[1] == '(DE)'):
plotPoints.append([secs, ipList[ip][0], (qaList[1])[1:-1]])
try:
theQuery = querySource[qaList[4]]
theDelta = secs - plotPoints[theQuery][0]
if (theDelta < 1.0):
plotPoints[-1].append(querySource[qaList[4]])
#print "Answer AN+ %s points to %d" % (qaList[4],querySource[qaList[4]])
except:
#print "Couldn't find any preceeding question for", qaList
pass
elif (qaList[1] != '(KA)' and qaList[1] != '(AD)' and qaList[1] != '(AD+)'):
print "Operation unknown", qaList
if (qaList[1] == '(AN)' or qaList[1] == '(AN+)' or qaList[1] == '(AD)' or qaList[1] == '(AD+)'):
if (qaList[2] == 'HINFO'):
ipList[ip][1] = qaList[4]
ipList[ip][2] = string.join(qaList[6:])
#print ipList[ip][1]
elif (qaList[2] == 'AAAA'):
if (ipList[ip][1] == ""):
ipList[ip][1] = qaList[4]
ipList[ip][2] = "Panther"
elif (qaList[2] == 'Addr'):
if (ipList[ip][1] == ""):
ipList[ip][1] = qaList[4]
ipList[ip][2] = "Jaguar"
else:
if (line == '\n'):
hunt = 'getTime'
else:
hunt = 'skip'
f.close()
#print plotPoints
#print querySource
#width=20.0*(maxTime-minTime)
if (maxTime < minTime + 10.0):
maxTime = minTime + 10.0
typesize = 12
width=20.0*(maxTime-minTime)
pageHeight=(len(ipList)+1) * typesize
scale = width/(maxTime-minTime)
leftMargin = typesize * 60
bottomMargin = typesize
pageRect = CGRectMake (-leftMargin, -bottomMargin, leftMargin + width, bottomMargin + pageHeight) # landscape
outFile = "%s.pdf" % (".".join(inFile.split('.')[:-1]))
c = CGPDFContextCreateWithFilename (outFile, pageRect)
print "Writing " + outFile
ourColourSpace = c.getColorSpace()
# QM/QU red solid/hollow
# PM/PU orange solid/hollow
# LQ blue hollow
# AN/DA green solid/hollow
#colourLookup = {"L":(0.0,0.0,.75), "Q":(.75,0.0,0.0), "P":(.75,0.5,0.0), "A":(0.0,0.75,0.0), "D":(0.0,0.75,0.0), "?":(.25,0.25,0.25)}
colourLookup = {"L":(0.0,0.0,1.0), "Q":(1.0,0.0,0.0), "P":(1.0,0.8,0.0), "A":(0.0,1.0,0.0), "D":(0.0,1.0,0.0), "?":(1.0,1.0,1.0)}
c.beginPage (pageRect)
c.setRGBFillColor(.75,0.0,0.0,1.0)
c.setRGBStrokeColor(.25,0.75,0.25,1.0)
c.setLineWidth(0.25)
for point in plotPoints:
#c.addArc((point[0]-minTime)*scale,point[1]*typesize+6,5,0,2*math.pi,1)
c.addArc((point[0]-minTime)*scale,point[1]*typesize+6,typesize/4,0,2*math.pi,1)
theColour = colourLookup[(point[2])[0]]
if (((point[2])[0]) != "L") and (((point[2])[0]) != "Q") and (((point[2])[0]) != "P") and (((point[2])[0]) != "A") and (((point[2])[0]) != "D"):
print "Unknown", point
if ((point[2])[-1] == "M" or (point[2])[0]== "A"):
c.setRGBFillColor(theColour[0],theColour[1],theColour[2],.5)
c.fillPath()
else:
c.setRGBStrokeColor(theColour[0],theColour[1],theColour[2],.5)
c.setLineWidth(1.0)
c.strokePath()
c.setRGBStrokeColor(.25,0.75,0.25,1.0)
c.setLineWidth(0.25)
for index in point[3:]:
c.beginPath()
c.moveToPoint((point[0]-minTime)*scale,point[1]*typesize+6)
c.addLineToPoint(((plotPoints[index])[0]-minTime)*scale,(plotPoints[index])[1]*typesize+6)
c.closePath()
c.strokePath()
c.setRGBFillColor (0,0,0, 1)
c.setTextDrawingMode (kCGTextFill)
c.setTextMatrix (CGAffineTransformIdentity)
c.selectFont ('Gill Sans', typesize, kCGEncodingMacRoman)
c.setRGBStrokeColor(0.25,0.0,0.0,1.0)
c.setLineWidth(0.1)
for ip,[height,hname,hinfo] in ipList.items():
c.beginPath()
c.moveToPoint(pageRect.origin.x,height*typesize+6)
c.addLineToPoint(width,height*typesize+6)
c.closePath()
c.strokePath()
c.showTextAtPoint(pageRect.origin.x + 2, height*typesize + 2, ip, len(ip))
c.showTextAtPoint(pageRect.origin.x + 2 + typesize*8, height*typesize + 2, hname, len(hname))
c.showTextAtPoint(pageRect.origin.x + 2 + typesize*25, height*typesize + 2, hinfo, len(hinfo))
for time in range (int(minTime),int(maxTime)+1):
c.beginPath()
c.moveToPoint((time-minTime)*scale,pageRect.origin.y)
c.addLineToPoint((time-minTime)*scale,pageHeight)
c.closePath()
if (int(time) % 10 == 0):
theHours = time/3600
theMinutes = time/60 % 60
theSeconds = time % 60
theTimeString = '%d:%02d:%02d' % (theHours, theMinutes, theSeconds)
# Should measure string width, but don't know how to do that
theStringWidth = typesize * 3.5
c.showTextAtPoint((time-minTime)*scale - theStringWidth/2, pageRect.origin.y + 2, theTimeString, len(theTimeString))
c.setLineWidth(0.3)
else:
c.setLineWidth(0.1)
c.strokePath()
c.endPage()
c.finish()
for arg in sys.argv[1:]:
parselog(arg)
| apache-2.0 |
teamfx/openjfx-9-dev-rt | modules/javafx.web/src/main/native/Tools/Scripts/webkitpy/common/net/regressionwindow.py | 165 | 2381 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# FIXME: This probably belongs in the buildbot module.
class RegressionWindow(object):
def __init__(self, build_before_failure, failing_build, failing_tests=None):
self._build_before_failure = build_before_failure
self._failing_build = failing_build
self._failing_tests = failing_tests
self._revisions = None
def build_before_failure(self):
return self._build_before_failure
def failing_build(self):
return self._failing_build
def failing_tests(self):
return self._failing_tests
def revisions(self):
# Cache revisions to avoid excessive allocations.
if not self._revisions:
self._revisions = range(self._failing_build.revision(), self._build_before_failure.revision(), -1)
self._revisions.reverse()
return self._revisions
| gpl-2.0 |
phassoa/openelisglobal-core | liquibase/OE4.2/testCatalogCI_LNSP/scripts/createLocalCode.py | 25 | 1703 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def trim( name, length):
if len( name ) <= length:
return name
else:
last_space = name.find(" ")
if last_space == -1:
return name[:35]
else:
return trim( name[:last_space], length)
def translate( name ):
if name == 'Sang total':
return 'Blood'
else:
return name
english_test_names = []
french_test_names = []
sample_types = []
name_results = []
guids = []
english_name_file = open('englishTestName.txt','r')
french_name_file = open('testName.txt', 'r')
sample_type_file = open("sampleType.txt", 'r')
result_file = open("../localCode.sql", "w")
guid_file = open("guid.txt", "r")
for line in english_name_file:
english_test_names.append(line.strip())
english_name_file.close()
for line in french_name_file:
french_test_names.append(line.strip())
french_name_file.close()
for line in sample_type_file:
sample_types.append(line.strip())
sample_type_file.close()
for line in guid_file:
guids.append(line.strip())
guid_file.close()
updateString = "update clinlims.test set local_code='"
for row in range(0, len(guids)):
if guids[row]:
test_name = english_test_names[row] if english_test_names[row] else french_test_names[row]
sample_type = sample_types[row] if sample_types[row] else "variable"
name_results.append(updateString)
name_results.append(trim(test_name, 35) + "-" + translate(sample_type) + "' where guid = '" + guids[row] + "';\n")
for line in name_results:
result_file.write(line)
print "Done look for results in localCode.sql"
| mpl-2.0 |
martinling/imusim | imusim/trajectories/sampled.py | 2 | 5624 | """
Classes representing sampled trajectories.
Sampled trajectories do not support evaluation of derivative values such as
velocities or accelerations. To evaulate these properties a splined trajectory
should be constructed. See L{splined}
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim 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.
#
# IMUSim 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 IMUSim. If not, see <http://www.gnu.org/licenses/>.
from base import PositionTrajectory, RotationTrajectory
from imusim.maths.quaternions import Quaternion, QuaternionArray
from imusim.utilities.caching import CacheLastValue
from imusim.utilities.time_series import TimeSeries
import imusim.maths.vectors as vectors
import numpy as np
class SampledPositionTrajectory(PositionTrajectory):
"""
Represents a sampled position trajectory.
@ivar positionKeyFrames: A L{TimeSeries} of position key frames.
"""
def __init__(self, keyFrames=None):
"""
Initialise trajectory.
@param keyFrames: A L{TimeSeries} of position key frame samples.
"""
self.positionKeyFrames = TimeSeries() if keyFrames is None else keyFrames
@CacheLastValue()
def position(self, t):
if len(self.positionKeyFrames) == 0:
if np.ndim(t) == 0:
return vectors.nan()
else:
return vectors.nan(len(t))
else:
return self.positionKeyFrames(t)
def velocity(self, t):
"""
Not implemented for sampled trajectories.
See L{imusim.trajectories.splined} for support.
"""
raise NotImplementedError, \
"Derivative not available from sampled trajectory. " \
+ "Create a splined trajectory to obtain derivatives."
def acceleration(self, t):
"""
Not implemented for sampled trajectories.
See L{imusim.trajectories.splined} for support.
"""
raise NotImplementedError, \
"Derivative not available from sampled trajectory. " \
+ "Create a splined trajectory to obtain derivatives."
@property
def startTime(self):
return self.positionKeyFrames.earliestTime
@property
def endTime(self):
return self.positionKeyFrames.latestTime
class SampledRotationTrajectory(RotationTrajectory):
"""
Represents a sampled rotation trajectory.
@ivar rotationKeyFrames: A L{TimeSeries} of rotiaton key frames.
"""
def __init__(self, keyFrames=None):
"""
Initialise trajectory.
@param keyFrames: A L{TimeSeries} of rotation key frame samples.
"""
self.rotationKeyFrames = TimeSeries() if keyFrames is None else keyFrames
@CacheLastValue()
def rotation(self, t):
if len(self.rotationKeyFrames) == 0:
if np.ndim(t) == 0:
return Quaternion.nan()
else:
return QuaternionArray.nan(len(t))
else:
return self.rotationKeyFrames(t)
def rotationalVelocity(self, t):
"""
Not implemented for sampled trajectories.
See L{splined} for support.
"""
raise NotImplementedError, \
"Derivative not available from sampled trajectory. " \
+ "Create a splined trajectory to obtain derivatives."
def rotationalAcceleration(self, t):
"""
Not implemented for sampled trajectories.
See L{splined} for support.
"""
raise NotImplementedError, \
"Derivative not available from sampled trajectory. " \
+ "Create a splined trajectory to obtain derivatives."
@property
def startTime(self):
return self.rotationKeyFrames.earliestTime
@property
def endTime(self):
return self.rotationKeyFrames.latestTime
class SampledTrajectory(SampledPositionTrajectory, SampledRotationTrajectory):
"""
Represents a sampled position and rotation trajectory.
"""
def __init__(self, positionKeyFrames=None, rotationKeyFrames=None):
"""
Initialise trajectory.
@param positionKeyFrames: L{TimeSeries} of position key frames.
@param rotationKeyFrames: L{TimeSeries} of rotation key frames.
"""
SampledPositionTrajectory.__init__(self, positionKeyFrames)
SampledRotationTrajectory.__init__(self, rotationKeyFrames)
@staticmethod
def fromArrays(time, position, rotation):
"""
Construct a L{SampledTrajectory} from time, position and rotation arrays.
@param time: sequence of sample times.
@param position: sequence of position samples.
@param rotation: sequence of rotation samples.
"""
return SampledTrajectory(
TimeSeries(time, position),
TimeSeries(time, rotation))
@property
def startTime(self):
return max(self.positionKeyFrames.earliestTime, self.rotationKeyFrames.earliestTime)
@property
def endTime(self):
return min(self.positionKeyFrames.latestTime, self.rotationKeyFrames.latestTime)
| gpl-3.0 |
sajeeshcs/nested_quota_final | nova/objects/pci_device_pool.py | 4 | 3410 | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
from oslo_serialization import jsonutils
import six
from nova import objects
from nova.objects import base
from nova.objects import fields
class PciDevicePool(base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'product_id': fields.StringField(),
'vendor_id': fields.StringField(),
'tags': fields.DictOfNullableStringsField(),
'count': fields.IntegerField(),
}
# NOTE(pmurray): before this object existed the pci device pool data was
# stored as a dict. For backward compatibility we need to be able to read
# it in from a dict
@classmethod
def from_dict(cls, value):
pool_dict = copy.copy(value)
pool = cls()
pool.vendor_id = pool_dict.pop("vendor_id")
pool.product_id = pool_dict.pop("product_id")
pool.count = pool_dict.pop("count")
pool.tags = {}
pool.tags.update(pool_dict)
return pool
# NOTE(sbauza): Before using objects, pci stats was a list of
# dictionaries not having tags. For compatibility with other modules, let's
# create a reversible method
def to_dict(self):
pci_pool = base.obj_to_primitive(self)
tags = pci_pool.pop('tags', None)
for k, v in six.iteritems(tags):
pci_pool[k] = v
return pci_pool
class PciDevicePoolList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
# PciDevicePool <= 1.0
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('PciDevicePool'),
}
child_versions = {
'1.0': '1.0',
}
def from_pci_stats(pci_stats):
"""Create and return a PciDevicePoolList from the data stored in the db,
which can be either the serialized object, or, prior to the creation of the
device pool objects, a simple dict or a list of such dicts.
"""
pools = None
if isinstance(pci_stats, six.string_types):
try:
pci_stats = jsonutils.loads(pci_stats)
except (ValueError, TypeError):
pci_stats = None
if pci_stats:
# Check for object-ness, or old-style storage format.
if 'nova_object.namespace' in pci_stats:
pools = objects.PciDevicePoolList.obj_from_primitive(pci_stats)
else:
# This can be either a dict or a list of dicts
if isinstance(pci_stats, list):
pool_list = [objects.PciDevicePool.from_dict(stat)
for stat in pci_stats]
else:
pool_list = [objects.PciDevicePool.from_dict(pci_stats)]
pools = objects.PciDevicePoolList(objects=pool_list)
return pools
| apache-2.0 |
KaranToor/MA450 | google-cloud-sdk/platform/gsutil/third_party/boto/tests/__init__.py | 454 | 1103 | # Copyright (c) 2006-2011 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
| apache-2.0 |
studio666/gnuradio | gr-atsc/python/atsc/__init__.py | 57 | 1161 | #
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
# The presence of this file turns this directory into a Python package
'''
Blocks and utilities for ATSC (Advanced Television Systems Committee) module.
'''
import os
try:
from atsc_swig import *
except ImportError:
dirname, filename = os.path.split(os.path.abspath(__file__))
__path__.append(os.path.join(dirname, "..", "..", "swig"))
from atsc_swig import *
| gpl-3.0 |
yb-kim/gemV | ext/ply/test/testyacc.py | 93 | 14230 | # testyacc.py
import unittest
try:
import StringIO
except ImportError:
import io as StringIO
import sys
import os
sys.path.insert(0,"..")
sys.tracebacklimit = 0
import ply.yacc
def check_expected(result,expected):
resultlines = []
for line in result.splitlines():
if line.startswith("WARNING: "):
line = line[9:]
elif line.startswith("ERROR: "):
line = line[7:]
resultlines.append(line)
expectedlines = expected.splitlines()
if len(resultlines) != len(expectedlines):
return False
for rline,eline in zip(resultlines,expectedlines):
if not rline.endswith(eline):
return False
return True
def run_import(module):
code = "import "+module
exec(code)
del sys.modules[module]
# Tests related to errors and warnings when building parsers
class YaccErrorWarningTests(unittest.TestCase):
def setUp(self):
sys.stderr = StringIO.StringIO()
sys.stdout = StringIO.StringIO()
try:
os.remove("parsetab.py")
os.remove("parsetab.pyc")
except OSError:
pass
def tearDown(self):
sys.stderr = sys.__stderr__
sys.stdout = sys.__stdout__
def test_yacc_badargs(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_badargs")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_badargs.py:23: Rule 'p_statement_assign' has too many arguments\n"
"yacc_badargs.py:27: Rule 'p_statement_expr' requires an argument\n"
))
def test_yacc_badid(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_badid")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_badid.py:32: Illegal name 'bad&rule' in rule 'statement'\n"
"yacc_badid.py:36: Illegal rule name 'bad&rule'\n"
))
def test_yacc_badprec(self):
try:
run_import("yacc_badprec")
except ply.yacc.YaccError:
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"precedence must be a list or tuple\n"
))
def test_yacc_badprec2(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_badprec2")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Bad precedence table\n"
))
def test_yacc_badprec3(self):
run_import("yacc_badprec3")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Precedence already specified for terminal 'MINUS'\n"
"Generating LALR tables\n"
))
def test_yacc_badrule(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_badrule")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_badrule.py:24: Syntax error. Expected ':'\n"
"yacc_badrule.py:28: Syntax error in rule 'statement'\n"
"yacc_badrule.py:33: Syntax error. Expected ':'\n"
"yacc_badrule.py:42: Syntax error. Expected ':'\n"
))
def test_yacc_badtok(self):
try:
run_import("yacc_badtok")
except ply.yacc.YaccError:
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"tokens must be a list or tuple\n"))
def test_yacc_dup(self):
run_import("yacc_dup")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_dup.py:27: Function p_statement redefined. Previously defined on line 23\n"
"Token 'EQUALS' defined, but not used\n"
"There is 1 unused token\n"
"Generating LALR tables\n"
))
def test_yacc_error1(self):
try:
run_import("yacc_error1")
except ply.yacc.YaccError:
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_error1.py:61: p_error() requires 1 argument\n"))
def test_yacc_error2(self):
try:
run_import("yacc_error2")
except ply.yacc.YaccError:
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_error2.py:61: p_error() requires 1 argument\n"))
def test_yacc_error3(self):
try:
run_import("yacc_error3")
except ply.yacc.YaccError:
e = sys.exc_info()[1]
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"'p_error' defined, but is not a function or method\n"))
def test_yacc_error4(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_error4")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_error4.py:62: Illegal rule name 'error'. Already defined as a token\n"
))
def test_yacc_inf(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_inf")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Token 'NUMBER' defined, but not used\n"
"There is 1 unused token\n"
"Infinite recursion detected for symbol 'statement'\n"
"Infinite recursion detected for symbol 'expression'\n"
))
def test_yacc_literal(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_literal")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_literal.py:36: Literal token '**' in rule 'expression' may only be a single character\n"
))
def test_yacc_misplaced(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_misplaced")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_misplaced.py:32: Misplaced '|'\n"
))
def test_yacc_missing1(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_missing1")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_missing1.py:24: Symbol 'location' used, but not defined as a token or a rule\n"
))
def test_yacc_nested(self):
run_import("yacc_nested")
result = sys.stdout.getvalue()
self.assert_(check_expected(result,
"A\n"
"A\n"
"A\n",
))
def test_yacc_nodoc(self):
run_import("yacc_nodoc")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_nodoc.py:27: No documentation string specified in function 'p_statement_expr' (ignored)\n"
"Generating LALR tables\n"
))
def test_yacc_noerror(self):
run_import("yacc_noerror")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"no p_error() function is defined\n"
"Generating LALR tables\n"
))
def test_yacc_nop(self):
run_import("yacc_nop")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_nop.py:27: Possible grammar rule 'statement_expr' defined without p_ prefix\n"
"Generating LALR tables\n"
))
def test_yacc_notfunc(self):
run_import("yacc_notfunc")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"'p_statement_assign' not defined as a function\n"
"Token 'EQUALS' defined, but not used\n"
"There is 1 unused token\n"
"Generating LALR tables\n"
))
def test_yacc_notok(self):
try:
run_import("yacc_notok")
except ply.yacc.YaccError:
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"No token list is defined\n"))
def test_yacc_rr(self):
run_import("yacc_rr")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Generating LALR tables\n"
"1 reduce/reduce conflict\n"
"reduce/reduce conflict in state 15 resolved using rule (statement -> NAME EQUALS NUMBER)\n"
"rejected rule (expression -> NUMBER) in state 15\n"
))
def test_yacc_rr_unused(self):
run_import("yacc_rr_unused")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"no p_error() function is defined\n"
"Generating LALR tables\n"
"3 reduce/reduce conflicts\n"
"reduce/reduce conflict in state 1 resolved using rule (rule3 -> A)\n"
"rejected rule (rule4 -> A) in state 1\n"
"reduce/reduce conflict in state 1 resolved using rule (rule3 -> A)\n"
"rejected rule (rule5 -> A) in state 1\n"
"reduce/reduce conflict in state 1 resolved using rule (rule4 -> A)\n"
"rejected rule (rule5 -> A) in state 1\n"
"Rule (rule5 -> A) is never reduced\n"
))
def test_yacc_simple(self):
run_import("yacc_simple")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Generating LALR tables\n"
))
def test_yacc_sr(self):
run_import("yacc_sr")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Generating LALR tables\n"
"20 shift/reduce conflicts\n"
))
def test_yacc_term1(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_term1")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_term1.py:24: Illegal rule name 'NUMBER'. Already defined as a token\n"
))
def test_yacc_unused(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_unused")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_unused.py:62: Symbol 'COMMA' used, but not defined as a token or a rule\n"
"Symbol 'COMMA' is unreachable\n"
"Symbol 'exprlist' is unreachable\n"
))
def test_yacc_unused_rule(self):
run_import("yacc_unused_rule")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_unused_rule.py:62: Rule 'integer' defined, but not used\n"
"There is 1 unused rule\n"
"Symbol 'integer' is unreachable\n"
"Generating LALR tables\n"
))
def test_yacc_uprec(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_uprec")
result = sys.stderr.getvalue()
print repr(result)
self.assert_(check_expected(result,
"yacc_uprec.py:37: Nothing known about the precedence of 'UMINUS'\n"
))
def test_yacc_uprec2(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_uprec2")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"yacc_uprec2.py:37: Syntax error. Nothing follows %prec\n"
))
def test_yacc_prec1(self):
self.assertRaises(ply.yacc.YaccError,run_import,"yacc_prec1")
result = sys.stderr.getvalue()
self.assert_(check_expected(result,
"Precedence rule 'left' defined for unknown symbol '+'\n"
"Precedence rule 'left' defined for unknown symbol '*'\n"
"Precedence rule 'left' defined for unknown symbol '-'\n"
"Precedence rule 'left' defined for unknown symbol '/'\n"
))
unittest.main()
| bsd-3-clause |
vybstat/scikit-learn | sklearn/covariance/empirical_covariance_.py | 101 | 9133 | """
Maximum likelihood covariance estimator.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Virgile Fritsch <virgile.fritsch@inria.fr>
#
# License: BSD 3 clause
# avoid division truncation
from __future__ import division
import warnings
import numpy as np
from scipy import linalg
from ..base import BaseEstimator
from ..utils import check_array
from ..utils.extmath import fast_logdet, pinvh
def log_likelihood(emp_cov, precision):
"""Computes the sample mean of the log_likelihood under a covariance model
computes the empirical expected log-likelihood (accounting for the
normalization terms and scaling), allowing for universal comparison (beyond
this software package)
Parameters
----------
emp_cov : 2D ndarray (n_features, n_features)
Maximum Likelihood Estimator of covariance
precision : 2D ndarray (n_features, n_features)
The precision matrix of the covariance model to be tested
Returns
-------
sample mean of the log-likelihood
"""
p = precision.shape[0]
log_likelihood_ = - np.sum(emp_cov * precision) + fast_logdet(precision)
log_likelihood_ -= p * np.log(2 * np.pi)
log_likelihood_ /= 2.
return log_likelihood_
def empirical_covariance(X, assume_centered=False):
"""Computes the Maximum likelihood covariance estimator
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Data from which to compute the covariance estimate
assume_centered : Boolean
If True, data are not centered before computation.
Useful when working with data whose mean is almost, but not exactly
zero.
If False, data are centered before computation.
Returns
-------
covariance : 2D ndarray, shape (n_features, n_features)
Empirical covariance (Maximum Likelihood Estimator).
"""
X = np.asarray(X)
if X.ndim == 1:
X = np.reshape(X, (1, -1))
if X.shape[0] == 1:
warnings.warn("Only one sample available. "
"You may want to reshape your data array")
if assume_centered:
covariance = np.dot(X.T, X) / X.shape[0]
else:
covariance = np.cov(X.T, bias=1)
if covariance.ndim == 0:
covariance = np.array([[covariance]])
return covariance
class EmpiricalCovariance(BaseEstimator):
"""Maximum likelihood covariance estimator
Read more in the :ref:`User Guide <covariance>`.
Parameters
----------
store_precision : bool
Specifies if the estimated precision is stored.
assume_centered : bool
If True, data are not centered before computation.
Useful when working with data whose mean is almost, but not exactly
zero.
If False (default), data are centered before computation.
Attributes
----------
covariance_ : 2D ndarray, shape (n_features, n_features)
Estimated covariance matrix
precision_ : 2D ndarray, shape (n_features, n_features)
Estimated pseudo-inverse matrix.
(stored only if store_precision is True)
"""
def __init__(self, store_precision=True, assume_centered=False):
self.store_precision = store_precision
self.assume_centered = assume_centered
def _set_covariance(self, covariance):
"""Saves the covariance and precision estimates
Storage is done accordingly to `self.store_precision`.
Precision stored only if invertible.
Parameters
----------
covariance : 2D ndarray, shape (n_features, n_features)
Estimated covariance matrix to be stored, and from which precision
is computed.
"""
covariance = check_array(covariance)
# set covariance
self.covariance_ = covariance
# set precision
if self.store_precision:
self.precision_ = pinvh(covariance)
else:
self.precision_ = None
def get_precision(self):
"""Getter for the precision matrix.
Returns
-------
precision_ : array-like,
The precision matrix associated to the current covariance object.
"""
if self.store_precision:
precision = self.precision_
else:
precision = pinvh(self.covariance_)
return precision
def fit(self, X, y=None):
"""Fits the Maximum Likelihood Estimator covariance model
according to the given training data and parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training data, where n_samples is the number of samples and
n_features is the number of features.
y : not used, present for API consistence purpose.
Returns
-------
self : object
Returns self.
"""
X = check_array(X)
if self.assume_centered:
self.location_ = np.zeros(X.shape[1])
else:
self.location_ = X.mean(0)
covariance = empirical_covariance(
X, assume_centered=self.assume_centered)
self._set_covariance(covariance)
return self
def score(self, X_test, y=None):
"""Computes the log-likelihood of a Gaussian data set with
`self.covariance_` as an estimator of its covariance matrix.
Parameters
----------
X_test : array-like, shape = [n_samples, n_features]
Test data of which we compute the likelihood, where n_samples is
the number of samples and n_features is the number of features.
X_test is assumed to be drawn from the same distribution than
the data used in fit (including centering).
y : not used, present for API consistence purpose.
Returns
-------
res : float
The likelihood of the data set with `self.covariance_` as an
estimator of its covariance matrix.
"""
# compute empirical covariance of the test set
test_cov = empirical_covariance(
X_test - self.location_, assume_centered=True)
# compute log likelihood
res = log_likelihood(test_cov, self.get_precision())
return res
def error_norm(self, comp_cov, norm='frobenius', scaling=True,
squared=True):
"""Computes the Mean Squared Error between two covariance estimators.
(In the sense of the Frobenius norm).
Parameters
----------
comp_cov : array-like, shape = [n_features, n_features]
The covariance to compare with.
norm : str
The type of norm used to compute the error. Available error types:
- 'frobenius' (default): sqrt(tr(A^t.A))
- 'spectral': sqrt(max(eigenvalues(A^t.A))
where A is the error ``(comp_cov - self.covariance_)``.
scaling : bool
If True (default), the squared error norm is divided by n_features.
If False, the squared error norm is not rescaled.
squared : bool
Whether to compute the squared error norm or the error norm.
If True (default), the squared error norm is returned.
If False, the error norm is returned.
Returns
-------
The Mean Squared Error (in the sense of the Frobenius norm) between
`self` and `comp_cov` covariance estimators.
"""
# compute the error
error = comp_cov - self.covariance_
# compute the error norm
if norm == "frobenius":
squared_norm = np.sum(error ** 2)
elif norm == "spectral":
squared_norm = np.amax(linalg.svdvals(np.dot(error.T, error)))
else:
raise NotImplementedError(
"Only spectral and frobenius norms are implemented")
# optionaly scale the error norm
if scaling:
squared_norm = squared_norm / error.shape[0]
# finally get either the squared norm or the norm
if squared:
result = squared_norm
else:
result = np.sqrt(squared_norm)
return result
def mahalanobis(self, observations):
"""Computes the squared Mahalanobis distances of given observations.
Parameters
----------
observations : array-like, shape = [n_observations, n_features]
The observations, the Mahalanobis distances of the which we
compute. Observations are assumed to be drawn from the same
distribution than the data used in fit.
Returns
-------
mahalanobis_distance : array, shape = [n_observations,]
Squared Mahalanobis distances of the observations.
"""
precision = self.get_precision()
# compute mahalanobis distances
centered_obs = observations - self.location_
mahalanobis_dist = np.sum(
np.dot(centered_obs, precision) * centered_obs, 1)
return mahalanobis_dist
| bsd-3-clause |
aswinpj/Pygments | pygments/lexers/go.py | 47 | 3701 | # -*- coding: utf-8 -*-
"""
pygments.lexers.go
~~~~~~~~~~~~~~~~~~
Lexers for the Google Go language.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, words
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation
__all__ = ['GoLexer']
class GoLexer(RegexLexer):
"""
For `Go <http://golang.org>`_ source.
.. versionadded:: 1.2
"""
name = 'Go'
filenames = ['*.go']
aliases = ['go']
mimetypes = ['text/x-gosrc']
flags = re.MULTILINE | re.UNICODE
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
(r'\\\n', Text), # line continuations
(r'//(.*?)\n', Comment.Single),
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(r'(import|package)\b', Keyword.Namespace),
(r'(var|func|struct|map|chan|type|interface|const)\b',
Keyword.Declaration),
(words((
'break', 'default', 'select', 'case', 'defer', 'go',
'else', 'goto', 'switch', 'fallthrough', 'if', 'range',
'continue', 'for', 'return'), suffix=r'\b'),
Keyword),
(r'(true|false|iota|nil)\b', Keyword.Constant),
# It seems the builtin types aren't actually keywords, but
# can be used as functions. So we need two declarations.
(words((
'uint', 'uint8', 'uint16', 'uint32', 'uint64',
'int', 'int8', 'int16', 'int32', 'int64',
'float', 'float32', 'float64',
'complex64', 'complex128', 'byte', 'rune',
'string', 'bool', 'error', 'uintptr',
'print', 'println', 'panic', 'recover', 'close', 'complex',
'real', 'imag', 'len', 'cap', 'append', 'copy', 'delete',
'new', 'make'), suffix=r'\b(\()'),
bygroups(Name.Builtin, Punctuation)),
(words((
'uint', 'uint8', 'uint16', 'uint32', 'uint64',
'int', 'int8', 'int16', 'int32', 'int64',
'float', 'float32', 'float64',
'complex64', 'complex128', 'byte', 'rune',
'string', 'bool', 'error', 'uintptr'), suffix=r'\b'),
Keyword.Type),
# imaginary_lit
(r'\d+i', Number),
(r'\d+\.\d*([Ee][-+]\d+)?i', Number),
(r'\.\d+([Ee][-+]\d+)?i', Number),
(r'\d+[Ee][-+]\d+i', Number),
# float_lit
(r'\d+(\.\d+[eE][+\-]?\d+|'
r'\.\d*|[eE][+\-]?\d+)', Number.Float),
(r'\.\d+([eE][+\-]?\d+)?', Number.Float),
# int_lit
# -- octal_lit
(r'0[0-7]+', Number.Oct),
# -- hex_lit
(r'0[xX][0-9a-fA-F]+', Number.Hex),
# -- decimal_lit
(r'(0|[1-9][0-9]*)', Number.Integer),
# char_lit
(r"""'(\\['"\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}"""
r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|[^\\])'""",
String.Char),
# StringLiteral
# -- raw_string_lit
(r'`[^`]*`', String),
# -- interpreted_string_lit
(r'"(\\\\|\\"|[^"])*"', String),
# Tokens
(r'(<<=|>>=|<<|>>|<=|>=|&\^=|&\^|\+=|-=|\*=|/=|%=|&=|\|=|&&|\|\|'
r'|<-|\+\+|--|==|!=|:=|\.\.\.|[+\-*/%&])', Operator),
(r'[|^<>=!()\[\]{}.,;:]', Punctuation),
# identifier
(r'[^\W\d]\w*', Name.Other),
]
}
| bsd-2-clause |
40023255/-w16b_test | static/Brython3.1.1-20150328-091302/Lib/site-packages/pygame/surface.py | 603 | 3844 | from browser import document, html, window
from javascript import console, JSConstructor
from .rect import Rect
#import pygame.rect
canvas_ID=1
_canvas_id=None
class Surface:
def __init__(self, dim=[], depth=16, surf=None):
if surf is None:
self._depth=depth
self._canvas=html.CANVAS(width=dim[0], height=dim[1])
elif isinstance(surf, Surface):
self._canvas=surf.copy()
#self._width=surf.get_width()
#self._height=surf.get_height()
elif isinstance(surf, html.CANVAS):
self._canvas=surf
#self._width=surf.style.width
#self._height=surf.style.height
self._context=self._canvas.getContext('2d')
self._canvas.id='layer_%s' % canvas_ID
#setattr(self._canvas.style, 'z-index',canvas_ID)
#setattr(self._canvas.style, 'position', 'relative')
#setattr(self._canvas.style, 'left', '0px')
#setattr(self._canvas.style, 'top', '0px')
canvas_ID+=1
#document['pydiv'] <= self._canvas
def blit(self, source, dest, area=None, special_flags=0):
#if area is None and isinstance(source, str):
# _img = JSConstructor(window.Image)()
# _img.src = source
# def img_onload(*args):
# self._context.drawImage(_img, dest[0], dest[1])
# _img.onload=img_onload
# _img.width, _img.height
global _canvas_id
if _canvas_id is None:
try:
_canvas_id=document.get(selector='canvas')[0].getAttribute('id')
except:
pass
if self._canvas.id == _canvas_id:
self._canvas.width=self._canvas.width
if area is None:
#lets set area to the size of the source
if isinstance(source, Surface):
area=[(0, 0), (source.canvas.width, source.canvas.height)]
if isinstance(source, Surface):
_ctx=source.canvas.getContext('2d')
_subset=_ctx.getImageData(area[0][0],area[0][1], area[1][0], area[1][1])
# we want just a subset of the source image copied
self._context.putImageData(_subset, dest[0], dest[1])
#print(dest[0], dest[1], _subset.width, _subset.height)
return Rect(dest[0], dest[1], dest[0]+_subset.width, dest[1]+_subset.height)
def convert(self, surface=None):
## fix me...
return self
def copy(self):
_imgdata=self._context.toDataURL('image/png')
_canvas=html.CANVAS(width=self._canvas.width,height=self._canvas.height)
_ctx=_canvas.getContext('2d')
_ctx.drawImage(_imgdata, 0, 0)
return _canvas
def fill(self, color):
""" fill canvas with this color """
self._context.fillStyle="rgb(%s,%s,%s)" % color
#console.log(self._canvas.width, self._canvas.height, self._context.fillStyle)
self._context.fillRect(0,0,self._canvas.width,self._canvas.height)
#self._context.fill()
@property
def height(self):
return int(self._canvas.height)
@property
def width(self):
return int(self._canvas.width)
@property
def canvas(self):
return self._canvas
def scroll(self, dx=0, dy=0):
_imgdata=self._context.toDataURL('image/png')
self._context.drawImage(_imgdata, dx, dy)
def get_at(self, pos):
#returns rgb
return self._context.getImageData(pos[0], pos[1],1,1).data
def set_at(self, pos, color):
self._context.fillStyle='rgb(%s,%s,%s)' % color
self._context.fillRect(pos[0], pos[1], 1, 1)
def get_size(self):
return self._canvas.width, self._canvas.height
def get_width(self):
return self._canvas.width
def get_height(self):
return self._canvas.height
def get_rect(self, centerx=None, centery=None):
return Rect(0, 0, self._canvas.width, self._canvas.height)
def set_colorkey(self, key, val):
pass
| agpl-3.0 |
Demolisty24/AlexaFood-Backend | venv/Lib/site-packages/jinja2/tests.py | 336 | 4131 | # -*- coding: utf-8 -*-
"""
jinja2.tests
~~~~~~~~~~~~
Jinja test functions. Used with the "is" operator.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
from collections import Mapping
from jinja2.runtime import Undefined
from jinja2._compat import text_type, string_types, integer_types
import decimal
number_re = re.compile(r'^-?\d+(\.\d+)?$')
regex_type = type(number_re)
test_callable = callable
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1
def test_even(value):
"""Return true if the variable is even."""
return value % 2 == 0
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0
def test_defined(value):
"""Return true if the variable is defined:
.. sourcecode:: jinja
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the :func:`default` filter for a simple way to set undefined
variables.
"""
return not isinstance(value, Undefined)
def test_undefined(value):
"""Like :func:`defined` but the other way round."""
return isinstance(value, Undefined)
def test_none(value):
"""Return true if the variable is none."""
return value is None
def test_lower(value):
"""Return true if the variable is lowercased."""
return text_type(value).islower()
def test_upper(value):
"""Return true if the variable is uppercased."""
return text_type(value).isupper()
def test_string(value):
"""Return true if the object is a string."""
return isinstance(value, string_types)
def test_mapping(value):
"""Return true if the object is a mapping (dict etc.).
.. versionadded:: 2.6
"""
return isinstance(value, Mapping)
def test_number(value):
"""Return true if the variable is a number."""
return isinstance(value, integer_types + (float, complex, decimal.Decimal))
def test_sequence(value):
"""Return true if the variable is a sequence. Sequences are variables
that are iterable.
"""
try:
len(value)
value.__getitem__
except:
return False
return True
def test_equalto(value, other):
"""Check if an object has the same value as another object:
.. sourcecode:: jinja
{% if foo.expression is equalto 42 %}
the foo attribute evaluates to the constant 42
{% endif %}
This appears to be a useless test as it does exactly the same as the
``==`` operator, but it can be useful when used together with the
`selectattr` function:
.. sourcecode:: jinja
{{ users|selectattr("email", "equalto", "foo@bar.invalid") }}
.. versionadded:: 2.8
"""
return value == other
def test_sameas(value, other):
"""Check if an object points to the same memory address than another
object:
.. sourcecode:: jinja
{% if foo.attribute is sameas false %}
the foo attribute really is the `False` singleton
{% endif %}
"""
return value is other
def test_iterable(value):
"""Check if it's possible to iterate over an object."""
try:
iter(value)
except TypeError:
return False
return True
def test_escaped(value):
"""Check if the value is escaped."""
return hasattr(value, '__html__')
TESTS = {
'odd': test_odd,
'even': test_even,
'divisibleby': test_divisibleby,
'defined': test_defined,
'undefined': test_undefined,
'none': test_none,
'lower': test_lower,
'upper': test_upper,
'string': test_string,
'mapping': test_mapping,
'number': test_number,
'sequence': test_sequence,
'iterable': test_iterable,
'callable': test_callable,
'sameas': test_sameas,
'equalto': test_equalto,
'escaped': test_escaped
}
| mit |
amcgee/pymomo | test/test_utilities/test_settings_dir.py | 2 | 1243 | from pymomo.utilities import build
from nose.tools import *
import unittest
import os.path
import os
import platform
from pymomo.exceptions import *
from pymomo.utilities.paths import MomoPaths
class TestSettingsDirectory:
def setUp(self):
self.paths = MomoPaths()
self.confdir = os.path.join(os.path.expanduser('~'), '.config')
def test_settings_dir(self):
assert os.path.exists(self.paths.settings)
@unittest.skipIf(platform.system() != 'Linux', 'Linux specific test')
def test_settings_linix(self):
settings_dir = os.path.abspath(os.path.join(self.confdir, 'WellDone-MoMo'))
assert settings_dir == self.paths.settings
@unittest.skipIf(platform.system() != 'Windows', 'Windows specific test')
def test_settings_windows(self):
if 'APPDATA' in os.environ:
base = os.environ['APPDATA']
else:
base = self.confdir
settings_dir = os.path.abspath(os.path.join(base, 'WellDone-MoMo'))
assert settings_dir == self.paths.settings
@unittest.skipIf(platform.system() != 'Darwin', 'Mac OS X specific test')
def test_settings_darwin(self):
settings_dir = os.path.abspath(os.path.join(os.path.expanduser('~'), 'Library', 'Preferences',
'WellDone-MoMo'))
assert settings_dir == self.paths.settings | lgpl-3.0 |
aeph6Ee0/youtube-dl | youtube_dl/extractor/r7.py | 53 | 4600 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import int_or_none
class R7IE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://
(?:
(?:[a-zA-Z]+)\.r7\.com(?:/[^/]+)+/idmedia/|
noticias\.r7\.com(?:/[^/]+)+/[^/]+-|
player\.r7\.com/video/i/
)
(?P<id>[\da-f]{24})
'''
_TESTS = [{
'url': 'http://videos.r7.com/policiais-humilham-suspeito-a-beira-da-morte-morre-com-dignidade-/idmedia/54e7050b0cf2ff57e0279389.html',
'md5': '403c4e393617e8e8ddc748978ee8efde',
'info_dict': {
'id': '54e7050b0cf2ff57e0279389',
'ext': 'mp4',
'title': 'Policiais humilham suspeito à beira da morte: "Morre com dignidade"',
'description': 'md5:01812008664be76a6479aa58ec865b72',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 98,
'like_count': int,
'view_count': int,
},
}, {
'url': 'http://esportes.r7.com/videos/cigano-manda-recado-aos-fas/idmedia/4e176727b51a048ee6646a1b.html',
'only_matching': True,
}, {
'url': 'http://noticias.r7.com/record-news/video/representante-do-instituto-sou-da-paz-fala-sobre-fim-do-estatuto-do-desarmamento-5480fc580cf2285b117f438d/',
'only_matching': True,
}, {
'url': 'http://player.r7.com/video/i/54e7050b0cf2ff57e0279389?play=true&video=http://vsh.r7.com/54e7050b0cf2ff57e0279389/ER7_RE_BG_MORTE_JOVENS_570kbps_2015-02-2009f17818-cc82-4c8f-86dc-89a66934e633-ATOS_copy.mp4&linkCallback=http://videos.r7.com/policiais-humilham-suspeito-a-beira-da-morte-morre-com-dignidade-/idmedia/54e7050b0cf2ff57e0279389.html&thumbnail=http://vtb.r7.com/ER7_RE_BG_MORTE_JOVENS_570kbps_2015-02-2009f17818-cc82-4c8f-86dc-89a66934e633-thumb.jpg&idCategory=192&share=true&layout=full&full=true',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
video = self._download_json(
'http://player-api.r7.com/video/i/%s' % video_id, video_id)
title = video['title']
formats = []
media_url_hls = video.get('media_url_hls')
if media_url_hls:
formats.extend(self._extract_m3u8_formats(
media_url_hls, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
media_url = video.get('media_url')
if media_url:
f = {
'url': media_url,
'format_id': 'http',
}
# m3u8 format always matches the http format, let's copy metadata from
# one to another
m3u8_formats = list(filter(
lambda f: f.get('vcodec') != 'none', formats))
if len(m3u8_formats) == 1:
f_copy = m3u8_formats[0].copy()
f_copy.update(f)
f_copy['protocol'] = 'http'
f = f_copy
formats.append(f)
self._sort_formats(formats)
description = video.get('description')
thumbnail = video.get('thumb')
duration = int_or_none(video.get('media_duration'))
like_count = int_or_none(video.get('likes'))
view_count = int_or_none(video.get('views'))
return {
'id': video_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'duration': duration,
'like_count': like_count,
'view_count': view_count,
'formats': formats,
}
class R7ArticleIE(InfoExtractor):
_VALID_URL = r'https?://(?:[a-zA-Z]+)\.r7\.com/(?:[^/]+/)+[^/?#&]+-(?P<id>\d+)'
_TEST = {
'url': 'http://tv.r7.com/record-play/balanco-geral/videos/policiais-humilham-suspeito-a-beira-da-morte-morre-com-dignidade-16102015',
'only_matching': True,
}
@classmethod
def suitable(cls, url):
return False if R7IE.suitable(url) else super(R7ArticleIE, cls).suitable(url)
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
video_id = self._search_regex(
r'<div[^>]+(?:id=["\']player-|class=["\']embed["\'][^>]+id=["\'])([\da-f]{24})',
webpage, 'video id')
return self.url_result('http://player.r7.com/video/i/%s' % video_id, R7IE.ie_key())
| unlicense |
makhtardiouf/makhtardiouf.github.io | angularcode/node_modules/node-gyp/gyp/pylib/gyp/input.py | 713 | 115880 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from compiler.ast import Const
from compiler.ast import Dict
from compiler.ast import Discard
from compiler.ast import List
from compiler.ast import Module
from compiler.ast import Node
from compiler.ast import Stmt
import compiler
import gyp.common
import gyp.simple_copy
import multiprocessing
import optparse
import os.path
import re
import shlex
import signal
import subprocess
import sys
import threading
import time
import traceback
from gyp.common import GypError
from gyp.common import OrderedSet
# A list of types that are treated as linkable.
linkable_types = [
'executable',
'shared_library',
'loadable_module',
'mac_kernel_extension',
]
# A list of sections that contain links to other targets.
dependency_sections = ['dependencies', 'export_dependent_settings']
# base_path_sections is a list of sections defined by GYP that contain
# pathnames. The generators can provide more keys, the two lists are merged
# into path_sections, but you should call IsPathSection instead of using either
# list directly.
base_path_sections = [
'destination',
'files',
'include_dirs',
'inputs',
'libraries',
'outputs',
'sources',
]
path_sections = set()
# These per-process dictionaries are used to cache build file data when loading
# in parallel mode.
per_process_data = {}
per_process_aux_data = {}
def IsPathSection(section):
# If section ends in one of the '=+?!' characters, it's applied to a section
# without the trailing characters. '/' is notably absent from this list,
# because there's no way for a regular expression to be treated as a path.
while section and section[-1:] in '=+?!':
section = section[:-1]
if section in path_sections:
return True
# Sections mathing the regexp '_(dir|file|path)s?$' are also
# considered PathSections. Using manual string matching since that
# is much faster than the regexp and this can be called hundreds of
# thousands of times so micro performance matters.
if "_" in section:
tail = section[-6:]
if tail[-1] == 's':
tail = tail[:-1]
if tail[-5:] in ('_file', '_path'):
return True
return tail[-4:] == '_dir'
return False
# base_non_configuration_keys is a list of key names that belong in the target
# itself and should not be propagated into its configurations. It is merged
# with a list that can come from the generator to
# create non_configuration_keys.
base_non_configuration_keys = [
# Sections that must exist inside targets and not configurations.
'actions',
'configurations',
'copies',
'default_configuration',
'dependencies',
'dependencies_original',
'libraries',
'postbuilds',
'product_dir',
'product_extension',
'product_name',
'product_prefix',
'rules',
'run_as',
'sources',
'standalone_static_library',
'suppress_wildcard',
'target_name',
'toolset',
'toolsets',
'type',
# Sections that can be found inside targets or configurations, but that
# should not be propagated from targets into their configurations.
'variables',
]
non_configuration_keys = []
# Keys that do not belong inside a configuration dictionary.
invalid_configuration_keys = [
'actions',
'all_dependent_settings',
'configurations',
'dependencies',
'direct_dependent_settings',
'libraries',
'link_settings',
'sources',
'standalone_static_library',
'target_name',
'type',
]
# Controls whether or not the generator supports multiple toolsets.
multiple_toolsets = False
# Paths for converting filelist paths to output paths: {
# toplevel,
# qualified_output_dir,
# }
generator_filelist_paths = None
def GetIncludedBuildFiles(build_file_path, aux_data, included=None):
"""Return a list of all build files included into build_file_path.
The returned list will contain build_file_path as well as all other files
that it included, either directly or indirectly. Note that the list may
contain files that were included into a conditional section that evaluated
to false and was not merged into build_file_path's dict.
aux_data is a dict containing a key for each build file or included build
file. Those keys provide access to dicts whose "included" keys contain
lists of all other files included by the build file.
included should be left at its default None value by external callers. It
is used for recursion.
The returned list will not contain any duplicate entries. Each build file
in the list will be relative to the current directory.
"""
if included == None:
included = []
if build_file_path in included:
return included
included.append(build_file_path)
for included_build_file in aux_data[build_file_path].get('included', []):
GetIncludedBuildFiles(included_build_file, aux_data, included)
return included
def CheckedEval(file_contents):
"""Return the eval of a gyp file.
The gyp file is restricted to dictionaries and lists only, and
repeated keys are not allowed.
Note that this is slower than eval() is.
"""
ast = compiler.parse(file_contents)
assert isinstance(ast, Module)
c1 = ast.getChildren()
assert c1[0] is None
assert isinstance(c1[1], Stmt)
c2 = c1[1].getChildren()
assert isinstance(c2[0], Discard)
c3 = c2[0].getChildren()
assert len(c3) == 1
return CheckNode(c3[0], [])
def CheckNode(node, keypath):
if isinstance(node, Dict):
c = node.getChildren()
dict = {}
for n in range(0, len(c), 2):
assert isinstance(c[n], Const)
key = c[n].getChildren()[0]
if key in dict:
raise GypError("Key '" + key + "' repeated at level " +
repr(len(keypath) + 1) + " with key path '" +
'.'.join(keypath) + "'")
kp = list(keypath) # Make a copy of the list for descending this node.
kp.append(key)
dict[key] = CheckNode(c[n + 1], kp)
return dict
elif isinstance(node, List):
c = node.getChildren()
children = []
for index, child in enumerate(c):
kp = list(keypath) # Copy list.
kp.append(repr(index))
children.append(CheckNode(child, kp))
return children
elif isinstance(node, Const):
return node.getChildren()[0]
else:
raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) +
"': " + repr(node))
def LoadOneBuildFile(build_file_path, data, aux_data, includes,
is_target, check):
if build_file_path in data:
return data[build_file_path]
if os.path.exists(build_file_path):
build_file_contents = open(build_file_path).read()
else:
raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd()))
build_file_data = None
try:
if check:
build_file_data = CheckedEval(build_file_contents)
else:
build_file_data = eval(build_file_contents, {'__builtins__': None},
None)
except SyntaxError, e:
e.filename = build_file_path
raise
except Exception, e:
gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path)
raise
if type(build_file_data) is not dict:
raise GypError("%s does not evaluate to a dictionary." % build_file_path)
data[build_file_path] = build_file_data
aux_data[build_file_path] = {}
# Scan for includes and merge them in.
if ('skip_includes' not in build_file_data or
not build_file_data['skip_includes']):
try:
if is_target:
LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
aux_data, includes, check)
else:
LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data,
aux_data, None, check)
except Exception, e:
gyp.common.ExceptionAppend(e,
'while reading includes of ' + build_file_path)
raise
return build_file_data
def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data,
includes, check):
includes_list = []
if includes != None:
includes_list.extend(includes)
if 'includes' in subdict:
for include in subdict['includes']:
# "include" is specified relative to subdict_path, so compute the real
# path to include by appending the provided "include" to the directory
# in which subdict_path resides.
relative_include = \
os.path.normpath(os.path.join(os.path.dirname(subdict_path), include))
includes_list.append(relative_include)
# Unhook the includes list, it's no longer needed.
del subdict['includes']
# Merge in the included files.
for include in includes_list:
if not 'included' in aux_data[subdict_path]:
aux_data[subdict_path]['included'] = []
aux_data[subdict_path]['included'].append(include)
gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include)
MergeDicts(subdict,
LoadOneBuildFile(include, data, aux_data, None, False, check),
subdict_path, include)
# Recurse into subdictionaries.
for k, v in subdict.iteritems():
if type(v) is dict:
LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data,
None, check)
elif type(v) is list:
LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data,
check)
# This recurses into lists so that it can look for dicts.
def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check):
for item in sublist:
if type(item) is dict:
LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data,
None, check)
elif type(item) is list:
LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check)
# Processes toolsets in all the targets. This recurses into condition entries
# since they can contain toolsets as well.
def ProcessToolsetsInDict(data):
if 'targets' in data:
target_list = data['targets']
new_target_list = []
for target in target_list:
# If this target already has an explicit 'toolset', and no 'toolsets'
# list, don't modify it further.
if 'toolset' in target and 'toolsets' not in target:
new_target_list.append(target)
continue
if multiple_toolsets:
toolsets = target.get('toolsets', ['target'])
else:
toolsets = ['target']
# Make sure this 'toolsets' definition is only processed once.
if 'toolsets' in target:
del target['toolsets']
if len(toolsets) > 0:
# Optimization: only do copies if more than one toolset is specified.
for build in toolsets[1:]:
new_target = gyp.simple_copy.deepcopy(target)
new_target['toolset'] = build
new_target_list.append(new_target)
target['toolset'] = toolsets[0]
new_target_list.append(target)
data['targets'] = new_target_list
if 'conditions' in data:
for condition in data['conditions']:
if type(condition) is list:
for condition_dict in condition[1:]:
if type(condition_dict) is dict:
ProcessToolsetsInDict(condition_dict)
# TODO(mark): I don't love this name. It just means that it's going to load
# a build file that contains targets and is expected to provide a targets dict
# that contains the targets...
def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes,
depth, check, load_dependencies):
# If depth is set, predefine the DEPTH variable to be a relative path from
# this build file's directory to the directory identified by depth.
if depth:
# TODO(dglazkov) The backslash/forward-slash replacement at the end is a
# temporary measure. This should really be addressed by keeping all paths
# in POSIX until actual project generation.
d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path))
if d == '':
variables['DEPTH'] = '.'
else:
variables['DEPTH'] = d.replace('\\', '/')
# The 'target_build_files' key is only set when loading target build files in
# the non-parallel code path, where LoadTargetBuildFile is called
# recursively. In the parallel code path, we don't need to check whether the
# |build_file_path| has already been loaded, because the 'scheduled' set in
# ParallelState guarantees that we never load the same |build_file_path|
# twice.
if 'target_build_files' in data:
if build_file_path in data['target_build_files']:
# Already loaded.
return False
data['target_build_files'].add(build_file_path)
gyp.DebugOutput(gyp.DEBUG_INCLUDES,
"Loading Target Build File '%s'", build_file_path)
build_file_data = LoadOneBuildFile(build_file_path, data, aux_data,
includes, True, check)
# Store DEPTH for later use in generators.
build_file_data['_DEPTH'] = depth
# Set up the included_files key indicating which .gyp files contributed to
# this target dict.
if 'included_files' in build_file_data:
raise GypError(build_file_path + ' must not contain included_files key')
included = GetIncludedBuildFiles(build_file_path, aux_data)
build_file_data['included_files'] = []
for included_file in included:
# included_file is relative to the current directory, but it needs to
# be made relative to build_file_path's directory.
included_relative = \
gyp.common.RelativePath(included_file,
os.path.dirname(build_file_path))
build_file_data['included_files'].append(included_relative)
# Do a first round of toolsets expansion so that conditions can be defined
# per toolset.
ProcessToolsetsInDict(build_file_data)
# Apply "pre"/"early" variable expansions and condition evaluations.
ProcessVariablesAndConditionsInDict(
build_file_data, PHASE_EARLY, variables, build_file_path)
# Since some toolsets might have been defined conditionally, perform
# a second round of toolsets expansion now.
ProcessToolsetsInDict(build_file_data)
# Look at each project's target_defaults dict, and merge settings into
# targets.
if 'target_defaults' in build_file_data:
if 'targets' not in build_file_data:
raise GypError("Unable to find targets in build file %s" %
build_file_path)
index = 0
while index < len(build_file_data['targets']):
# This procedure needs to give the impression that target_defaults is
# used as defaults, and the individual targets inherit from that.
# The individual targets need to be merged into the defaults. Make
# a deep copy of the defaults for each target, merge the target dict
# as found in the input file into that copy, and then hook up the
# copy with the target-specific data merged into it as the replacement
# target dict.
old_target_dict = build_file_data['targets'][index]
new_target_dict = gyp.simple_copy.deepcopy(
build_file_data['target_defaults'])
MergeDicts(new_target_dict, old_target_dict,
build_file_path, build_file_path)
build_file_data['targets'][index] = new_target_dict
index += 1
# No longer needed.
del build_file_data['target_defaults']
# Look for dependencies. This means that dependency resolution occurs
# after "pre" conditionals and variable expansion, but before "post" -
# in other words, you can't put a "dependencies" section inside a "post"
# conditional within a target.
dependencies = []
if 'targets' in build_file_data:
for target_dict in build_file_data['targets']:
if 'dependencies' not in target_dict:
continue
for dependency in target_dict['dependencies']:
dependencies.append(
gyp.common.ResolveTarget(build_file_path, dependency, None)[0])
if load_dependencies:
for dependency in dependencies:
try:
LoadTargetBuildFile(dependency, data, aux_data, variables,
includes, depth, check, load_dependencies)
except Exception, e:
gyp.common.ExceptionAppend(
e, 'while loading dependencies of %s' % build_file_path)
raise
else:
return (build_file_path, dependencies)
def CallLoadTargetBuildFile(global_flags,
build_file_path, variables,
includes, depth, check,
generator_input_info):
"""Wrapper around LoadTargetBuildFile for parallel processing.
This wrapper is used when LoadTargetBuildFile is executed in
a worker process.
"""
try:
signal.signal(signal.SIGINT, signal.SIG_IGN)
# Apply globals so that the worker process behaves the same.
for key, value in global_flags.iteritems():
globals()[key] = value
SetGeneratorGlobals(generator_input_info)
result = LoadTargetBuildFile(build_file_path, per_process_data,
per_process_aux_data, variables,
includes, depth, check, False)
if not result:
return result
(build_file_path, dependencies) = result
# We can safely pop the build_file_data from per_process_data because it
# will never be referenced by this process again, so we don't need to keep
# it in the cache.
build_file_data = per_process_data.pop(build_file_path)
# This gets serialized and sent back to the main process via a pipe.
# It's handled in LoadTargetBuildFileCallback.
return (build_file_path,
build_file_data,
dependencies)
except GypError, e:
sys.stderr.write("gyp: %s\n" % e)
return None
except Exception, e:
print >>sys.stderr, 'Exception:', e
print >>sys.stderr, traceback.format_exc()
return None
class ParallelProcessingError(Exception):
pass
class ParallelState(object):
"""Class to keep track of state when processing input files in parallel.
If build files are loaded in parallel, use this to keep track of
state during farming out and processing parallel jobs. It's stored
in a global so that the callback function can have access to it.
"""
def __init__(self):
# The multiprocessing pool.
self.pool = None
# The condition variable used to protect this object and notify
# the main loop when there might be more data to process.
self.condition = None
# The "data" dict that was passed to LoadTargetBuildFileParallel
self.data = None
# The number of parallel calls outstanding; decremented when a response
# was received.
self.pending = 0
# The set of all build files that have been scheduled, so we don't
# schedule the same one twice.
self.scheduled = set()
# A list of dependency build file paths that haven't been scheduled yet.
self.dependencies = []
# Flag to indicate if there was an error in a child process.
self.error = False
def LoadTargetBuildFileCallback(self, result):
"""Handle the results of running LoadTargetBuildFile in another process.
"""
self.condition.acquire()
if not result:
self.error = True
self.condition.notify()
self.condition.release()
return
(build_file_path0, build_file_data0, dependencies0) = result
self.data[build_file_path0] = build_file_data0
self.data['target_build_files'].add(build_file_path0)
for new_dependency in dependencies0:
if new_dependency not in self.scheduled:
self.scheduled.add(new_dependency)
self.dependencies.append(new_dependency)
self.pending -= 1
self.condition.notify()
self.condition.release()
def LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth,
check, generator_input_info):
parallel_state = ParallelState()
parallel_state.condition = threading.Condition()
# Make copies of the build_files argument that we can modify while working.
parallel_state.dependencies = list(build_files)
parallel_state.scheduled = set(build_files)
parallel_state.pending = 0
parallel_state.data = data
try:
parallel_state.condition.acquire()
while parallel_state.dependencies or parallel_state.pending:
if parallel_state.error:
break
if not parallel_state.dependencies:
parallel_state.condition.wait()
continue
dependency = parallel_state.dependencies.pop()
parallel_state.pending += 1
global_flags = {
'path_sections': globals()['path_sections'],
'non_configuration_keys': globals()['non_configuration_keys'],
'multiple_toolsets': globals()['multiple_toolsets']}
if not parallel_state.pool:
parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count())
parallel_state.pool.apply_async(
CallLoadTargetBuildFile,
args = (global_flags, dependency,
variables, includes, depth, check, generator_input_info),
callback = parallel_state.LoadTargetBuildFileCallback)
except KeyboardInterrupt, e:
parallel_state.pool.terminate()
raise e
parallel_state.condition.release()
parallel_state.pool.close()
parallel_state.pool.join()
parallel_state.pool = None
if parallel_state.error:
sys.exit(1)
# Look for the bracket that matches the first bracket seen in a
# string, and return the start and end as a tuple. For example, if
# the input is something like "<(foo <(bar)) blah", then it would
# return (1, 13), indicating the entire string except for the leading
# "<" and trailing " blah".
LBRACKETS= set('{[(')
BRACKETS = {'}': '{', ']': '[', ')': '('}
def FindEnclosingBracketGroup(input_str):
stack = []
start = -1
for index, char in enumerate(input_str):
if char in LBRACKETS:
stack.append(char)
if start == -1:
start = index
elif char in BRACKETS:
if not stack:
return (-1, -1)
if stack.pop() != BRACKETS[char]:
return (-1, -1)
if not stack:
return (start, index + 1)
return (-1, -1)
def IsStrCanonicalInt(string):
"""Returns True if |string| is in its canonical integer form.
The canonical form is such that str(int(string)) == string.
"""
if type(string) is str:
# This function is called a lot so for maximum performance, avoid
# involving regexps which would otherwise make the code much
# shorter. Regexps would need twice the time of this function.
if string:
if string == "0":
return True
if string[0] == "-":
string = string[1:]
if not string:
return False
if '1' <= string[0] <= '9':
return string.isdigit()
return False
# This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)",
# "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())".
# In the last case, the inner "<()" is captured in match['content'].
early_variable_re = re.compile(
r'(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)'
r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
r'\((?P<is_array>\s*\[?)'
r'(?P<content>.*?)(\]?)\))')
# This matches the same as early_variable_re, but with '>' instead of '<'.
late_variable_re = re.compile(
r'(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)'
r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
r'\((?P<is_array>\s*\[?)'
r'(?P<content>.*?)(\]?)\))')
# This matches the same as early_variable_re, but with '^' instead of '<'.
latelate_variable_re = re.compile(
r'(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)'
r'(?P<command_string>[-a-zA-Z0-9_.]+)?'
r'\((?P<is_array>\s*\[?)'
r'(?P<content>.*?)(\]?)\))')
# Global cache of results from running commands so they don't have to be run
# more then once.
cached_command_results = {}
def FixupPlatformCommand(cmd):
if sys.platform == 'win32':
if type(cmd) is list:
cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:]
else:
cmd = re.sub('^cat ', 'type ', cmd)
return cmd
PHASE_EARLY = 0
PHASE_LATE = 1
PHASE_LATELATE = 2
def ExpandVariables(input, phase, variables, build_file):
# Look for the pattern that gets expanded into variables
if phase == PHASE_EARLY:
variable_re = early_variable_re
expansion_symbol = '<'
elif phase == PHASE_LATE:
variable_re = late_variable_re
expansion_symbol = '>'
elif phase == PHASE_LATELATE:
variable_re = latelate_variable_re
expansion_symbol = '^'
else:
assert False
input_str = str(input)
if IsStrCanonicalInt(input_str):
return int(input_str)
# Do a quick scan to determine if an expensive regex search is warranted.
if expansion_symbol not in input_str:
return input_str
# Get the entire list of matches as a list of MatchObject instances.
# (using findall here would return strings instead of MatchObjects).
matches = list(variable_re.finditer(input_str))
if not matches:
return input_str
output = input_str
# Reverse the list of matches so that replacements are done right-to-left.
# That ensures that earlier replacements won't mess up the string in a
# way that causes later calls to find the earlier substituted text instead
# of what's intended for replacement.
matches.reverse()
for match_group in matches:
match = match_group.groupdict()
gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match)
# match['replace'] is the substring to look for, match['type']
# is the character code for the replacement type (< > <! >! <| >| <@
# >@ <!@ >!@), match['is_array'] contains a '[' for command
# arrays, and match['content'] is the name of the variable (< >)
# or command to run (<! >!). match['command_string'] is an optional
# command string. Currently, only 'pymod_do_main' is supported.
# run_command is true if a ! variant is used.
run_command = '!' in match['type']
command_string = match['command_string']
# file_list is true if a | variant is used.
file_list = '|' in match['type']
# Capture these now so we can adjust them later.
replace_start = match_group.start('replace')
replace_end = match_group.end('replace')
# Find the ending paren, and re-evaluate the contained string.
(c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:])
# Adjust the replacement range to match the entire command
# found by FindEnclosingBracketGroup (since the variable_re
# probably doesn't match the entire command if it contained
# nested variables).
replace_end = replace_start + c_end
# Find the "real" replacement, matching the appropriate closing
# paren, and adjust the replacement start and end.
replacement = input_str[replace_start:replace_end]
# Figure out what the contents of the variable parens are.
contents_start = replace_start + c_start + 1
contents_end = replace_end - 1
contents = input_str[contents_start:contents_end]
# Do filter substitution now for <|().
# Admittedly, this is different than the evaluation order in other
# contexts. However, since filtration has no chance to run on <|(),
# this seems like the only obvious way to give them access to filters.
if file_list:
processed_variables = gyp.simple_copy.deepcopy(variables)
ProcessListFiltersInDict(contents, processed_variables)
# Recurse to expand variables in the contents
contents = ExpandVariables(contents, phase,
processed_variables, build_file)
else:
# Recurse to expand variables in the contents
contents = ExpandVariables(contents, phase, variables, build_file)
# Strip off leading/trailing whitespace so that variable matches are
# simpler below (and because they are rarely needed).
contents = contents.strip()
# expand_to_list is true if an @ variant is used. In that case,
# the expansion should result in a list. Note that the caller
# is to be expecting a list in return, and not all callers do
# because not all are working in list context. Also, for list
# expansions, there can be no other text besides the variable
# expansion in the input string.
expand_to_list = '@' in match['type'] and input_str == replacement
if run_command or file_list:
# Find the build file's directory, so commands can be run or file lists
# generated relative to it.
build_file_dir = os.path.dirname(build_file)
if build_file_dir == '' and not file_list:
# If build_file is just a leaf filename indicating a file in the
# current directory, build_file_dir might be an empty string. Set
# it to None to signal to subprocess.Popen that it should run the
# command in the current directory.
build_file_dir = None
# Support <|(listfile.txt ...) which generates a file
# containing items from a gyp list, generated at gyp time.
# This works around actions/rules which have more inputs than will
# fit on the command line.
if file_list:
if type(contents) is list:
contents_list = contents
else:
contents_list = contents.split(' ')
replacement = contents_list[0]
if os.path.isabs(replacement):
raise GypError('| cannot handle absolute paths, got "%s"' % replacement)
if not generator_filelist_paths:
path = os.path.join(build_file_dir, replacement)
else:
if os.path.isabs(build_file_dir):
toplevel = generator_filelist_paths['toplevel']
rel_build_file_dir = gyp.common.RelativePath(build_file_dir, toplevel)
else:
rel_build_file_dir = build_file_dir
qualified_out_dir = generator_filelist_paths['qualified_out_dir']
path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
gyp.common.EnsureDirExists(path)
replacement = gyp.common.RelativePath(path, build_file_dir)
f = gyp.common.WriteOnDiff(path)
for i in contents_list[1:]:
f.write('%s\n' % i)
f.close()
elif run_command:
use_shell = True
if match['is_array']:
contents = eval(contents)
use_shell = False
# Check for a cached value to avoid executing commands, or generating
# file lists more than once. The cache key contains the command to be
# run as well as the directory to run it from, to account for commands
# that depend on their current directory.
# TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
# someone could author a set of GYP files where each time the command
# is invoked it produces different output by design. When the need
# arises, the syntax should be extended to support no caching off a
# command's output so it is run every time.
cache_key = (str(contents), build_file_dir)
cached_value = cached_command_results.get(cache_key, None)
if cached_value is None:
gyp.DebugOutput(gyp.DEBUG_VARIABLES,
"Executing command '%s' in directory '%s'",
contents, build_file_dir)
replacement = ''
if command_string == 'pymod_do_main':
# <!pymod_do_main(modulename param eters) loads |modulename| as a
# python module and then calls that module's DoMain() function,
# passing ["param", "eters"] as a single list argument. For modules
# that don't load quickly, this can be faster than
# <!(python modulename param eters). Do this in |build_file_dir|.
oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
if build_file_dir: # build_file_dir may be None (see above).
os.chdir(build_file_dir)
try:
parsed_contents = shlex.split(contents)
try:
py_module = __import__(parsed_contents[0])
except ImportError as e:
raise GypError("Error importing pymod_do_main"
"module (%s): %s" % (parsed_contents[0], e))
replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip()
finally:
os.chdir(oldwd)
assert replacement != None
elif command_string:
raise GypError("Unknown command string '%s' in '%s'." %
(command_string, contents))
else:
# Fix up command with platform specific workarounds.
contents = FixupPlatformCommand(contents)
try:
p = subprocess.Popen(contents, shell=use_shell,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
cwd=build_file_dir)
except Exception, e:
raise GypError("%s while executing command '%s' in %s" %
(e, contents, build_file))
p_stdout, p_stderr = p.communicate('')
if p.wait() != 0 or p_stderr:
sys.stderr.write(p_stderr)
# Simulate check_call behavior, since check_call only exists
# in python 2.5 and later.
raise GypError("Call to '%s' returned exit status %d while in %s." %
(contents, p.returncode, build_file))
replacement = p_stdout.rstrip()
cached_command_results[cache_key] = replacement
else:
gyp.DebugOutput(gyp.DEBUG_VARIABLES,
"Had cache value for command '%s' in directory '%s'",
contents,build_file_dir)
replacement = cached_value
else:
if not contents in variables:
if contents[-1] in ['!', '/']:
# In order to allow cross-compiles (nacl) to happen more naturally,
# we will allow references to >(sources/) etc. to resolve to
# and empty list if undefined. This allows actions to:
# 'action!': [
# '>@(_sources!)',
# ],
# 'action/': [
# '>@(_sources/)',
# ],
replacement = []
else:
raise GypError('Undefined variable ' + contents +
' in ' + build_file)
else:
replacement = variables[contents]
if type(replacement) is list:
for item in replacement:
if not contents[-1] == '/' and type(item) not in (str, int):
raise GypError('Variable ' + contents +
' must expand to a string or list of strings; ' +
'list contains a ' +
item.__class__.__name__)
# Run through the list and handle variable expansions in it. Since
# the list is guaranteed not to contain dicts, this won't do anything
# with conditions sections.
ProcessVariablesAndConditionsInList(replacement, phase, variables,
build_file)
elif type(replacement) not in (str, int):
raise GypError('Variable ' + contents +
' must expand to a string or list of strings; ' +
'found a ' + replacement.__class__.__name__)
if expand_to_list:
# Expanding in list context. It's guaranteed that there's only one
# replacement to do in |input_str| and that it's this replacement. See
# above.
if type(replacement) is list:
# If it's already a list, make a copy.
output = replacement[:]
else:
# Split it the same way sh would split arguments.
output = shlex.split(str(replacement))
else:
# Expanding in string context.
encoded_replacement = ''
if type(replacement) is list:
# When expanding a list into string context, turn the list items
# into a string in a way that will work with a subprocess call.
#
# TODO(mark): This isn't completely correct. This should
# call a generator-provided function that observes the
# proper list-to-argument quoting rules on a specific
# platform instead of just calling the POSIX encoding
# routine.
encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
else:
encoded_replacement = replacement
output = output[:replace_start] + str(encoded_replacement) + \
output[replace_end:]
# Prepare for the next match iteration.
input_str = output
if output == input:
gyp.DebugOutput(gyp.DEBUG_VARIABLES,
"Found only identity matches on %r, avoiding infinite "
"recursion.",
output)
else:
# Look for more matches now that we've replaced some, to deal with
# expanding local variables (variables defined in the same
# variables block as this one).
gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output)
if type(output) is list:
if output and type(output[0]) is list:
# Leave output alone if it's a list of lists.
# We don't want such lists to be stringified.
pass
else:
new_output = []
for item in output:
new_output.append(
ExpandVariables(item, phase, variables, build_file))
output = new_output
else:
output = ExpandVariables(output, phase, variables, build_file)
# Convert all strings that are canonically-represented integers into integers.
if type(output) is list:
for index in xrange(0, len(output)):
if IsStrCanonicalInt(output[index]):
output[index] = int(output[index])
elif IsStrCanonicalInt(output):
output = int(output)
return output
# The same condition is often evaluated over and over again so it
# makes sense to cache as much as possible between evaluations.
cached_conditions_asts = {}
def EvalCondition(condition, conditions_key, phase, variables, build_file):
"""Returns the dict that should be used or None if the result was
that nothing should be used."""
if type(condition) is not list:
raise GypError(conditions_key + ' must be a list')
if len(condition) < 2:
# It's possible that condition[0] won't work in which case this
# attempt will raise its own IndexError. That's probably fine.
raise GypError(conditions_key + ' ' + condition[0] +
' must be at least length 2, not ' + str(len(condition)))
i = 0
result = None
while i < len(condition):
cond_expr = condition[i]
true_dict = condition[i + 1]
if type(true_dict) is not dict:
raise GypError('{} {} must be followed by a dictionary, not {}'.format(
conditions_key, cond_expr, type(true_dict)))
if len(condition) > i + 2 and type(condition[i + 2]) is dict:
false_dict = condition[i + 2]
i = i + 3
if i != len(condition):
raise GypError('{} {} has {} unexpected trailing items'.format(
conditions_key, cond_expr, len(condition) - i))
else:
false_dict = None
i = i + 2
if result == None:
result = EvalSingleCondition(
cond_expr, true_dict, false_dict, phase, variables, build_file)
return result
def EvalSingleCondition(
cond_expr, true_dict, false_dict, phase, variables, build_file):
"""Returns true_dict if cond_expr evaluates to true, and false_dict
otherwise."""
# Do expansions on the condition itself. Since the conditon can naturally
# contain variable references without needing to resort to GYP expansion
# syntax, this is of dubious value for variables, but someone might want to
# use a command expansion directly inside a condition.
cond_expr_expanded = ExpandVariables(cond_expr, phase, variables,
build_file)
if type(cond_expr_expanded) not in (str, int):
raise ValueError(
'Variable expansion in this context permits str and int ' + \
'only, found ' + cond_expr_expanded.__class__.__name__)
try:
if cond_expr_expanded in cached_conditions_asts:
ast_code = cached_conditions_asts[cond_expr_expanded]
else:
ast_code = compile(cond_expr_expanded, '<string>', 'eval')
cached_conditions_asts[cond_expr_expanded] = ast_code
if eval(ast_code, {'__builtins__': None}, variables):
return true_dict
return false_dict
except SyntaxError, e:
syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s '
'at character %d.' %
(str(e.args[0]), e.text, build_file, e.offset),
e.filename, e.lineno, e.offset, e.text)
raise syntax_error
except NameError, e:
gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' %
(cond_expr_expanded, build_file))
raise GypError(e)
def ProcessConditionsInDict(the_dict, phase, variables, build_file):
# Process a 'conditions' or 'target_conditions' section in the_dict,
# depending on phase.
# early -> conditions
# late -> target_conditions
# latelate -> no conditions
#
# Each item in a conditions list consists of cond_expr, a string expression
# evaluated as the condition, and true_dict, a dict that will be merged into
# the_dict if cond_expr evaluates to true. Optionally, a third item,
# false_dict, may be present. false_dict is merged into the_dict if
# cond_expr evaluates to false.
#
# Any dict merged into the_dict will be recursively processed for nested
# conditionals and other expansions, also according to phase, immediately
# prior to being merged.
if phase == PHASE_EARLY:
conditions_key = 'conditions'
elif phase == PHASE_LATE:
conditions_key = 'target_conditions'
elif phase == PHASE_LATELATE:
return
else:
assert False
if not conditions_key in the_dict:
return
conditions_list = the_dict[conditions_key]
# Unhook the conditions list, it's no longer needed.
del the_dict[conditions_key]
for condition in conditions_list:
merge_dict = EvalCondition(condition, conditions_key, phase, variables,
build_file)
if merge_dict != None:
# Expand variables and nested conditinals in the merge_dict before
# merging it.
ProcessVariablesAndConditionsInDict(merge_dict, phase,
variables, build_file)
MergeDicts(the_dict, merge_dict, build_file, build_file)
def LoadAutomaticVariablesFromDict(variables, the_dict):
# Any keys with plain string values in the_dict become automatic variables.
# The variable name is the key name with a "_" character prepended.
for key, value in the_dict.iteritems():
if type(value) in (str, int, list):
variables['_' + key] = value
def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
# Any keys in the_dict's "variables" dict, if it has one, becomes a
# variable. The variable name is the key name in the "variables" dict.
# Variables that end with the % character are set only if they are unset in
# the variables dict. the_dict_key is the name of the key that accesses
# the_dict in the_dict's parent dict. If the_dict's parent is not a dict
# (it could be a list or it could be parentless because it is a root dict),
# the_dict_key will be None.
for key, value in the_dict.get('variables', {}).iteritems():
if type(value) not in (str, int, list):
continue
if key.endswith('%'):
variable_name = key[:-1]
if variable_name in variables:
# If the variable is already set, don't set it.
continue
if the_dict_key is 'variables' and variable_name in the_dict:
# If the variable is set without a % in the_dict, and the_dict is a
# variables dict (making |variables| a varaibles sub-dict of a
# variables dict), use the_dict's definition.
value = the_dict[variable_name]
else:
variable_name = key
variables[variable_name] = value
def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in,
build_file, the_dict_key=None):
"""Handle all variable and command expansion and conditional evaluation.
This function is the public entry point for all variable expansions and
conditional evaluations. The variables_in dictionary will not be modified
by this function.
"""
# Make a copy of the variables_in dict that can be modified during the
# loading of automatics and the loading of the variables dict.
variables = variables_in.copy()
LoadAutomaticVariablesFromDict(variables, the_dict)
if 'variables' in the_dict:
# Make sure all the local variables are added to the variables
# list before we process them so that you can reference one
# variable from another. They will be fully expanded by recursion
# in ExpandVariables.
for key, value in the_dict['variables'].iteritems():
variables[key] = value
# Handle the associated variables dict first, so that any variable
# references within can be resolved prior to using them as variables.
# Pass a copy of the variables dict to avoid having it be tainted.
# Otherwise, it would have extra automatics added for everything that
# should just be an ordinary variable in this scope.
ProcessVariablesAndConditionsInDict(the_dict['variables'], phase,
variables, build_file, 'variables')
LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
for key, value in the_dict.iteritems():
# Skip "variables", which was already processed if present.
if key != 'variables' and type(value) is str:
expanded = ExpandVariables(value, phase, variables, build_file)
if type(expanded) not in (str, int):
raise ValueError(
'Variable expansion in this context permits str and int ' + \
'only, found ' + expanded.__class__.__name__ + ' for ' + key)
the_dict[key] = expanded
# Variable expansion may have resulted in changes to automatics. Reload.
# TODO(mark): Optimization: only reload if no changes were made.
variables = variables_in.copy()
LoadAutomaticVariablesFromDict(variables, the_dict)
LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
# Process conditions in this dict. This is done after variable expansion
# so that conditions may take advantage of expanded variables. For example,
# if the_dict contains:
# {'type': '<(library_type)',
# 'conditions': [['_type=="static_library"', { ... }]]},
# _type, as used in the condition, will only be set to the value of
# library_type if variable expansion is performed before condition
# processing. However, condition processing should occur prior to recursion
# so that variables (both automatic and "variables" dict type) may be
# adjusted by conditions sections, merged into the_dict, and have the
# intended impact on contained dicts.
#
# This arrangement means that a "conditions" section containing a "variables"
# section will only have those variables effective in subdicts, not in
# the_dict. The workaround is to put a "conditions" section within a
# "variables" section. For example:
# {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
# 'defines': ['<(define)'],
# 'my_subdict': {'defines': ['<(define)']}},
# will not result in "IS_MAC" being appended to the "defines" list in the
# current scope but would result in it being appended to the "defines" list
# within "my_subdict". By comparison:
# {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
# 'defines': ['<(define)'],
# 'my_subdict': {'defines': ['<(define)']}},
# will append "IS_MAC" to both "defines" lists.
# Evaluate conditions sections, allowing variable expansions within them
# as well as nested conditionals. This will process a 'conditions' or
# 'target_conditions' section, perform appropriate merging and recursive
# conditional and variable processing, and then remove the conditions section
# from the_dict if it is present.
ProcessConditionsInDict(the_dict, phase, variables, build_file)
# Conditional processing may have resulted in changes to automatics or the
# variables dict. Reload.
variables = variables_in.copy()
LoadAutomaticVariablesFromDict(variables, the_dict)
LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
# Recurse into child dicts, or process child lists which may result in
# further recursion into descendant dicts.
for key, value in the_dict.iteritems():
# Skip "variables" and string values, which were already processed if
# present.
if key == 'variables' or type(value) is str:
continue
if type(value) is dict:
# Pass a copy of the variables dict so that subdicts can't influence
# parents.
ProcessVariablesAndConditionsInDict(value, phase, variables,
build_file, key)
elif type(value) is list:
# The list itself can't influence the variables dict, and
# ProcessVariablesAndConditionsInList will make copies of the variables
# dict if it needs to pass it to something that can influence it. No
# copy is necessary here.
ProcessVariablesAndConditionsInList(value, phase, variables,
build_file)
elif type(value) is not int:
raise TypeError('Unknown type ' + value.__class__.__name__ + \
' for ' + key)
def ProcessVariablesAndConditionsInList(the_list, phase, variables,
build_file):
# Iterate using an index so that new values can be assigned into the_list.
index = 0
while index < len(the_list):
item = the_list[index]
if type(item) is dict:
# Make a copy of the variables dict so that it won't influence anything
# outside of its own scope.
ProcessVariablesAndConditionsInDict(item, phase, variables, build_file)
elif type(item) is list:
ProcessVariablesAndConditionsInList(item, phase, variables, build_file)
elif type(item) is str:
expanded = ExpandVariables(item, phase, variables, build_file)
if type(expanded) in (str, int):
the_list[index] = expanded
elif type(expanded) is list:
the_list[index:index+1] = expanded
index += len(expanded)
# index now identifies the next item to examine. Continue right now
# without falling into the index increment below.
continue
else:
raise ValueError(
'Variable expansion in this context permits strings and ' + \
'lists only, found ' + expanded.__class__.__name__ + ' at ' + \
index)
elif type(item) is not int:
raise TypeError('Unknown type ' + item.__class__.__name__ + \
' at index ' + index)
index = index + 1
def BuildTargetsDict(data):
"""Builds a dict mapping fully-qualified target names to their target dicts.
|data| is a dict mapping loaded build files by pathname relative to the
current directory. Values in |data| are build file contents. For each
|data| value with a "targets" key, the value of the "targets" key is taken
as a list containing target dicts. Each target's fully-qualified name is
constructed from the pathname of the build file (|data| key) and its
"target_name" property. These fully-qualified names are used as the keys
in the returned dict. These keys provide access to the target dicts,
the dicts in the "targets" lists.
"""
targets = {}
for build_file in data['target_build_files']:
for target in data[build_file].get('targets', []):
target_name = gyp.common.QualifiedTarget(build_file,
target['target_name'],
target['toolset'])
if target_name in targets:
raise GypError('Duplicate target definitions for ' + target_name)
targets[target_name] = target
return targets
def QualifyDependencies(targets):
"""Make dependency links fully-qualified relative to the current directory.
|targets| is a dict mapping fully-qualified target names to their target
dicts. For each target in this dict, keys known to contain dependency
links are examined, and any dependencies referenced will be rewritten
so that they are fully-qualified and relative to the current directory.
All rewritten dependencies are suitable for use as keys to |targets| or a
similar dict.
"""
all_dependency_sections = [dep + op
for dep in dependency_sections
for op in ('', '!', '/')]
for target, target_dict in targets.iteritems():
target_build_file = gyp.common.BuildFile(target)
toolset = target_dict['toolset']
for dependency_key in all_dependency_sections:
dependencies = target_dict.get(dependency_key, [])
for index in xrange(0, len(dependencies)):
dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
target_build_file, dependencies[index], toolset)
if not multiple_toolsets:
# Ignore toolset specification in the dependency if it is specified.
dep_toolset = toolset
dependency = gyp.common.QualifiedTarget(dep_file,
dep_target,
dep_toolset)
dependencies[index] = dependency
# Make sure anything appearing in a list other than "dependencies" also
# appears in the "dependencies" list.
if dependency_key != 'dependencies' and \
dependency not in target_dict['dependencies']:
raise GypError('Found ' + dependency + ' in ' + dependency_key +
' of ' + target + ', but not in dependencies')
def ExpandWildcardDependencies(targets, data):
"""Expands dependencies specified as build_file:*.
For each target in |targets|, examines sections containing links to other
targets. If any such section contains a link of the form build_file:*, it
is taken as a wildcard link, and is expanded to list each target in
build_file. The |data| dict provides access to build file dicts.
Any target that does not wish to be included by wildcard can provide an
optional "suppress_wildcard" key in its target dict. When present and
true, a wildcard dependency link will not include such targets.
All dependency names, including the keys to |targets| and the values in each
dependency list, must be qualified when this function is called.
"""
for target, target_dict in targets.iteritems():
toolset = target_dict['toolset']
target_build_file = gyp.common.BuildFile(target)
for dependency_key in dependency_sections:
dependencies = target_dict.get(dependency_key, [])
# Loop this way instead of "for dependency in" or "for index in xrange"
# because the dependencies list will be modified within the loop body.
index = 0
while index < len(dependencies):
(dependency_build_file, dependency_target, dependency_toolset) = \
gyp.common.ParseQualifiedTarget(dependencies[index])
if dependency_target != '*' and dependency_toolset != '*':
# Not a wildcard. Keep it moving.
index = index + 1
continue
if dependency_build_file == target_build_file:
# It's an error for a target to depend on all other targets in
# the same file, because a target cannot depend on itself.
raise GypError('Found wildcard in ' + dependency_key + ' of ' +
target + ' referring to same build file')
# Take the wildcard out and adjust the index so that the next
# dependency in the list will be processed the next time through the
# loop.
del dependencies[index]
index = index - 1
# Loop through the targets in the other build file, adding them to
# this target's list of dependencies in place of the removed
# wildcard.
dependency_target_dicts = data[dependency_build_file]['targets']
for dependency_target_dict in dependency_target_dicts:
if int(dependency_target_dict.get('suppress_wildcard', False)):
continue
dependency_target_name = dependency_target_dict['target_name']
if (dependency_target != '*' and
dependency_target != dependency_target_name):
continue
dependency_target_toolset = dependency_target_dict['toolset']
if (dependency_toolset != '*' and
dependency_toolset != dependency_target_toolset):
continue
dependency = gyp.common.QualifiedTarget(dependency_build_file,
dependency_target_name,
dependency_target_toolset)
index = index + 1
dependencies.insert(index, dependency)
index = index + 1
def Unify(l):
"""Removes duplicate elements from l, keeping the first element."""
seen = {}
return [seen.setdefault(e, e) for e in l if e not in seen]
def RemoveDuplicateDependencies(targets):
"""Makes sure every dependency appears only once in all targets's dependency
lists."""
for target_name, target_dict in targets.iteritems():
for dependency_key in dependency_sections:
dependencies = target_dict.get(dependency_key, [])
if dependencies:
target_dict[dependency_key] = Unify(dependencies)
def Filter(l, item):
"""Removes item from l."""
res = {}
return [res.setdefault(e, e) for e in l if e != item]
def RemoveSelfDependencies(targets):
"""Remove self dependencies from targets that have the prune_self_dependency
variable set."""
for target_name, target_dict in targets.iteritems():
for dependency_key in dependency_sections:
dependencies = target_dict.get(dependency_key, [])
if dependencies:
for t in dependencies:
if t == target_name:
if targets[t].get('variables', {}).get('prune_self_dependency', 0):
target_dict[dependency_key] = Filter(dependencies, target_name)
def RemoveLinkDependenciesFromNoneTargets(targets):
"""Remove dependencies having the 'link_dependency' attribute from the 'none'
targets."""
for target_name, target_dict in targets.iteritems():
for dependency_key in dependency_sections:
dependencies = target_dict.get(dependency_key, [])
if dependencies:
for t in dependencies:
if target_dict.get('type', None) == 'none':
if targets[t].get('variables', {}).get('link_dependency', 0):
target_dict[dependency_key] = \
Filter(target_dict[dependency_key], t)
class DependencyGraphNode(object):
"""
Attributes:
ref: A reference to an object that this DependencyGraphNode represents.
dependencies: List of DependencyGraphNodes on which this one depends.
dependents: List of DependencyGraphNodes that depend on this one.
"""
class CircularException(GypError):
pass
def __init__(self, ref):
self.ref = ref
self.dependencies = []
self.dependents = []
def __repr__(self):
return '<DependencyGraphNode: %r>' % self.ref
def FlattenToList(self):
# flat_list is the sorted list of dependencies - actually, the list items
# are the "ref" attributes of DependencyGraphNodes. Every target will
# appear in flat_list after all of its dependencies, and before all of its
# dependents.
flat_list = OrderedSet()
# in_degree_zeros is the list of DependencyGraphNodes that have no
# dependencies not in flat_list. Initially, it is a copy of the children
# of this node, because when the graph was built, nodes with no
# dependencies were made implicit dependents of the root node.
in_degree_zeros = set(self.dependents[:])
while in_degree_zeros:
# Nodes in in_degree_zeros have no dependencies not in flat_list, so they
# can be appended to flat_list. Take these nodes out of in_degree_zeros
# as work progresses, so that the next node to process from the list can
# always be accessed at a consistent position.
node = in_degree_zeros.pop()
flat_list.add(node.ref)
# Look at dependents of the node just added to flat_list. Some of them
# may now belong in in_degree_zeros.
for node_dependent in node.dependents:
is_in_degree_zero = True
# TODO: We want to check through the
# node_dependent.dependencies list but if it's long and we
# always start at the beginning, then we get O(n^2) behaviour.
for node_dependent_dependency in node_dependent.dependencies:
if not node_dependent_dependency.ref in flat_list:
# The dependent one or more dependencies not in flat_list. There
# will be more chances to add it to flat_list when examining
# it again as a dependent of those other dependencies, provided
# that there are no cycles.
is_in_degree_zero = False
break
if is_in_degree_zero:
# All of the dependent's dependencies are already in flat_list. Add
# it to in_degree_zeros where it will be processed in a future
# iteration of the outer loop.
in_degree_zeros.add(node_dependent)
return list(flat_list)
def FindCycles(self):
"""
Returns a list of cycles in the graph, where each cycle is its own list.
"""
results = []
visited = set()
def Visit(node, path):
for child in node.dependents:
if child in path:
results.append([child] + path[:path.index(child) + 1])
elif not child in visited:
visited.add(child)
Visit(child, [child] + path)
visited.add(self)
Visit(self, [self])
return results
def DirectDependencies(self, dependencies=None):
"""Returns a list of just direct dependencies."""
if dependencies == None:
dependencies = []
for dependency in self.dependencies:
# Check for None, corresponding to the root node.
if dependency.ref != None and dependency.ref not in dependencies:
dependencies.append(dependency.ref)
return dependencies
def _AddImportedDependencies(self, targets, dependencies=None):
"""Given a list of direct dependencies, adds indirect dependencies that
other dependencies have declared to export their settings.
This method does not operate on self. Rather, it operates on the list
of dependencies in the |dependencies| argument. For each dependency in
that list, if any declares that it exports the settings of one of its
own dependencies, those dependencies whose settings are "passed through"
are added to the list. As new items are added to the list, they too will
be processed, so it is possible to import settings through multiple levels
of dependencies.
This method is not terribly useful on its own, it depends on being
"primed" with a list of direct dependencies such as one provided by
DirectDependencies. DirectAndImportedDependencies is intended to be the
public entry point.
"""
if dependencies == None:
dependencies = []
index = 0
while index < len(dependencies):
dependency = dependencies[index]
dependency_dict = targets[dependency]
# Add any dependencies whose settings should be imported to the list
# if not already present. Newly-added items will be checked for
# their own imports when the list iteration reaches them.
# Rather than simply appending new items, insert them after the
# dependency that exported them. This is done to more closely match
# the depth-first method used by DeepDependencies.
add_index = 1
for imported_dependency in \
dependency_dict.get('export_dependent_settings', []):
if imported_dependency not in dependencies:
dependencies.insert(index + add_index, imported_dependency)
add_index = add_index + 1
index = index + 1
return dependencies
def DirectAndImportedDependencies(self, targets, dependencies=None):
"""Returns a list of a target's direct dependencies and all indirect
dependencies that a dependency has advertised settings should be exported
through the dependency for.
"""
dependencies = self.DirectDependencies(dependencies)
return self._AddImportedDependencies(targets, dependencies)
def DeepDependencies(self, dependencies=None):
"""Returns an OrderedSet of all of a target's dependencies, recursively."""
if dependencies is None:
# Using a list to get ordered output and a set to do fast "is it
# already added" checks.
dependencies = OrderedSet()
for dependency in self.dependencies:
# Check for None, corresponding to the root node.
if dependency.ref is None:
continue
if dependency.ref not in dependencies:
dependency.DeepDependencies(dependencies)
dependencies.add(dependency.ref)
return dependencies
def _LinkDependenciesInternal(self, targets, include_shared_libraries,
dependencies=None, initial=True):
"""Returns an OrderedSet of dependency targets that are linked
into this target.
This function has a split personality, depending on the setting of
|initial|. Outside callers should always leave |initial| at its default
setting.
When adding a target to the list of dependencies, this function will
recurse into itself with |initial| set to False, to collect dependencies
that are linked into the linkable target for which the list is being built.
If |include_shared_libraries| is False, the resulting dependencies will not
include shared_library targets that are linked into this target.
"""
if dependencies is None:
# Using a list to get ordered output and a set to do fast "is it
# already added" checks.
dependencies = OrderedSet()
# Check for None, corresponding to the root node.
if self.ref is None:
return dependencies
# It's kind of sucky that |targets| has to be passed into this function,
# but that's presently the easiest way to access the target dicts so that
# this function can find target types.
if 'target_name' not in targets[self.ref]:
raise GypError("Missing 'target_name' field in target.")
if 'type' not in targets[self.ref]:
raise GypError("Missing 'type' field in target %s" %
targets[self.ref]['target_name'])
target_type = targets[self.ref]['type']
is_linkable = target_type in linkable_types
if initial and not is_linkable:
# If this is the first target being examined and it's not linkable,
# return an empty list of link dependencies, because the link
# dependencies are intended to apply to the target itself (initial is
# True) and this target won't be linked.
return dependencies
# Don't traverse 'none' targets if explicitly excluded.
if (target_type == 'none' and
not targets[self.ref].get('dependencies_traverse', True)):
dependencies.add(self.ref)
return dependencies
# Executables, mac kernel extensions and loadable modules are already fully
# and finally linked. Nothing else can be a link dependency of them, there
# can only be dependencies in the sense that a dependent target might run
# an executable or load the loadable_module.
if not initial and target_type in ('executable', 'loadable_module',
'mac_kernel_extension'):
return dependencies
# Shared libraries are already fully linked. They should only be included
# in |dependencies| when adjusting static library dependencies (in order to
# link against the shared_library's import lib), but should not be included
# in |dependencies| when propagating link_settings.
# The |include_shared_libraries| flag controls which of these two cases we
# are handling.
if (not initial and target_type == 'shared_library' and
not include_shared_libraries):
return dependencies
# The target is linkable, add it to the list of link dependencies.
if self.ref not in dependencies:
dependencies.add(self.ref)
if initial or not is_linkable:
# If this is a subsequent target and it's linkable, don't look any
# further for linkable dependencies, as they'll already be linked into
# this target linkable. Always look at dependencies of the initial
# target, and always look at dependencies of non-linkables.
for dependency in self.dependencies:
dependency._LinkDependenciesInternal(targets,
include_shared_libraries,
dependencies, False)
return dependencies
def DependenciesForLinkSettings(self, targets):
"""
Returns a list of dependency targets whose link_settings should be merged
into this target.
"""
# TODO(sbaig) Currently, chrome depends on the bug that shared libraries'
# link_settings are propagated. So for now, we will allow it, unless the
# 'allow_sharedlib_linksettings_propagation' flag is explicitly set to
# False. Once chrome is fixed, we can remove this flag.
include_shared_libraries = \
targets[self.ref].get('allow_sharedlib_linksettings_propagation', True)
return self._LinkDependenciesInternal(targets, include_shared_libraries)
def DependenciesToLinkAgainst(self, targets):
"""
Returns a list of dependency targets that are linked into this target.
"""
return self._LinkDependenciesInternal(targets, True)
def BuildDependencyList(targets):
# Create a DependencyGraphNode for each target. Put it into a dict for easy
# access.
dependency_nodes = {}
for target, spec in targets.iteritems():
if target not in dependency_nodes:
dependency_nodes[target] = DependencyGraphNode(target)
# Set up the dependency links. Targets that have no dependencies are treated
# as dependent on root_node.
root_node = DependencyGraphNode(None)
for target, spec in targets.iteritems():
target_node = dependency_nodes[target]
target_build_file = gyp.common.BuildFile(target)
dependencies = spec.get('dependencies')
if not dependencies:
target_node.dependencies = [root_node]
root_node.dependents.append(target_node)
else:
for dependency in dependencies:
dependency_node = dependency_nodes.get(dependency)
if not dependency_node:
raise GypError("Dependency '%s' not found while "
"trying to load target %s" % (dependency, target))
target_node.dependencies.append(dependency_node)
dependency_node.dependents.append(target_node)
flat_list = root_node.FlattenToList()
# If there's anything left unvisited, there must be a circular dependency
# (cycle).
if len(flat_list) != len(targets):
if not root_node.dependents:
# If all targets have dependencies, add the first target as a dependent
# of root_node so that the cycle can be discovered from root_node.
target = targets.keys()[0]
target_node = dependency_nodes[target]
target_node.dependencies.append(root_node)
root_node.dependents.append(target_node)
cycles = []
for cycle in root_node.FindCycles():
paths = [node.ref for node in cycle]
cycles.append('Cycle: %s' % ' -> '.join(paths))
raise DependencyGraphNode.CircularException(
'Cycles in dependency graph detected:\n' + '\n'.join(cycles))
return [dependency_nodes, flat_list]
def VerifyNoGYPFileCircularDependencies(targets):
# Create a DependencyGraphNode for each gyp file containing a target. Put
# it into a dict for easy access.
dependency_nodes = {}
for target in targets.iterkeys():
build_file = gyp.common.BuildFile(target)
if not build_file in dependency_nodes:
dependency_nodes[build_file] = DependencyGraphNode(build_file)
# Set up the dependency links.
for target, spec in targets.iteritems():
build_file = gyp.common.BuildFile(target)
build_file_node = dependency_nodes[build_file]
target_dependencies = spec.get('dependencies', [])
for dependency in target_dependencies:
try:
dependency_build_file = gyp.common.BuildFile(dependency)
except GypError, e:
gyp.common.ExceptionAppend(
e, 'while computing dependencies of .gyp file %s' % build_file)
raise
if dependency_build_file == build_file:
# A .gyp file is allowed to refer back to itself.
continue
dependency_node = dependency_nodes.get(dependency_build_file)
if not dependency_node:
raise GypError("Dependancy '%s' not found" % dependency_build_file)
if dependency_node not in build_file_node.dependencies:
build_file_node.dependencies.append(dependency_node)
dependency_node.dependents.append(build_file_node)
# Files that have no dependencies are treated as dependent on root_node.
root_node = DependencyGraphNode(None)
for build_file_node in dependency_nodes.itervalues():
if len(build_file_node.dependencies) == 0:
build_file_node.dependencies.append(root_node)
root_node.dependents.append(build_file_node)
flat_list = root_node.FlattenToList()
# If there's anything left unvisited, there must be a circular dependency
# (cycle).
if len(flat_list) != len(dependency_nodes):
if not root_node.dependents:
# If all files have dependencies, add the first file as a dependent
# of root_node so that the cycle can be discovered from root_node.
file_node = dependency_nodes.values()[0]
file_node.dependencies.append(root_node)
root_node.dependents.append(file_node)
cycles = []
for cycle in root_node.FindCycles():
paths = [node.ref for node in cycle]
cycles.append('Cycle: %s' % ' -> '.join(paths))
raise DependencyGraphNode.CircularException(
'Cycles in .gyp file dependency graph detected:\n' + '\n'.join(cycles))
def DoDependentSettings(key, flat_list, targets, dependency_nodes):
# key should be one of all_dependent_settings, direct_dependent_settings,
# or link_settings.
for target in flat_list:
target_dict = targets[target]
build_file = gyp.common.BuildFile(target)
if key == 'all_dependent_settings':
dependencies = dependency_nodes[target].DeepDependencies()
elif key == 'direct_dependent_settings':
dependencies = \
dependency_nodes[target].DirectAndImportedDependencies(targets)
elif key == 'link_settings':
dependencies = \
dependency_nodes[target].DependenciesForLinkSettings(targets)
else:
raise GypError("DoDependentSettings doesn't know how to determine "
'dependencies for ' + key)
for dependency in dependencies:
dependency_dict = targets[dependency]
if not key in dependency_dict:
continue
dependency_build_file = gyp.common.BuildFile(dependency)
MergeDicts(target_dict, dependency_dict[key],
build_file, dependency_build_file)
def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
sort_dependencies):
# Recompute target "dependencies" properties. For each static library
# target, remove "dependencies" entries referring to other static libraries,
# unless the dependency has the "hard_dependency" attribute set. For each
# linkable target, add a "dependencies" entry referring to all of the
# target's computed list of link dependencies (including static libraries
# if no such entry is already present.
for target in flat_list:
target_dict = targets[target]
target_type = target_dict['type']
if target_type == 'static_library':
if not 'dependencies' in target_dict:
continue
target_dict['dependencies_original'] = target_dict.get(
'dependencies', [])[:]
# A static library should not depend on another static library unless
# the dependency relationship is "hard," which should only be done when
# a dependent relies on some side effect other than just the build
# product, like a rule or action output. Further, if a target has a
# non-hard dependency, but that dependency exports a hard dependency,
# the non-hard dependency can safely be removed, but the exported hard
# dependency must be added to the target to keep the same dependency
# ordering.
dependencies = \
dependency_nodes[target].DirectAndImportedDependencies(targets)
index = 0
while index < len(dependencies):
dependency = dependencies[index]
dependency_dict = targets[dependency]
# Remove every non-hard static library dependency and remove every
# non-static library dependency that isn't a direct dependency.
if (dependency_dict['type'] == 'static_library' and \
not dependency_dict.get('hard_dependency', False)) or \
(dependency_dict['type'] != 'static_library' and \
not dependency in target_dict['dependencies']):
# Take the dependency out of the list, and don't increment index
# because the next dependency to analyze will shift into the index
# formerly occupied by the one being removed.
del dependencies[index]
else:
index = index + 1
# Update the dependencies. If the dependencies list is empty, it's not
# needed, so unhook it.
if len(dependencies) > 0:
target_dict['dependencies'] = dependencies
else:
del target_dict['dependencies']
elif target_type in linkable_types:
# Get a list of dependency targets that should be linked into this
# target. Add them to the dependencies list if they're not already
# present.
link_dependencies = \
dependency_nodes[target].DependenciesToLinkAgainst(targets)
for dependency in link_dependencies:
if dependency == target:
continue
if not 'dependencies' in target_dict:
target_dict['dependencies'] = []
if not dependency in target_dict['dependencies']:
target_dict['dependencies'].append(dependency)
# Sort the dependencies list in the order from dependents to dependencies.
# e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
# Note: flat_list is already sorted in the order from dependencies to
# dependents.
if sort_dependencies and 'dependencies' in target_dict:
target_dict['dependencies'] = [dep for dep in reversed(flat_list)
if dep in target_dict['dependencies']]
# Initialize this here to speed up MakePathRelative.
exception_re = re.compile(r'''["']?[-/$<>^]''')
def MakePathRelative(to_file, fro_file, item):
# If item is a relative path, it's relative to the build file dict that it's
# coming from. Fix it up to make it relative to the build file dict that
# it's going into.
# Exception: any |item| that begins with these special characters is
# returned without modification.
# / Used when a path is already absolute (shortcut optimization;
# such paths would be returned as absolute anyway)
# $ Used for build environment variables
# - Used for some build environment flags (such as -lapr-1 in a
# "libraries" section)
# < Used for our own variable and command expansions (see ExpandVariables)
# > Used for our own variable and command expansions (see ExpandVariables)
# ^ Used for our own variable and command expansions (see ExpandVariables)
#
# "/' Used when a value is quoted. If these are present, then we
# check the second character instead.
#
if to_file == fro_file or exception_re.match(item):
return item
else:
# TODO(dglazkov) The backslash/forward-slash replacement at the end is a
# temporary measure. This should really be addressed by keeping all paths
# in POSIX until actual project generation.
ret = os.path.normpath(os.path.join(
gyp.common.RelativePath(os.path.dirname(fro_file),
os.path.dirname(to_file)),
item)).replace('\\', '/')
if item[-1] == '/':
ret += '/'
return ret
def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
# Python documentation recommends objects which do not support hash
# set this value to None. Python library objects follow this rule.
is_hashable = lambda val: val.__hash__
# If x is hashable, returns whether x is in s. Else returns whether x is in l.
def is_in_set_or_list(x, s, l):
if is_hashable(x):
return x in s
return x in l
prepend_index = 0
# Make membership testing of hashables in |to| (in particular, strings)
# faster.
hashable_to_set = set(x for x in to if is_hashable(x))
for item in fro:
singleton = False
if type(item) in (str, int):
# The cheap and easy case.
if is_paths:
to_item = MakePathRelative(to_file, fro_file, item)
else:
to_item = item
if not (type(item) is str and item.startswith('-')):
# Any string that doesn't begin with a "-" is a singleton - it can
# only appear once in a list, to be enforced by the list merge append
# or prepend.
singleton = True
elif type(item) is dict:
# Make a copy of the dictionary, continuing to look for paths to fix.
# The other intelligent aspects of merge processing won't apply because
# item is being merged into an empty dict.
to_item = {}
MergeDicts(to_item, item, to_file, fro_file)
elif type(item) is list:
# Recurse, making a copy of the list. If the list contains any
# descendant dicts, path fixing will occur. Note that here, custom
# values for is_paths and append are dropped; those are only to be
# applied to |to| and |fro|, not sublists of |fro|. append shouldn't
# matter anyway because the new |to_item| list is empty.
to_item = []
MergeLists(to_item, item, to_file, fro_file)
else:
raise TypeError(
'Attempt to merge list item of unsupported type ' + \
item.__class__.__name__)
if append:
# If appending a singleton that's already in the list, don't append.
# This ensures that the earliest occurrence of the item will stay put.
if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
to.append(to_item)
if is_hashable(to_item):
hashable_to_set.add(to_item)
else:
# If prepending a singleton that's already in the list, remove the
# existing instance and proceed with the prepend. This ensures that the
# item appears at the earliest possible position in the list.
while singleton and to_item in to:
to.remove(to_item)
# Don't just insert everything at index 0. That would prepend the new
# items to the list in reverse order, which would be an unwelcome
# surprise.
to.insert(prepend_index, to_item)
if is_hashable(to_item):
hashable_to_set.add(to_item)
prepend_index = prepend_index + 1
def MergeDicts(to, fro, to_file, fro_file):
# I wanted to name the parameter "from" but it's a Python keyword...
for k, v in fro.iteritems():
# It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
# copy semantics. Something else may want to merge from the |fro| dict
# later, and having the same dict ref pointed to twice in the tree isn't
# what anyone wants considering that the dicts may subsequently be
# modified.
if k in to:
bad_merge = False
if type(v) in (str, int):
if type(to[k]) not in (str, int):
bad_merge = True
elif type(v) is not type(to[k]):
bad_merge = True
if bad_merge:
raise TypeError(
'Attempt to merge dict value of type ' + v.__class__.__name__ + \
' into incompatible type ' + to[k].__class__.__name__ + \
' for key ' + k)
if type(v) in (str, int):
# Overwrite the existing value, if any. Cheap and easy.
is_path = IsPathSection(k)
if is_path:
to[k] = MakePathRelative(to_file, fro_file, v)
else:
to[k] = v
elif type(v) is dict:
# Recurse, guaranteeing copies will be made of objects that require it.
if not k in to:
to[k] = {}
MergeDicts(to[k], v, to_file, fro_file)
elif type(v) is list:
# Lists in dicts can be merged with different policies, depending on
# how the key in the "from" dict (k, the from-key) is written.
#
# If the from-key has ...the to-list will have this action
# this character appended:... applied when receiving the from-list:
# = replace
# + prepend
# ? set, only if to-list does not yet exist
# (none) append
#
# This logic is list-specific, but since it relies on the associated
# dict key, it's checked in this dict-oriented function.
ext = k[-1]
append = True
if ext == '=':
list_base = k[:-1]
lists_incompatible = [list_base, list_base + '?']
to[list_base] = []
elif ext == '+':
list_base = k[:-1]
lists_incompatible = [list_base + '=', list_base + '?']
append = False
elif ext == '?':
list_base = k[:-1]
lists_incompatible = [list_base, list_base + '=', list_base + '+']
else:
list_base = k
lists_incompatible = [list_base + '=', list_base + '?']
# Some combinations of merge policies appearing together are meaningless.
# It's stupid to replace and append simultaneously, for example. Append
# and prepend are the only policies that can coexist.
for list_incompatible in lists_incompatible:
if list_incompatible in fro:
raise GypError('Incompatible list policies ' + k + ' and ' +
list_incompatible)
if list_base in to:
if ext == '?':
# If the key ends in "?", the list will only be merged if it doesn't
# already exist.
continue
elif type(to[list_base]) is not list:
# This may not have been checked above if merging in a list with an
# extension character.
raise TypeError(
'Attempt to merge dict value of type ' + v.__class__.__name__ + \
' into incompatible type ' + to[list_base].__class__.__name__ + \
' for key ' + list_base + '(' + k + ')')
else:
to[list_base] = []
# Call MergeLists, which will make copies of objects that require it.
# MergeLists can recurse back into MergeDicts, although this will be
# to make copies of dicts (with paths fixed), there will be no
# subsequent dict "merging" once entering a list because lists are
# always replaced, appended to, or prepended to.
is_paths = IsPathSection(list_base)
MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
else:
raise TypeError(
'Attempt to merge dict value of unsupported type ' + \
v.__class__.__name__ + ' for key ' + k)
def MergeConfigWithInheritance(new_configuration_dict, build_file,
target_dict, configuration, visited):
# Skip if previously visted.
if configuration in visited:
return
# Look at this configuration.
configuration_dict = target_dict['configurations'][configuration]
# Merge in parents.
for parent in configuration_dict.get('inherit_from', []):
MergeConfigWithInheritance(new_configuration_dict, build_file,
target_dict, parent, visited + [configuration])
# Merge it into the new config.
MergeDicts(new_configuration_dict, configuration_dict,
build_file, build_file)
# Drop abstract.
if 'abstract' in new_configuration_dict:
del new_configuration_dict['abstract']
def SetUpConfigurations(target, target_dict):
# key_suffixes is a list of key suffixes that might appear on key names.
# These suffixes are handled in conditional evaluations (for =, +, and ?)
# and rules/exclude processing (for ! and /). Keys with these suffixes
# should be treated the same as keys without.
key_suffixes = ['=', '+', '?', '!', '/']
build_file = gyp.common.BuildFile(target)
# Provide a single configuration by default if none exists.
# TODO(mark): Signal an error if default_configurations exists but
# configurations does not.
if not 'configurations' in target_dict:
target_dict['configurations'] = {'Default': {}}
if not 'default_configuration' in target_dict:
concrete = [i for (i, config) in target_dict['configurations'].iteritems()
if not config.get('abstract')]
target_dict['default_configuration'] = sorted(concrete)[0]
merged_configurations = {}
configs = target_dict['configurations']
for (configuration, old_configuration_dict) in configs.iteritems():
# Skip abstract configurations (saves work only).
if old_configuration_dict.get('abstract'):
continue
# Configurations inherit (most) settings from the enclosing target scope.
# Get the inheritance relationship right by making a copy of the target
# dict.
new_configuration_dict = {}
for (key, target_val) in target_dict.iteritems():
key_ext = key[-1:]
if key_ext in key_suffixes:
key_base = key[:-1]
else:
key_base = key
if not key_base in non_configuration_keys:
new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val)
# Merge in configuration (with all its parents first).
MergeConfigWithInheritance(new_configuration_dict, build_file,
target_dict, configuration, [])
merged_configurations[configuration] = new_configuration_dict
# Put the new configurations back into the target dict as a configuration.
for configuration in merged_configurations.keys():
target_dict['configurations'][configuration] = (
merged_configurations[configuration])
# Now drop all the abstract ones.
for configuration in target_dict['configurations'].keys():
old_configuration_dict = target_dict['configurations'][configuration]
if old_configuration_dict.get('abstract'):
del target_dict['configurations'][configuration]
# Now that all of the target's configurations have been built, go through
# the target dict's keys and remove everything that's been moved into a
# "configurations" section.
delete_keys = []
for key in target_dict:
key_ext = key[-1:]
if key_ext in key_suffixes:
key_base = key[:-1]
else:
key_base = key
if not key_base in non_configuration_keys:
delete_keys.append(key)
for key in delete_keys:
del target_dict[key]
# Check the configurations to see if they contain invalid keys.
for configuration in target_dict['configurations'].keys():
configuration_dict = target_dict['configurations'][configuration]
for key in configuration_dict.keys():
if key in invalid_configuration_keys:
raise GypError('%s not allowed in the %s configuration, found in '
'target %s' % (key, configuration, target))
def ProcessListFiltersInDict(name, the_dict):
"""Process regular expression and exclusion-based filters on lists.
An exclusion list is in a dict key named with a trailing "!", like
"sources!". Every item in such a list is removed from the associated
main list, which in this example, would be "sources". Removed items are
placed into a "sources_excluded" list in the dict.
Regular expression (regex) filters are contained in dict keys named with a
trailing "/", such as "sources/" to operate on the "sources" list. Regex
filters in a dict take the form:
'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
['include', '_mac\\.cc$'] ],
The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
_win.cc. The second filter then includes all files ending in _mac.cc that
are now or were once in the "sources" list. Items matching an "exclude"
filter are subject to the same processing as would occur if they were listed
by name in an exclusion list (ending in "!"). Items matching an "include"
filter are brought back into the main list if previously excluded by an
exclusion list or exclusion regex filter. Subsequent matching "exclude"
patterns can still cause items to be excluded after matching an "include".
"""
# Look through the dictionary for any lists whose keys end in "!" or "/".
# These are lists that will be treated as exclude lists and regular
# expression-based exclude/include lists. Collect the lists that are
# needed first, looking for the lists that they operate on, and assemble
# then into |lists|. This is done in a separate loop up front, because
# the _included and _excluded keys need to be added to the_dict, and that
# can't be done while iterating through it.
lists = []
del_lists = []
for key, value in the_dict.iteritems():
operation = key[-1]
if operation != '!' and operation != '/':
continue
if type(value) is not list:
raise ValueError(name + ' key ' + key + ' must be list, not ' + \
value.__class__.__name__)
list_key = key[:-1]
if list_key not in the_dict:
# This happens when there's a list like "sources!" but no corresponding
# "sources" list. Since there's nothing for it to operate on, queue up
# the "sources!" list for deletion now.
del_lists.append(key)
continue
if type(the_dict[list_key]) is not list:
value = the_dict[list_key]
raise ValueError(name + ' key ' + list_key + \
' must be list, not ' + \
value.__class__.__name__ + ' when applying ' + \
{'!': 'exclusion', '/': 'regex'}[operation])
if not list_key in lists:
lists.append(list_key)
# Delete the lists that are known to be unneeded at this point.
for del_list in del_lists:
del the_dict[del_list]
for list_key in lists:
the_list = the_dict[list_key]
# Initialize the list_actions list, which is parallel to the_list. Each
# item in list_actions identifies whether the corresponding item in
# the_list should be excluded, unconditionally preserved (included), or
# whether no exclusion or inclusion has been applied. Items for which
# no exclusion or inclusion has been applied (yet) have value -1, items
# excluded have value 0, and items included have value 1. Includes and
# excludes override previous actions. All items in list_actions are
# initialized to -1 because no excludes or includes have been processed
# yet.
list_actions = list((-1,) * len(the_list))
exclude_key = list_key + '!'
if exclude_key in the_dict:
for exclude_item in the_dict[exclude_key]:
for index in xrange(0, len(the_list)):
if exclude_item == the_list[index]:
# This item matches the exclude_item, so set its action to 0
# (exclude).
list_actions[index] = 0
# The "whatever!" list is no longer needed, dump it.
del the_dict[exclude_key]
regex_key = list_key + '/'
if regex_key in the_dict:
for regex_item in the_dict[regex_key]:
[action, pattern] = regex_item
pattern_re = re.compile(pattern)
if action == 'exclude':
# This item matches an exclude regex, so set its value to 0 (exclude).
action_value = 0
elif action == 'include':
# This item matches an include regex, so set its value to 1 (include).
action_value = 1
else:
# This is an action that doesn't make any sense.
raise ValueError('Unrecognized action ' + action + ' in ' + name + \
' key ' + regex_key)
for index in xrange(0, len(the_list)):
list_item = the_list[index]
if list_actions[index] == action_value:
# Even if the regex matches, nothing will change so continue (regex
# searches are expensive).
continue
if pattern_re.search(list_item):
# Regular expression match.
list_actions[index] = action_value
# The "whatever/" list is no longer needed, dump it.
del the_dict[regex_key]
# Add excluded items to the excluded list.
#
# Note that exclude_key ("sources!") is different from excluded_key
# ("sources_excluded"). The exclude_key list is input and it was already
# processed and deleted; the excluded_key list is output and it's about
# to be created.
excluded_key = list_key + '_excluded'
if excluded_key in the_dict:
raise GypError(name + ' key ' + excluded_key +
' must not be present prior '
' to applying exclusion/regex filters for ' + list_key)
excluded_list = []
# Go backwards through the list_actions list so that as items are deleted,
# the indices of items that haven't been seen yet don't shift. That means
# that things need to be prepended to excluded_list to maintain them in the
# same order that they existed in the_list.
for index in xrange(len(list_actions) - 1, -1, -1):
if list_actions[index] == 0:
# Dump anything with action 0 (exclude). Keep anything with action 1
# (include) or -1 (no include or exclude seen for the item).
excluded_list.insert(0, the_list[index])
del the_list[index]
# If anything was excluded, put the excluded list into the_dict at
# excluded_key.
if len(excluded_list) > 0:
the_dict[excluded_key] = excluded_list
# Now recurse into subdicts and lists that may contain dicts.
for key, value in the_dict.iteritems():
if type(value) is dict:
ProcessListFiltersInDict(key, value)
elif type(value) is list:
ProcessListFiltersInList(key, value)
def ProcessListFiltersInList(name, the_list):
for item in the_list:
if type(item) is dict:
ProcessListFiltersInDict(name, item)
elif type(item) is list:
ProcessListFiltersInList(name, item)
def ValidateTargetType(target, target_dict):
"""Ensures the 'type' field on the target is one of the known types.
Arguments:
target: string, name of target.
target_dict: dict, target spec.
Raises an exception on error.
"""
VALID_TARGET_TYPES = ('executable', 'loadable_module',
'static_library', 'shared_library',
'mac_kernel_extension', 'none')
target_type = target_dict.get('type', None)
if target_type not in VALID_TARGET_TYPES:
raise GypError("Target %s has an invalid target type '%s'. "
"Must be one of %s." %
(target, target_type, '/'.join(VALID_TARGET_TYPES)))
if (target_dict.get('standalone_static_library', 0) and
not target_type == 'static_library'):
raise GypError('Target %s has type %s but standalone_static_library flag is'
' only valid for static_library type.' % (target,
target_type))
def ValidateSourcesInTarget(target, target_dict, build_file,
duplicate_basename_check):
if not duplicate_basename_check:
return
if target_dict.get('type', None) != 'static_library':
return
sources = target_dict.get('sources', [])
basenames = {}
for source in sources:
name, ext = os.path.splitext(source)
is_compiled_file = ext in [
'.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
if not is_compiled_file:
continue
basename = os.path.basename(name) # Don't include extension.
basenames.setdefault(basename, []).append(source)
error = ''
for basename, files in basenames.iteritems():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
if error:
print('static library %s has several files with the same basename:\n' %
target + error + 'libtool on Mac cannot handle that. Use '
'--no-duplicate-basename-check to disable this validation.')
raise GypError('Duplicate basenames in sources section, see list above')
def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
"""Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to.
Arguments:
target: string, name of target.
target_dict: dict, target spec containing "rules" and "sources" lists.
extra_sources_for_rules: a list of keys to scan for rule matches in
addition to 'sources'.
"""
# Dicts to map between values found in rules' 'rule_name' and 'extension'
# keys and the rule dicts themselves.
rule_names = {}
rule_extensions = {}
rules = target_dict.get('rules', [])
for rule in rules:
# Make sure that there's no conflict among rule names and extensions.
rule_name = rule['rule_name']
if rule_name in rule_names:
raise GypError('rule %s exists in duplicate, target %s' %
(rule_name, target))
rule_names[rule_name] = rule
rule_extension = rule['extension']
if rule_extension.startswith('.'):
rule_extension = rule_extension[1:]
if rule_extension in rule_extensions:
raise GypError(('extension %s associated with multiple rules, ' +
'target %s rules %s and %s') %
(rule_extension, target,
rule_extensions[rule_extension]['rule_name'],
rule_name))
rule_extensions[rule_extension] = rule
# Make sure rule_sources isn't already there. It's going to be
# created below if needed.
if 'rule_sources' in rule:
raise GypError(
'rule_sources must not exist in input, target %s rule %s' %
(target, rule_name))
rule_sources = []
source_keys = ['sources']
source_keys.extend(extra_sources_for_rules)
for source_key in source_keys:
for source in target_dict.get(source_key, []):
(source_root, source_extension) = os.path.splitext(source)
if source_extension.startswith('.'):
source_extension = source_extension[1:]
if source_extension == rule_extension:
rule_sources.append(source)
if len(rule_sources) > 0:
rule['rule_sources'] = rule_sources
def ValidateRunAsInTarget(target, target_dict, build_file):
target_name = target_dict.get('target_name')
run_as = target_dict.get('run_as')
if not run_as:
return
if type(run_as) is not dict:
raise GypError("The 'run_as' in target %s from file %s should be a "
"dictionary." %
(target_name, build_file))
action = run_as.get('action')
if not action:
raise GypError("The 'run_as' in target %s from file %s must have an "
"'action' section." %
(target_name, build_file))
if type(action) is not list:
raise GypError("The 'action' for 'run_as' in target %s from file %s "
"must be a list." %
(target_name, build_file))
working_directory = run_as.get('working_directory')
if working_directory and type(working_directory) is not str:
raise GypError("The 'working_directory' for 'run_as' in target %s "
"in file %s should be a string." %
(target_name, build_file))
environment = run_as.get('environment')
if environment and type(environment) is not dict:
raise GypError("The 'environment' for 'run_as' in target %s "
"in file %s should be a dictionary." %
(target_name, build_file))
def ValidateActionsInTarget(target, target_dict, build_file):
'''Validates the inputs to the actions in a target.'''
target_name = target_dict.get('target_name')
actions = target_dict.get('actions', [])
for action in actions:
action_name = action.get('action_name')
if not action_name:
raise GypError("Anonymous action in target %s. "
"An action must have an 'action_name' field." %
target_name)
inputs = action.get('inputs', None)
if inputs is None:
raise GypError('Action in target %s has no inputs.' % target_name)
action_command = action.get('action')
if action_command and not action_command[0]:
raise GypError("Empty action as command in target %s." % target_name)
def TurnIntIntoStrInDict(the_dict):
"""Given dict the_dict, recursively converts all integers into strings.
"""
# Use items instead of iteritems because there's no need to try to look at
# reinserted keys and their associated values.
for k, v in the_dict.items():
if type(v) is int:
v = str(v)
the_dict[k] = v
elif type(v) is dict:
TurnIntIntoStrInDict(v)
elif type(v) is list:
TurnIntIntoStrInList(v)
if type(k) is int:
del the_dict[k]
the_dict[str(k)] = v
def TurnIntIntoStrInList(the_list):
"""Given list the_list, recursively converts all integers into strings.
"""
for index in xrange(0, len(the_list)):
item = the_list[index]
if type(item) is int:
the_list[index] = str(item)
elif type(item) is dict:
TurnIntIntoStrInDict(item)
elif type(item) is list:
TurnIntIntoStrInList(item)
def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets,
data):
"""Return only the targets that are deep dependencies of |root_targets|."""
qualified_root_targets = []
for target in root_targets:
target = target.strip()
qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list)
if not qualified_targets:
raise GypError("Could not find target %s" % target)
qualified_root_targets.extend(qualified_targets)
wanted_targets = {}
for target in qualified_root_targets:
wanted_targets[target] = targets[target]
for dependency in dependency_nodes[target].DeepDependencies():
wanted_targets[dependency] = targets[dependency]
wanted_flat_list = [t for t in flat_list if t in wanted_targets]
# Prune unwanted targets from each build_file's data dict.
for build_file in data['target_build_files']:
if not 'targets' in data[build_file]:
continue
new_targets = []
for target in data[build_file]['targets']:
qualified_name = gyp.common.QualifiedTarget(build_file,
target['target_name'],
target['toolset'])
if qualified_name in wanted_targets:
new_targets.append(target)
data[build_file]['targets'] = new_targets
return wanted_targets, wanted_flat_list
def VerifyNoCollidingTargets(targets):
"""Verify that no two targets in the same directory share the same name.
Arguments:
targets: A list of targets in the form 'path/to/file.gyp:target_name'.
"""
# Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
used = {}
for target in targets:
# Separate out 'path/to/file.gyp, 'target_name' from
# 'path/to/file.gyp:target_name'.
path, name = target.rsplit(':', 1)
# Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
subdir, gyp = os.path.split(path)
# Use '.' for the current directory '', so that the error messages make
# more sense.
if not subdir:
subdir = '.'
# Prepare a key like 'path/to:target_name'.
key = subdir + ':' + name
if key in used:
# Complain if this target is already used.
raise GypError('Duplicate target name "%s" in directory "%s" used both '
'in "%s" and "%s".' % (name, subdir, gyp, used[key]))
used[key] = gyp
def SetGeneratorGlobals(generator_input_info):
# Set up path_sections and non_configuration_keys with the default data plus
# the generator-specific data.
global path_sections
path_sections = set(base_path_sections)
path_sections.update(generator_input_info['path_sections'])
global non_configuration_keys
non_configuration_keys = base_non_configuration_keys[:]
non_configuration_keys.extend(generator_input_info['non_configuration_keys'])
global multiple_toolsets
multiple_toolsets = generator_input_info[
'generator_supports_multiple_toolsets']
global generator_filelist_paths
generator_filelist_paths = generator_input_info['generator_filelist_paths']
def Load(build_files, variables, includes, depth, generator_input_info, check,
circular_check, duplicate_basename_check, parallel, root_targets):
SetGeneratorGlobals(generator_input_info)
# A generator can have other lists (in addition to sources) be processed
# for rules.
extra_sources_for_rules = generator_input_info['extra_sources_for_rules']
# Load build files. This loads every target-containing build file into
# the |data| dictionary such that the keys to |data| are build file names,
# and the values are the entire build file contents after "early" or "pre"
# processing has been done and includes have been resolved.
# NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
# well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
# track of the keys corresponding to "target" files.
data = {'target_build_files': set()}
# Normalize paths everywhere. This is important because paths will be
# used as keys to the data dict and for references between input files.
build_files = set(map(os.path.normpath, build_files))
if parallel:
LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth,
check, generator_input_info)
else:
aux_data = {}
for build_file in build_files:
try:
LoadTargetBuildFile(build_file, data, aux_data,
variables, includes, depth, check, True)
except Exception, e:
gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file)
raise
# Build a dict to access each target's subdict by qualified name.
targets = BuildTargetsDict(data)
# Fully qualify all dependency links.
QualifyDependencies(targets)
# Remove self-dependencies from targets that have 'prune_self_dependencies'
# set to 1.
RemoveSelfDependencies(targets)
# Expand dependencies specified as build_file:*.
ExpandWildcardDependencies(targets, data)
# Remove all dependencies marked as 'link_dependency' from the targets of
# type 'none'.
RemoveLinkDependenciesFromNoneTargets(targets)
# Apply exclude (!) and regex (/) list filters only for dependency_sections.
for target_name, target_dict in targets.iteritems():
tmp_dict = {}
for key_base in dependency_sections:
for op in ('', '!', '/'):
key = key_base + op
if key in target_dict:
tmp_dict[key] = target_dict[key]
del target_dict[key]
ProcessListFiltersInDict(target_name, tmp_dict)
# Write the results back to |target_dict|.
for key in tmp_dict:
target_dict[key] = tmp_dict[key]
# Make sure every dependency appears at most once.
RemoveDuplicateDependencies(targets)
if circular_check:
# Make sure that any targets in a.gyp don't contain dependencies in other
# .gyp files that further depend on a.gyp.
VerifyNoGYPFileCircularDependencies(targets)
[dependency_nodes, flat_list] = BuildDependencyList(targets)
if root_targets:
# Remove, from |targets| and |flat_list|, the targets that are not deep
# dependencies of the targets specified in |root_targets|.
targets, flat_list = PruneUnwantedTargets(
targets, flat_list, dependency_nodes, root_targets, data)
# Check that no two targets in the same directory have the same name.
VerifyNoCollidingTargets(flat_list)
# Handle dependent settings of various types.
for settings_type in ['all_dependent_settings',
'direct_dependent_settings',
'link_settings']:
DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
# Take out the dependent settings now that they've been published to all
# of the targets that require them.
for target in flat_list:
if settings_type in targets[target]:
del targets[target][settings_type]
# Make sure static libraries don't declare dependencies on other static
# libraries, but that linkables depend on all unlinked static libraries
# that they need so that their link steps will be correct.
gii = generator_input_info
if gii['generator_wants_static_library_dependencies_adjusted']:
AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes,
gii['generator_wants_sorted_dependencies'])
# Apply "post"/"late"/"target" variable expansions and condition evaluations.
for target in flat_list:
target_dict = targets[target]
build_file = gyp.common.BuildFile(target)
ProcessVariablesAndConditionsInDict(
target_dict, PHASE_LATE, variables, build_file)
# Move everything that can go into a "configurations" section into one.
for target in flat_list:
target_dict = targets[target]
SetUpConfigurations(target, target_dict)
# Apply exclude (!) and regex (/) list filters.
for target in flat_list:
target_dict = targets[target]
ProcessListFiltersInDict(target, target_dict)
# Apply "latelate" variable expansions and condition evaluations.
for target in flat_list:
target_dict = targets[target]
build_file = gyp.common.BuildFile(target)
ProcessVariablesAndConditionsInDict(
target_dict, PHASE_LATELATE, variables, build_file)
# Make sure that the rules make sense, and build up rule_sources lists as
# needed. Not all generators will need to use the rule_sources lists, but
# some may, and it seems best to build the list in a common spot.
# Also validate actions and run_as elements in targets.
for target in flat_list:
target_dict = targets[target]
build_file = gyp.common.BuildFile(target)
ValidateTargetType(target, target_dict)
ValidateSourcesInTarget(target, target_dict, build_file,
duplicate_basename_check)
ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
ValidateRunAsInTarget(target, target_dict, build_file)
ValidateActionsInTarget(target, target_dict, build_file)
# Generators might not expect ints. Turn them into strs.
TurnIntIntoStrInDict(data)
# TODO(mark): Return |data| for now because the generator needs a list of
# build files that came in. In the future, maybe it should just accept
# a list, and not the whole data dict.
return [flat_list, targets, data]
| mit |
IsCoolEntertainment/debpkg_python-boto | boto/sdb/db/manager/__init__.py | 173 | 4210 | # Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
def get_manager(cls):
"""
Returns the appropriate Manager class for a given Model class. It
does this by looking in the boto config for a section like this::
[DB]
db_type = SimpleDB
db_user = <aws access key id>
db_passwd = <aws secret access key>
db_name = my_domain
[DB_TestBasic]
db_type = SimpleDB
db_user = <another aws access key id>
db_passwd = <another aws secret access key>
db_name = basic_domain
db_port = 1111
The values in the DB section are "generic values" that will be used
if nothing more specific is found. You can also create a section for
a specific Model class that gives the db info for that class.
In the example above, TestBasic is a Model subclass.
"""
db_user = boto.config.get('DB', 'db_user', None)
db_passwd = boto.config.get('DB', 'db_passwd', None)
db_type = boto.config.get('DB', 'db_type', 'SimpleDB')
db_name = boto.config.get('DB', 'db_name', None)
db_table = boto.config.get('DB', 'db_table', None)
db_host = boto.config.get('DB', 'db_host', "sdb.amazonaws.com")
db_port = boto.config.getint('DB', 'db_port', 443)
enable_ssl = boto.config.getbool('DB', 'enable_ssl', True)
sql_dir = boto.config.get('DB', 'sql_dir', None)
debug = boto.config.getint('DB', 'debug', 0)
# first see if there is a fully qualified section name in the Boto config
module_name = cls.__module__.replace('.', '_')
db_section = 'DB_' + module_name + '_' + cls.__name__
if not boto.config.has_section(db_section):
db_section = 'DB_' + cls.__name__
if boto.config.has_section(db_section):
db_user = boto.config.get(db_section, 'db_user', db_user)
db_passwd = boto.config.get(db_section, 'db_passwd', db_passwd)
db_type = boto.config.get(db_section, 'db_type', db_type)
db_name = boto.config.get(db_section, 'db_name', db_name)
db_table = boto.config.get(db_section, 'db_table', db_table)
db_host = boto.config.get(db_section, 'db_host', db_host)
db_port = boto.config.getint(db_section, 'db_port', db_port)
enable_ssl = boto.config.getint(db_section, 'enable_ssl', enable_ssl)
debug = boto.config.getint(db_section, 'debug', debug)
elif hasattr(cls, "_db_name") and cls._db_name is not None:
# More specific then the generic DB config is any _db_name class property
db_name = cls._db_name
elif hasattr(cls.__bases__[0], "_manager"):
return cls.__bases__[0]._manager
if db_type == 'SimpleDB':
from boto.sdb.db.manager.sdbmanager import SDBManager
return SDBManager(cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl)
elif db_type == 'XML':
from boto.sdb.db.manager.xmlmanager import XMLManager
return XMLManager(cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl)
else:
raise ValueError('Unknown db_type: %s' % db_type)
| mit |
yu239/Paddle | paddle/scripts/cluster_train/conf.py | 20 | 1113 | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
HOSTS = [
"root@192.168.100.17",
"root@192.168.100.18",
]
'''
workspace configuration
'''
#root dir for workspace, can be set as any director with real user account
ROOT_DIR = "/home/paddle"
'''
network configuration
'''
#pserver nics
PADDLE_NIC = "eth0"
#pserver port
PADDLE_PORT = 7164
#pserver ports num
PADDLE_PORTS_NUM = 2
#pserver sparse ports num
PADDLE_PORTS_NUM_FOR_SPARSE = 2
#environments setting for all processes in cluster job
LD_LIBRARY_PATH = "/usr/local/cuda/lib64:/usr/lib64"
| apache-2.0 |
dagnir/servo | tests/wpt/web-platform-tests/tools/webdriver/webdriver/searchcontext.py | 251 | 2153 | """WebDriver element location functionality."""
class SearchContext(object):
"""Abstract class that provides the core element location functionality."""
def find_element_by_css(self, selector):
"""Find the first element matching a css selector."""
return self._find_element('css selector', selector)
def find_elements_by_css(self, selector):
"""Find all elements matching a css selector."""
return self._find_elements('css selector', selector)
def find_element_by_link_text(self, text):
"""Find the first link with the given text."""
return self._find_element('link text', text)
def find_elements_by_link_text(self, text):
"""Find all links with the given text."""
return self._find_elements('link text', text)
def find_element_by_partial_link_text(self, text):
"""Find the first link containing the given text."""
return self._find_element('partial link text', text)
def find_elements_by_partial_link_text(self, text):
"""Find all links containing the given text."""
return self._find_elements('partial link text', text)
def find_element_by_xpath(self, xpath):
"""Find the first element matching the xpath."""
return self._find_element('xpath', xpath)
def find_elements_by_xpath(self, xpath):
"""Find all elements matching the xpath."""
return self._find_elements('xpath', xpath)
def _find_element(self, strategy, value):
return self.execute('POST',
'/element',
'findElement',
self._get_locator(strategy, value))
def _find_elements(self, strategy, value):
return self.execute('POST',
'/elements',
'findElements',
self._get_locator(strategy, value))
def _get_locator(self, strategy, value):
if self.mode == 'strict':
return {'strategy': strategy, 'value': value}
elif self.mode == 'compatibility':
return {'using': strategy, 'value': value}
| mpl-2.0 |
guthemberg/yanoama | yanoama/pilot/system/server.py | 1 | 5045 | #!/home/upmc_aren/python_env/bin/python
import SocketServer
from threading import Thread
import subprocess
"""
run few command on remote node in yanoama
commands are coded two comma-separated
integers only
codes list:
0,0: update main sources
0,1: bootstrap
0,2: shutdown (kill pilot and amend)
0,3: start amen daemon
0,4: stop amen daemon
9,9: get date for testing
"""
class LinuxSystemConsole(object):
def getHostname(self):
return (subprocess.Popen(['hostname'], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]).strip()
def run(self,cmd):
output = "unknown "
args=cmd.split(',')
if len(args)!=2:
return output
try:
command=int(args[0])
param=int(args[1])
except ValueError:
return output
"""
maintenance codes:
0,0: update main sources
0,1: bootstrap
0,2: shutdown/kill pilot
0,3: start amen daemon
0,4: stop amen daemon
"""
if command == 0 :
if param == 0:
output = self.update_sources()
elif param == 1:
self.clenup_temp_scripts()
script_name='bootstrap.sh'
# script_wrapper_name='bootstrap_wrapper.sh'
dest_dir='/tmp/'
bootstrap_source_script='/home/upmc_aren/yanoama/yanoama/system/'+script_name
# bootstrap_source_script_wrapper='/home/upmc_aren/yanoama/yanoama/system/'+script_wrapper_name
self.update_sources()
self.copy_file(bootstrap_source_script, dest_dir)
# self.copy_file(bootstrap_source_script_wrapper, dest_dir)
self.run_shell_script(dest_dir+script_name)
output="restarting."
elif param == 2:
output = self.kill('pilotd')
elif param == 3:
output = self.start_amend()
elif param == 4:
output = self.stop_amend()
elif command == 9 and param == 9:
output = self.get_date()
return output
def update_sources(self):
return subprocess.Popen(['git','pull'], \
cwd='/home/upmc_aren/yanoama', \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
def get_date(self):
return subprocess.Popen(['date'], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
def copy_file(self,source_file,destination_path):
return subprocess.Popen(['cp','-f',source_file,destination_path], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
def kill(self,process_name):
output = subprocess.Popen(['sudo', 'pkill', '-f', process_name], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
if process_name=="pilotd":
subprocess.Popen(['sudo', 'rm', '-rf', "/var/run/pilotd.pid"], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
return output
def start_amend(self):
return subprocess.Popen(['sudo','/home/upmc_aren/monitoring/amen/amend','start'], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
def stop_amend(self):
return subprocess.Popen(['sudo','/home/upmc_aren/monitoring/amen/amend','stop'], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
def run_shell_script(self,full_path_to_shell):
return subprocess.Popen(['sh',full_path_to_shell], \
stdout=subprocess.PIPE, close_fds=True)
def clenup_temp_scripts(self):
return subprocess.Popen(['sudo','rm','-rf','/tmp/*.sh'], \
stdout=subprocess.PIPE, close_fds=True).communicate()[0]
class PilotServer(SocketServer.BaseRequestHandler):
bsize=1024
def handle(self):
console = LinuxSystemConsole()
data = self.request.recv(self.bsize)
output = console.run(data.strip())
self.request.send(output[:min(len(output),self.bsize)])
return
def finish(self):
self.request.send('bye ' + str(self.client_address) + '\n')
class service(SocketServer.BaseRequestHandler):
def handle(self):
data = 'dummy'
print "Client connected with ", self.client_address
while len(data):
data = self.request.recv(1024)
self.request.send(data)
print "Client exited"
self.request.close()
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
# t = ThreadedTCPServer(('',1520), PilotServer)
# t.serve_forever() | bsd-3-clause |
drawquest/drawquest-web | website/drawquest/apps/bounces/migrations/0002_auto__add_complaint.py | 1 | 1899 | # 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 model 'Complaint'
db.create_table('bounces_complaint', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('email', self.gf('django.db.models.fields.CharField')(max_length=255)),
('feedback_type', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
))
db.send_create_signal('bounces', ['Complaint'])
def backwards(self, orm):
# Deleting model 'Complaint'
db.delete_table('bounces_complaint')
models = {
'bounces.bounce': {
'Meta': {'object_name': 'Bounce'},
'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permanent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'sub_type': ('django.db.models.fields.SmallIntegerField', [], {})
},
'bounces.complaint': {
'Meta': {'object_name': 'Complaint'},
'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'feedback_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'bounces.suppressedemail': {
'Meta': {'object_name': 'SuppressedEmail'},
'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['bounces']
| bsd-3-clause |
chinesebear/rtt-net | rtt-2.1/tools/menuconfig.py | 6 | 1266 | import os
# make rtconfig.h from .config
def mk_rtconfig(filename):
try:
config = file(filename)
except:
print 'open .config failed'
return
rtconfig = file('rtconfig.h', 'w')
rtconfig.write('#ifndef RT_CONFIG_H__\n')
rtconfig.write('#define RT_CONFIG_H__\n\n')
empty_line = 1
for line in config:
line = line.lstrip(' ').replace('\n', '').replace('\r', '')
if len(line) == 0: continue
if line[0] == '#':
if len(line) == 1:
if empty_line:
continue
rtconfig.write('\n')
empty_line = 1
continue
rtconfig.write('/*%s */\n' % line[1:])
empty_line = 0
else:
empty_line = 0
setting = line.split('=')
if len(setting) >= 2:
if setting[0].startswith('CONFIG_'):
setting[0] = setting[0][7:]
if setting[1] == 'y':
rtconfig.write('#define %s\n' % setting[0])
else:
rtconfig.write('#define %s %s\n' % (setting[0], setting[1]))
rtconfig.write('#endif\n')
rtconfig.close()
def config():
mk_rtconfig('.config')
| mit |
myarjunar/QGIS | python/plugins/processing/algs/gdal/ui/RasterOptionsWidget.py | 2 | 2746 | # -*- coding: utf-8 -*-
"""
***************************************************************************
RasterOptionsWidget.py
---------------------
Date : December 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'December 2016'
__copyright__ = '(C) 2016, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtWidgets import QLineEdit, QComboBox
from qgis.gui import QgsRasterFormatSaveOptionsWidget
from processing.core.parameters import ParameterString
from processing.core.outputs import OutputString
from processing.gui.wrappers import WidgetWrapper, DIALOG_MODELER, DIALOG_BATCH
class RasterOptionsWidgetWrapper(WidgetWrapper):
def createWidget(self):
if self.dialogType == DIALOG_MODELER:
widget = QComboBox()
widget.setEditable(True)
strings = self.dialog.getAvailableValuesOfType(ParameterString, OutputString)
options = [(self.dialog.resolveValueDescription(s), s) for s in strings]
for desc, val in options:
widget.addItem(desc, val)
widget.setEditText(self.param.default or '')
return widget
elif self.dialogType == DIALOG_BATCH:
widget = QLineEdit()
if self.param.default:
widget.setText(self.param.default)
else:
return QgsRasterFormatSaveOptionsWidget()
def setValue(self, value):
if value is None:
value = ''
if self.dialogType == DIALOG_MODELER:
self.setComboValue(value)
elif self.dialogType == DIALOG_BATCH:
self.widget.setText(value)
else:
self.widget.setValue(value)
def value(self):
if self.dialogType == DIALOG_MODELER:
return self.comboValue()
elif self.dialogType == DIALOG_BATCH:
return self.widget.text()
else:
return ' '.join(self.widget.options())
| gpl-2.0 |
un33k/CouchPotatoServer | libs/tornado/concurrent.py | 65 | 16799 | #!/usr/bin/env python
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for working with threads and ``Futures``.
``Futures`` are a pattern for concurrent programming introduced in
Python 3.2 in the `concurrent.futures` package (this package has also
been backported to older versions of Python and can be installed with
``pip install futures``). Tornado will use `concurrent.futures.Future` if
it is available; otherwise it will use a compatible class defined in this
module.
"""
from __future__ import absolute_import, division, print_function, with_statement
import functools
import platform
import traceback
import sys
from tornado.log import app_log
from tornado.stack_context import ExceptionStackContext, wrap
from tornado.util import raise_exc_info, ArgReplacer
try:
from concurrent import futures
except ImportError:
futures = None
# Can the garbage collector handle cycles that include __del__ methods?
# This is true in cpython beginning with version 3.4 (PEP 442).
_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
sys.version_info >= (3, 4))
class ReturnValueIgnoredError(Exception):
pass
# This class and associated code in the future object is derived
# from the Trollius project, a backport of asyncio to Python 2.x - 3.x
class _TracebackLogger(object):
"""Helper to log a traceback upon destruction if not cleared.
This solves a nasty problem with Futures and Tasks that have an
exception set: if nobody asks for the exception, the exception is
never logged. This violates the Zen of Python: 'Errors should
never pass silently. Unless explicitly silenced.'
However, we don't want to log the exception as soon as
set_exception() is called: if the calling code is written
properly, it will get the exception and handle it properly. But
we *do* want to log it if result() or exception() was never called
-- otherwise developers waste a lot of time wondering why their
buggy code fails silently.
An earlier attempt added a __del__() method to the Future class
itself, but this backfired because the presence of __del__()
prevents garbage collection from breaking cycles. A way out of
this catch-22 is to avoid having a __del__() method on the Future
class itself, but instead to have a reference to a helper object
with a __del__() method that logs the traceback, where we ensure
that the helper object doesn't participate in cycles, and only the
Future has a reference to it.
The helper object is added when set_exception() is called. When
the Future is collected, and the helper is present, the helper
object is also collected, and its __del__() method will log the
traceback. When the Future's result() or exception() method is
called (and a helper object is present), it removes the the helper
object, after calling its clear() method to prevent it from
logging.
One downside is that we do a fair amount of work to extract the
traceback from the exception, even when it is never logged. It
would seem cheaper to just store the exception object, but that
references the traceback, which references stack frames, which may
reference the Future, which references the _TracebackLogger, and
then the _TracebackLogger would be included in a cycle, which is
what we're trying to avoid! As an optimization, we don't
immediately format the exception; we only do the work when
activate() is called, which call is delayed until after all the
Future's callbacks have run. Since usually a Future has at least
one callback (typically set by 'yield From') and usually that
callback extracts the callback, thereby removing the need to
format the exception.
PS. I don't claim credit for this solution. I first heard of it
in a discussion about closing files when they are collected.
"""
__slots__ = ('exc_info', 'formatted_tb')
def __init__(self, exc_info):
self.exc_info = exc_info
self.formatted_tb = None
def activate(self):
exc_info = self.exc_info
if exc_info is not None:
self.exc_info = None
self.formatted_tb = traceback.format_exception(*exc_info)
def clear(self):
self.exc_info = None
self.formatted_tb = None
def __del__(self):
if self.formatted_tb:
app_log.error('Future exception was never retrieved: %s',
''.join(self.formatted_tb).rstrip())
class Future(object):
"""Placeholder for an asynchronous result.
A ``Future`` encapsulates the result of an asynchronous
operation. In synchronous applications ``Futures`` are used
to wait for the result from a thread or process pool; in
Tornado they are normally used with `.IOLoop.add_future` or by
yielding them in a `.gen.coroutine`.
`tornado.concurrent.Future` is similar to
`concurrent.futures.Future`, but not thread-safe (and therefore
faster for use with single-threaded event loops).
In addition to ``exception`` and ``set_exception``, methods ``exc_info``
and ``set_exc_info`` are supported to capture tracebacks in Python 2.
The traceback is automatically available in Python 3, but in the
Python 2 futures backport this information is discarded.
This functionality was previously available in a separate class
``TracebackFuture``, which is now a deprecated alias for this class.
.. versionchanged:: 4.0
`tornado.concurrent.Future` is always a thread-unsafe ``Future``
with support for the ``exc_info`` methods. Previously it would
be an alias for the thread-safe `concurrent.futures.Future`
if that package was available and fall back to the thread-unsafe
implementation if it was not.
.. versionchanged:: 4.1
If a `.Future` contains an error but that error is never observed
(by calling ``result()``, ``exception()``, or ``exc_info()``),
a stack trace will be logged when the `.Future` is garbage collected.
This normally indicates an error in the application, but in cases
where it results in undesired logging it may be necessary to
suppress the logging by ensuring that the exception is observed:
``f.add_done_callback(lambda f: f.exception())``.
"""
def __init__(self):
self._done = False
self._result = None
self._exc_info = None
self._log_traceback = False # Used for Python >= 3.4
self._tb_logger = None # Used for Python <= 3.3
self._callbacks = []
def cancel(self):
"""Cancel the operation, if possible.
Tornado ``Futures`` do not support cancellation, so this method always
returns False.
"""
return False
def cancelled(self):
"""Returns True if the operation has been cancelled.
Tornado ``Futures`` do not support cancellation, so this method
always returns False.
"""
return False
def running(self):
"""Returns True if this operation is currently running."""
return not self._done
def done(self):
"""Returns True if the future has finished running."""
return self._done
def _clear_tb_log(self):
self._log_traceback = False
if self._tb_logger is not None:
self._tb_logger.clear()
self._tb_logger = None
def result(self, timeout=None):
"""If the operation succeeded, return its result. If it failed,
re-raise its exception.
"""
self._clear_tb_log()
if self._result is not None:
return self._result
if self._exc_info is not None:
raise_exc_info(self._exc_info)
self._check_done()
return self._result
def exception(self, timeout=None):
"""If the operation raised an exception, return the `Exception`
object. Otherwise returns None.
"""
self._clear_tb_log()
if self._exc_info is not None:
return self._exc_info[1]
else:
self._check_done()
return None
def add_done_callback(self, fn):
"""Attaches the given callback to the `Future`.
It will be invoked with the `Future` as its argument when the Future
has finished running and its result is available. In Tornado
consider using `.IOLoop.add_future` instead of calling
`add_done_callback` directly.
"""
if self._done:
fn(self)
else:
self._callbacks.append(fn)
def set_result(self, result):
"""Sets the result of a ``Future``.
It is undefined to call any of the ``set`` methods more than once
on the same object.
"""
self._result = result
self._set_done()
def set_exception(self, exception):
"""Sets the exception of a ``Future.``"""
self.set_exc_info(
(exception.__class__,
exception,
getattr(exception, '__traceback__', None)))
def exc_info(self):
"""Returns a tuple in the same format as `sys.exc_info` or None.
.. versionadded:: 4.0
"""
self._clear_tb_log()
return self._exc_info
def set_exc_info(self, exc_info):
"""Sets the exception information of a ``Future.``
Preserves tracebacks on Python 2.
.. versionadded:: 4.0
"""
self._exc_info = exc_info
self._log_traceback = True
if not _GC_CYCLE_FINALIZERS:
self._tb_logger = _TracebackLogger(exc_info)
try:
self._set_done()
finally:
# Activate the logger after all callbacks have had a
# chance to call result() or exception().
if self._log_traceback and self._tb_logger is not None:
self._tb_logger.activate()
self._exc_info = exc_info
def _check_done(self):
if not self._done:
raise Exception("DummyFuture does not support blocking for results")
def _set_done(self):
self._done = True
for cb in self._callbacks:
try:
cb(self)
except Exception:
app_log.exception('exception calling callback %r for %r',
cb, self)
self._callbacks = None
# On Python 3.3 or older, objects with a destructor part of a reference
# cycle are never destroyed. It's no longer the case on Python 3.4 thanks to
# the PEP 442.
if _GC_CYCLE_FINALIZERS:
def __del__(self):
if not self._log_traceback:
# set_exception() was not called, or result() or exception()
# has consumed the exception
return
tb = traceback.format_exception(*self._exc_info)
app_log.error('Future %r exception was never retrieved: %s',
self, ''.join(tb).rstrip())
TracebackFuture = Future
if futures is None:
FUTURES = Future
else:
FUTURES = (futures.Future, Future)
def is_future(x):
return isinstance(x, FUTURES)
class DummyExecutor(object):
def submit(self, fn, *args, **kwargs):
future = TracebackFuture()
try:
future.set_result(fn(*args, **kwargs))
except Exception:
future.set_exc_info(sys.exc_info())
return future
def shutdown(self, wait=True):
pass
dummy_executor = DummyExecutor()
def run_on_executor(fn):
"""Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
This decorator should be used only on methods of objects with attributes
``executor`` and ``io_loop``.
"""
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
callback = kwargs.pop("callback", None)
future = self.executor.submit(fn, self, *args, **kwargs)
if callback:
self.io_loop.add_future(future,
lambda future: callback(future.result()))
return future
return wrapper
_NO_RESULT = object()
def return_future(f):
"""Decorator to make a function that returns via callback return a
`Future`.
The wrapped function should take a ``callback`` keyword argument
and invoke it with one argument when it has finished. To signal failure,
the function can simply raise an exception (which will be
captured by the `.StackContext` and passed along to the ``Future``).
From the caller's perspective, the callback argument is optional.
If one is given, it will be invoked when the function is complete
with `Future.result()` as an argument. If the function fails, the
callback will not be run and an exception will be raised into the
surrounding `.StackContext`.
If no callback is given, the caller should use the ``Future`` to
wait for the function to complete (perhaps by yielding it in a
`.gen.engine` function, or passing it to `.IOLoop.add_future`).
Usage::
@return_future
def future_func(arg1, arg2, callback):
# Do stuff (possibly asynchronous)
callback(result)
@gen.engine
def caller(callback):
yield future_func(arg1, arg2)
callback()
Note that ``@return_future`` and ``@gen.engine`` can be applied to the
same function, provided ``@return_future`` appears first. However,
consider using ``@gen.coroutine`` instead of this combination.
"""
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
callback, args, kwargs = replacer.replace(
lambda value=_NO_RESULT: future.set_result(value),
args, kwargs)
def handle_error(typ, value, tb):
future.set_exc_info((typ, value, tb))
return True
exc_info = None
with ExceptionStackContext(handle_error):
try:
result = f(*args, **kwargs)
if result is not None:
raise ReturnValueIgnoredError(
"@return_future should not be used with functions "
"that return values")
except:
exc_info = sys.exc_info()
raise
if exc_info is not None:
# If the initial synchronous part of f() raised an exception,
# go ahead and raise it to the caller directly without waiting
# for them to inspect the Future.
future.result()
# If the caller passed in a callback, schedule it to be called
# when the future resolves. It is important that this happens
# just before we return the future, or else we risk confusing
# stack contexts with multiple exceptions (one here with the
# immediate exception, and again when the future resolves and
# the callback triggers its exception by calling future.result()).
if callback is not None:
def run_callback(future):
result = future.result()
if result is _NO_RESULT:
callback()
else:
callback(future.result())
future.add_done_callback(wrap(run_callback))
return future
return wrapper
def chain_future(a, b):
"""Chain two futures together so that when one completes, so does the other.
The result (success or failure) of ``a`` will be copied to ``b``, unless
``b`` has already been completed or cancelled by the time ``a`` finishes.
"""
def copy(future):
assert future is a
if b.done():
return
if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture)
and a.exc_info() is not None):
b.set_exc_info(a.exc_info())
elif a.exception() is not None:
b.set_exception(a.exception())
else:
b.set_result(a.result())
a.add_done_callback(copy)
| gpl-3.0 |
jgao54/airflow | tests/contrib/hooks/test_emr_hook.py | 3 | 2877 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
import boto3
from airflow import configuration
from airflow.contrib.hooks.emr_hook import EmrHook
try:
from moto import mock_emr
except ImportError:
mock_emr = None
@unittest.skipIf(mock_emr is None, 'moto package not present')
class TestEmrHook(unittest.TestCase):
@mock_emr
def setUp(self):
configuration.load_test_config()
@mock_emr
def test_get_conn_returns_a_boto3_connection(self):
hook = EmrHook(aws_conn_id='aws_default')
self.assertIsNotNone(hook.get_conn().list_clusters())
@mock_emr
def test_create_job_flow_uses_the_emr_config_to_create_a_cluster(self):
client = boto3.client('emr', region_name='us-east-1')
hook = EmrHook(aws_conn_id='aws_default', emr_conn_id='emr_default')
cluster = hook.create_job_flow({'Name': 'test_cluster'})
self.assertEqual(client.list_clusters()['Clusters'][0]['Id'],
cluster['JobFlowId'])
@mock_emr
def test_create_job_flow_extra_args(self):
"""
Test that we can add extra arguments to the launch call.
This is useful for when AWS add new options, such as
"SecurityConfiguration" so that we don't have to change our code
"""
client = boto3.client('emr', region_name='us-east-1')
hook = EmrHook(aws_conn_id='aws_default', emr_conn_id='emr_default')
# AmiVersion is really old and almost no one will use it anymore, but
# it's one of the "optional" request params that moto supports - it's
# coverage of EMR isn't 100% it turns out.
cluster = hook.create_job_flow({'Name': 'test_cluster',
'ReleaseLabel': '',
'AmiVersion': '3.2'})
cluster = client.describe_cluster(ClusterId=cluster['JobFlowId'])['Cluster']
# The AmiVersion comes back as {Requested,Running}AmiVersion fields.
self.assertEqual(cluster['RequestedAmiVersion'], '3.2')
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
PriceChild/ansible | lib/ansible/modules/cloud/misc/proxmox_kvm.py | 6 | 47830 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Abdoul Bah (@helldorado) <bahabdoul at gmail.com>
"""
Ansible module to manage Qemu(KVM) instance in Proxmox VE cluster.
This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
"""
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: proxmox_kvm
short_description: Management of Qemu(KVM) Virtual Machines in Proxmox VE cluster.
description:
- Allows you to create/delete/stop Qemu(KVM) Virtual Machines in Proxmox VE cluster.
version_added: "2.3"
author: "Abdoul Bah (@helldorado) <bahabdoul at gmail.com>"
options:
acpi:
description:
- Specify if ACPI should be enables/disabled.
required: false
default: "yes"
choices: [ "yes", "no" ]
agent:
description:
- Specify if the QEMU GuestAgent should be enabled/disabled.
required: false
default: null
choices: [ "yes", "no" ]
args:
description:
- Pass arbitrary arguments to kvm.
- This option is for experts only!
default: "-serial unix:/var/run/qemu-server/VMID.serial,server,nowait"
required: false
api_host:
description:
- Specify the target host of the Proxmox VE cluster.
required: true
api_user:
description:
- Specify the user to authenticate with.
required: true
api_password:
description:
- Specify the password to authenticate with.
- You can use C(PROXMOX_PASSWORD) environment variable.
default: null
required: false
autostart:
description:
- Specify, if the VM should be automatically restarted after crash (currently ignored in PVE API).
required: false
default: "no"
choices: [ "yes", "no" ]
balloon:
description:
- Specify the amount of RAM for the VM in MB.
- Using zero disables the balloon driver.
required: false
default: 0
bios:
description:
- Specify the BIOS implementation.
choices: ['seabios', 'ovmf']
required: false
default: null
boot:
description:
- Specify the boot order -> boot on floppy C(a), hard disk C(c), CD-ROM C(d), or network C(n).
- You can combine to set order.
required: false
default: cnd
bootdisk:
description:
- Enable booting from specified disk. C((ide|sata|scsi|virtio)\d+)
required: false
default: null
clone:
description:
- Name of VM to be cloned. If C(vmid) is setted, C(clone) can take arbitrary value but required for intiating the clone.
required: false
default: null
cores:
description:
- Specify number of cores per socket.
required: false
default: 1
cpu:
description:
- Specify emulated CPU type.
required: false
default: kvm64
cpulimit:
description:
- Specify if CPU usage will be limited. Value 0 indicates no CPU limit.
- If the computer has 2 CPUs, it has total of '2' CPU time
required: false
default: null
cpuunits:
description:
- Specify CPU weight for a VM.
- You can disable fair-scheduler configuration by setting this to 0
default: 1000
required: false
delete:
description:
- Specify a list of settings you want to delete.
required: false
default: null
description:
description:
- Specify the description for the VM. Only used on the configuration web interface.
- This is saved as comment inside the configuration file.
required: false
default: null
digest:
description:
- Specify if to prevent changes if current configuration file has different SHA1 digest.
- This can be used to prevent concurrent modifications.
required: false
default: null
force:
description:
- Allow to force stop VM.
- Can be used only with states C(stopped), C(restarted).
default: null
choices: [ "yes", "no" ]
required: false
format:
description:
- Target drive’s backing file’s data format.
- Used only with clone
default: qcow2
choices: [ "cloop", "cow", "qcow", "qcow2", "qed", "raw", "vmdk" ]
required: false
freeze:
description:
- Specify if PVE should freeze CPU at startup (use 'c' monitor command to start execution).
required: false
default: null
choices: [ "yes", "no" ]
full:
description:
- Create a full copy of all disk. This is always done when you clone a normal VM.
- For VM templates, we try to create a linked clone by default.
- Used only with clone
default: yes
choices: [ "yes", "no"]
required: false
hostpci:
description:
- Specify a hash/dictionary of map host pci devices into guest. C(hostpci='{"key":"value", "key":"value"}').
- Keys allowed are - C(hostpci[n]) where 0 ≤ n ≤ N.
- Values allowed are - C("host="HOSTPCIID[;HOSTPCIID2...]",pcie="1|0",rombar="1|0",x-vga="1|0"").
- The C(host) parameter is Host PCI device pass through. HOSTPCIID syntax is C(bus:dev.func) (hexadecimal numbers).
- C(pcie=boolean) I(default=0) Choose the PCI-express bus (needs the q35 machine model).
- C(rombar=boolean) I(default=1) Specify whether or not the device’s ROM will be visible in the guest’s memory map.
- C(x-vga=boolean) I(default=0) Enable vfio-vga device support.
- /!\ This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.
required: false
default: null
hotplug:
description:
- Selectively enable hotplug features.
- This is a comma separated list of hotplug features C('network', 'disk', 'cpu', 'memory' and 'usb').
- Value 0 disables hotplug completely and value 1 is an alias for the default C('network,disk,usb').
required: false
default: null
hugepages:
description:
- Enable/disable hugepages memory.
choices: ['any', '2', '1024']
required: false
default: null
ide:
description:
- A hash/dictionary of volume used as IDE hard disk or CD-ROM. C(ide='{"key":"value", "key":"value"}').
- Keys allowed are - C(ide[n]) where 0 ≤ n ≤ 3.
- Values allowed are - C("storage:size,format=value").
- C(storage) is the storage identifier where to create the disk.
- C(size) is the size of the disk in GB.
- C(format) is the drive’s backing file’s data format. C(qcow2|raw|subvol).
required: false
default: null
keyboard:
description:
- Sets the keyboard layout for VNC server.
required: false
default: null
kvm:
description:
- Enable/disable KVM hardware virtualization.
required: false
default: "yes"
choices: [ "yes", "no" ]
localtime:
description:
- Sets the real time clock to local time.
- This is enabled by default if ostype indicates a Microsoft OS.
required: false
default: null
choices: [ "yes", "no" ]
lock:
description:
- Lock/unlock the VM.
choices: ['migrate', 'backup', 'snapshot', 'rollback']
required: false
default: null
machine:
description:
- Specifies the Qemu machine type.
- type => C((pc|pc(-i440fx)?-\d+\.\d+(\.pxe)?|q35|pc-q35-\d+\.\d+(\.pxe)?))
required: false
default: null
memory:
description:
- Memory size in MB for instance.
required: false
default: 512
migrate_downtime:
description:
- Sets maximum tolerated downtime (in seconds) for migrations.
required: false
default: null
migrate_speed:
description:
- Sets maximum speed (in MB/s) for migrations.
- A value of 0 is no limit.
required: false
default: null
name:
description:
- Specifies the VM name. Only used on the configuration web interface.
- Required only for C(state=present).
default: null
required: false
net:
description:
- A hash/dictionary of network interfaces for the VM. C(net='{"key":"value", "key":"value"}').
- Keys allowed are - C(net[n]) where 0 ≤ n ≤ N.
- Values allowed are - C("model="XX:XX:XX:XX:XX:XX",brigde="value",rate="value",tag="value",firewall="1|0",trunks="vlanid"").
- Model is one of C(e1000 e1000-82540em e1000-82544gc e1000-82545em i82551 i82557b i82559er ne2k_isa ne2k_pci pcnet rtl8139 virtio vmxnet3).
- C(XX:XX:XX:XX:XX:XX) should be an unique MAC address. This is automatically generated if not specified.
- The C(bridge) parameter can be used to automatically add the interface to a bridge device. The Proxmox VE standard bridge is called 'vmbr0'.
- Option C(rate) is used to limit traffic bandwidth from and to this interface. It is specified as floating point number, unit is 'Megabytes per second'.
- If you specify no bridge, we create a kvm 'user' (NATed) network device, which provides DHCP and DNS services.
default: null
required: false
newid:
description:
- VMID for the clone. Used only with clone.
- If newid is not set, the next available VM ID will be fetched from ProxmoxAPI.
default: null
required: false
node:
description:
- Proxmox VE node, where the new VM will be created.
- Only required for C(state=present).
- For other states, it will be autodiscovered.
default: null
required: false
numa:
description:
- A hash/dictionaries of NUMA topology. C(numa='{"key":"value", "key":"value"}').
- Keys allowed are - C(numa[n]) where 0 ≤ n ≤ N.
- Values allowed are - C("cpu="<id[-id];...>",hostnodes="<id[-id];...>",memory="number",policy="(bind|interleave|preferred)"").
- C(cpus) CPUs accessing this NUMA node.
- C(hostnodes) Host NUMA nodes to use.
- C(memory) Amount of memory this NUMA node provides.
- C(policy) NUMA allocation policy.
default: null
required: false
onboot:
description:
- Specifies whether a VM will be started during system bootup.
default: "yes"
choices: [ "yes", "no" ]
required: false
ostype:
description:
- Specifies guest operating system. This is used to enable special optimization/features for specific operating systems.
- The l26 is Linux 2.6/3.X Kernel.
choices: ['other', 'wxp', 'w2k', 'w2k3', 'w2k8', 'wvista', 'win7', 'win8', 'l24', 'l26', 'solaris']
default: l26
required: false
parallel:
description:
- A hash/dictionary of map host parallel devices. C(parallel='{"key":"value", "key":"value"}').
- Keys allowed are - (parallel[n]) where 0 ≤ n ≤ 2.
- Values allowed are - C("/dev/parport\d+|/dev/usb/lp\d+").
default: null
required: false
pool:
description:
- Add the new VM to the specified pool.
default: null
required: false
protection:
description:
- Enable/disable the protection flag of the VM. This will enable/disable the remove VM and remove disk operations.
default: null
choices: [ "yes", "no" ]
required: false
reboot:
description:
- Allow reboot. If set to yes, the VM exit on reboot.
default: null
choices: [ "yes", "no" ]
required: false
revert:
description:
- Revert a pending change.
default: null
required: false
sata:
description:
- A hash/dictionary of volume used as sata hard disk or CD-ROM. C(sata='{"key":"value", "key":"value"}').
- Keys allowed are - C(sata[n]) where 0 ≤ n ≤ 5.
- Values allowed are - C("storage:size,format=value").
- C(storage) is the storage identifier where to create the disk.
- C(size) is the size of the disk in GB.
- C(format) is the drive’s backing file’s data format. C(qcow2|raw|subvol).
default: null
required: false
scsi:
description:
- A hash/dictionary of volume used as SCSI hard disk or CD-ROM. C(scsi='{"key":"value", "key":"value"}').
- Keys allowed are - C(sata[n]) where 0 ≤ n ≤ 13.
- Values allowed are - C("storage:size,format=value").
- C(storage) is the storage identifier where to create the disk.
- C(size) is the size of the disk in GB.
- C(format) is the drive’s backing file’s data format. C(qcow2|raw|subvol).
default: null
required: false
scsihw:
description:
- Specifies the SCSI controller model.
choices: ['lsi', 'lsi53c810', 'virtio-scsi-pci', 'virtio-scsi-single', 'megasas', 'pvscsi']
required: false
default: null
serial:
description:
- A hash/dictionary of serial device to create inside the VM. C('{"key":"value", "key":"value"}').
- Keys allowed are - serial[n](str; required) where 0 ≤ n ≤ 3.
- Values allowed are - C((/dev/.+|socket)).
- /!\ If you pass through a host serial device, it is no longer possible to migrate such machines - use with special care.
default: null
required: false
shares:
description:
- Rets amount of memory shares for auto-ballooning. (0 - 50000).
- The larger the number is, the more memory this VM gets.
- The number is relative to weights of all other running VMs.
- Using 0 disables auto-ballooning, this means no limit.
required: false
default: null
skiplock:
description:
- Ignore locks
- Only root is allowed to use this option.
required: false
default: null
smbios:
description:
- Specifies SMBIOS type 1 fields.
required: false
default: null
snapname:
description:
- The name of the snapshot. Used only with clone.
default: null
required: false
sockets:
description:
- Sets the number of CPU sockets. (1 - N).
required: false
default: 1
startdate:
description:
- Sets the initial date of the real time clock.
- Valid format for date are C('now') or C('2016-09-25T16:01:21') or C('2016-09-25').
required: false
default: null
startup:
description:
- Startup and shutdown behavior. C([[order=]\d+] [,up=\d+] [,down=\d+]).
- Order is a non-negative number defining the general startup order.
- Shutdown in done with reverse ordering.
required: false
default: null
state:
description:
- Indicates desired state of the instance.
- If C(current), the current state of the VM will be fecthed. You can access it with C(results.status)
choices: ['present', 'started', 'absent', 'stopped', 'restarted','current']
required: false
default: present
storage:
description:
- Target storage for full clone.
default: null
required: false
tablet:
description:
- Enables/disables the USB tablet device.
required: false
choices: [ "yes", "no" ]
default: "no"
target:
description:
- Target node. Only allowed if the original VM is on shared storage.
- Used only with clone
default: null
required: false
tdf:
description:
- Enables/disables time drift fix.
required: false
default: null
choices: [ "yes", "no" ]
template:
description:
- Enables/disables the template.
required: false
default: "no"
choices: [ "yes", "no" ]
timeout:
description:
- Timeout for operations.
default: 30
required: false
update:
description:
- If C(yes), the VM will be update with new value.
- Cause of the operations of the API and security reasons, I have disabled the update of the following parameters
- C(net, virtio, ide, sata, scsi). Per example updating C(net) update the MAC address and C(virtio) create always new disk...
default: "no"
choices: [ "yes", "no" ]
required: false
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.
default: "no"
choices: [ "yes", "no" ]
required: false
vcpus:
description:
- Sets number of hotplugged vcpus.
required: false
default: null
vga:
description:
- Select VGA type. If you want to use high resolution modes (>= 1280x1024x16) then you should use option 'std' or 'vmware'.
choices: ['std', 'cirrus', 'vmware', 'qxl', 'serial0', 'serial1', 'serial2', 'serial3', 'qxl2', 'qxl3', 'qxl4']
required: false
default: std
virtio:
description:
- A hash/dictionary of volume used as VIRTIO hard disk. C(virtio='{"key":"value", "key":"value"}').
- Keys allowed are - C(virto[n]) where 0 ≤ n ≤ 15.
- Values allowed are - C("storage:size,format=value").
- C(storage) is the storage identifier where to create the disk.
- C(size) is the size of the disk in GB.
- C(format) is the drive’s backing file’s data format. C(qcow2|raw|subvol).
required: false
default: null
vmid:
description:
- Specifies the VM ID. Instead use I(name) parameter.
- If vmid is not set, the next available VM ID will be fetched from ProxmoxAPI.
default: null
required: false
watchdog:
description:
- Creates a virtual hardware watchdog device.
required: false
default: null
requirements: [ "proxmoxer", "requests" ]
'''
EXAMPLES = '''
# Create new VM with minimal options
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
# Create new VM with minimal options and given vmid
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
vmid : 100
# Create new VM with two network interface options.
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
net : '{"net0":"virtio,bridge=vmbr1,rate=200", "net1":"e1000,bridge=vmbr2,"}'
# Create new VM with one network interface, three virto hard disk, 4 cores, and 2 vcpus.
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
net : '{"net0":"virtio,bridge=vmbr1,rate=200"}'
virtio : '{"virtio0":"VMs_LVM:10", "virtio1":"VMs:2,format=qcow2", "virtio2":"VMs:5,format=raw"}'
cores : 4
vcpus : 2
# Clone VM with only source VM name
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
clone : spynal # The VM source
name : zavala # The target VM name
node : sabrewulf
storage : VMs
format : qcow2
timeout : 500 # Note: The task can take a while. Adapt
# Clone VM with source vmid and target newid and raw format
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
clone : arbitrary_name
vmid : 108
newid : 152
name : zavala # The target VM name
node : sabrewulf
storage : LVM_STO
format : raw
timeout : 300 # Note: The task can take a while. Adapt
# Create new VM and lock it for snapashot.
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
lock : snapshot
# Create new VM and set protection to disable the remove VM and remove disk operations
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
protection : yes
# Start VM
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : started
# Stop VM
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : stopped
# Stop VM with force
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : stopped
force : yes
# Restart VM
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : restarted
# Remove VM
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : absent
# Get VM current state
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
state : current
# Update VM configuration
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
cpu : 8
memory : 16384
update : yes
# Delete QEMU parameters
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
delete : 'args,template,cpulimit'
# Revert a pending change
- proxmox_kvm:
api_user : root@pam
api_password: secret
api_host : helldorado
name : spynal
node : sabrewulf
revert : 'template,cpulimit'
'''
RETURN = '''
devices:
description: The list of devices created or used.
returned: success
type: dict
sample: '
{
"ide0": "VMS_LVM:vm-115-disk-1",
"ide1": "VMs:115/vm-115-disk-3.raw",
"virtio0": "VMS_LVM:vm-115-disk-2",
"virtio1": "VMs:115/vm-115-disk-1.qcow2",
"virtio2": "VMs:115/vm-115-disk-2.raw"
}'
mac:
description: List of mac address created and net[n] attached. Useful when you want to use provision systems like Foreman via PXE.
returned: success
type: dict
sample: '
{
"net0": "3E:6E:97:D2:31:9F",
"net1": "B6:A1:FC:EF:78:A4"
}'
vmid:
description: The VM vmid.
returned: success
type: int
sample: 115
status:
description:
- The current virtual machine status.
- Returned only when C(state=current)
returned: success
type: dict
sample: '{
"changed": false,
"msg": "VM kropta with vmid = 110 is running",
"status": "running"
}'
'''
import os
import time
try:
from proxmoxer import ProxmoxAPI
HAS_PROXMOXER = True
except ImportError:
HAS_PROXMOXER = False
VZ_TYPE = 'qemu'
def get_nextvmid(proxmox):
try:
vmid = proxmox.cluster.nextid.get()
return vmid
except Exception as e:
module.fail_json(msg="Unable to get next vmid. Failed with exception: %s")
def get_vmid(proxmox, name):
return [vm['vmid'] for vm in proxmox.cluster.resources.get(type='vm') if vm['name'] == name]
def get_vm(proxmox, vmid):
return [vm for vm in proxmox.cluster.resources.get(type='vm') if vm['vmid'] == int(vmid)]
def node_check(proxmox, node):
return [True for nd in proxmox.nodes.get() if nd['node'] == node]
def get_vminfo(module, proxmox, node, vmid, **kwargs):
global results
results = {}
mac = {}
devices = {}
try:
vm = proxmox.nodes(node).qemu(vmid).config.get()
except Exception as e:
module.fail_json(msg='Getting information for VM with vmid = %s failed with exception: %s' % (vmid, e))
# Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
# Convert all dict in kwargs to elements. For hostpci[n], ide[n], net[n], numa[n], parallel[n], sata[n], scsi[n], serial[n], virtio[n]
for k in kwargs.keys():
if isinstance(kwargs[k], dict):
kwargs.update(kwargs[k])
del kwargs[k]
# Split information by type
for k, v in kwargs.items():
if re.match(r'net[0-9]', k) is not None:
interface = k
k = vm[k]
k = re.search('=(.*?),', k).group(1)
mac[interface] = k
if re.match(r'virtio[0-9]', k) is not None or re.match(r'ide[0-9]', k) is not None or re.match(r'scsi[0-9]', k) is not None or re.match(r'sata[0-9]', k) is not None:
device = k
k = vm[k]
k = re.search('(.*?),', k).group(1)
devices[device] = k
results['mac'] = mac
results['devices'] = devices
results['vmid'] = int(vmid)
def settings(module, proxmox, vmid, node, name, timeout, **kwargs):
proxmox_node = proxmox.nodes(node)
# Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
if getattr(proxmox_node, VZ_TYPE)(vmid).config.set(**kwargs) is None:
return True
else:
return False
def create_vm(module, proxmox, vmid, newid, node, name, memory, cpu, cores, sockets, timeout, update, **kwargs):
# Available only in PVE 4
only_v4 = ['force', 'protection', 'skiplock']
# valide clone parameters
valid_clone_params = ['format', 'full', 'pool', 'snapname', 'storage', 'target']
clone_params = {}
# Default args for vm. Note: -args option is for experts only. It allows you to pass arbitrary arguments to kvm.
vm_args = "-serial unix:/var/run/qemu-server/{}.serial,server,nowait".format(vmid)
proxmox_node = proxmox.nodes(node)
# Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
kwargs = dict((k,v) for k, v in kwargs.items() if v is not None)
kwargs.update(dict([k, int(v)] for k, v in kwargs.items() if isinstance(v, bool)))
# The features work only on PVE 4
if PVE_MAJOR_VERSION < 4:
for p in only_v4:
if p in kwargs:
del kwargs[p]
# If update, don't update disk (virtio, ide, sata, scsi) and network interface
if update:
if 'virtio' in kwargs:
del kwargs['virtio']
if 'sata' in kwargs:
del kwargs['sata']
if 'scsi' in kwargs:
del kwargs['scsi']
if 'ide' in kwargs:
del kwargs['ide']
if 'net' in kwargs:
del kwargs['net']
# Convert all dict in kwargs to elements. For hostpci[n], ide[n], net[n], numa[n], parallel[n], sata[n], scsi[n], serial[n], virtio[n]
for k in kwargs.keys():
if isinstance(kwargs[k], dict):
kwargs.update(kwargs[k])
del kwargs[k]
# Rename numa_enabled to numa. According the API documentation
if 'numa_enabled' in kwargs:
kwargs['numa'] = kwargs['numa_enabled']
del kwargs['numa_enabled']
# -args and skiplock require root@pam user
if module.params['api_user'] == "root@pam" and module.params['args'] is None:
if not update:
kwargs['args'] = vm_args
elif module.params['api_user'] == "root@pam" and module.params['args'] is not None:
kwargs['args'] = module.params['args']
elif module.params['api_user'] != "root@pam" and module.params['args'] is not None:
module.fail_json(msg='args parameter require root@pam user. ')
if module.params['api_user'] != "root@pam" and module.params['skiplock'] is not None:
module.fail_json(msg='skiplock parameter require root@pam user. ')
if update:
if getattr(proxmox_node, VZ_TYPE)(vmid).config.set(name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs) is None:
return True
else:
return False
elif module.params['clone'] is not None:
for param in valid_clone_params:
if module.params[param] is not None:
clone_params[param] = module.params[param]
clone_params.update(dict([k, int(v)] for k, v in clone_params.items() if isinstance(v, bool)))
taskid = proxmox_node.qemu(vmid).clone.post(newid=newid, name=name, **clone_params)
else:
taskid = getattr(proxmox_node, VZ_TYPE).create(vmid=vmid, name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs)
while timeout:
if (proxmox_node.tasks(taskid).status.get()['status'] == 'stopped'
and proxmox_node.tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True
timeout = timeout - 1
if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for creating VM. Last line in task before timeout: %s'
% proxmox_node.tasks(taskid).log.get()[:1])
time.sleep(1)
return False
def start_vm(module, proxmox, vm, vmid, timeout):
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.start.post()
while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped'
and proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK' ):
return True
timeout = timeout - 1
if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for starting VM. Last line in task before timeout: %s'
% proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1)
return False
def stop_vm(module, proxmox, vm, vmid, timeout, force):
if force:
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.shutdown.post(forceStop=1)
else:
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.shutdown.post()
while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped'
and proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True
timeout = timeout - 1
if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for stopping VM. Last line in task before timeout: %s'
% proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1)
return False
def main():
module = AnsibleModule(
argument_spec = dict(
acpi = dict(type='bool', default='yes'),
agent = dict(type='bool'),
args = dict(type='str', default=None),
api_host = dict(required=True),
api_user = dict(required=True),
api_password = dict(no_log=True),
autostart = dict(type='bool', default='no'),
balloon = dict(type='int',default=0),
bios = dict(choices=['seabios', 'ovmf']),
boot = dict(type='str', default='cnd'),
bootdisk = dict(type='str'),
clone = dict(type='str', default=None),
cores = dict(type='int', default=1),
cpu = dict(type='str', default='kvm64'),
cpulimit = dict(type='int'),
cpuunits = dict(type='int', default=1000),
delete = dict(type='str', default=None),
description = dict(type='str'),
digest = dict(type='str'),
force = dict(type='bool', default=None),
format = dict(type='str', default='qcow2', choices=['cloop', 'cow', 'qcow', 'qcow2', 'qed', 'raw', 'vmdk' ]),
freeze = dict(type='bool'),
full = dict(type='bool', default='yes'),
hostpci = dict(type='dict'),
hotplug = dict(type='str'),
hugepages = dict(choices=['any', '2', '1024']),
ide = dict(type='dict', default=None),
keyboard = dict(type='str'),
kvm = dict(type='bool', default='yes'),
localtime = dict(type='bool'),
lock = dict(choices=['migrate', 'backup', 'snapshot', 'rollback']),
machine = dict(type='str'),
memory = dict(type='int', default=512),
migrate_downtime = dict(type='int'),
migrate_speed = dict(type='int'),
name = dict(type='str'),
net = dict(type='dict'),
newid = dict(type='int', default=None),
node = dict(),
numa = dict(type='dict'),
numa_enabled = dict(type='bool'),
onboot = dict(type='bool', default='yes'),
ostype = dict(default='l26', choices=['other', 'wxp', 'w2k', 'w2k3', 'w2k8', 'wvista', 'win7', 'win8', 'l24', 'l26', 'solaris']),
parallel = dict(type='dict'),
pool = dict(type='str'),
protection = dict(type='bool'),
reboot = dict(type='bool'),
revert = dict(type='str', default=None),
sata = dict(type='dict'),
scsi = dict(type='dict'),
scsihw = dict(choices=['lsi', 'lsi53c810', 'virtio-scsi-pci', 'virtio-scsi-single', 'megasas', 'pvscsi']),
serial = dict(type='dict'),
shares = dict(type='int'),
skiplock = dict(type='bool'),
smbios = dict(type='str'),
snapname = dict(type='str'),
sockets = dict(type='int', default=1),
startdate = dict(type='str'),
startup = dict(),
state = dict(default='present', choices=['present', 'absent', 'stopped', 'started', 'restarted', 'current']),
storage = dict(type='str'),
tablet = dict(type='bool', default='no'),
target = dict(type='str'),
tdf = dict(type='bool'),
template = dict(type='bool', default='no'),
timeout = dict(type='int', default=30),
update = dict(type='bool', default='no'),
validate_certs = dict(type='bool', default='no'),
vcpus = dict(type='int', default=None),
vga = dict(default='std', choices=['std', 'cirrus', 'vmware', 'qxl', 'serial0', 'serial1', 'serial2', 'serial3', 'qxl2', 'qxl3', 'qxl4']),
virtio = dict(type='dict', default=None),
vmid = dict(type='int', default=None),
watchdog = dict(),
),
mutually_exclusive = [('delete', 'revert'), ('delete','update'), ('revert','update'), ('clone', 'update'), ('clone', 'delete'), ('clone','revert')],
required_one_of=[('name','vmid',)],
required_if=[('state', 'present', ['node'])]
)
if not HAS_PROXMOXER:
module.fail_json(msg='proxmoxer required for this module')
api_user = module.params['api_user']
api_host = module.params['api_host']
api_password = module.params['api_password']
clone = module.params['clone']
cpu = module.params['cpu']
cores = module.params['cores']
delete = module.params['delete']
memory = module.params['memory']
name = module.params['name']
newid = module.params['newid']
node = module.params['node']
revert = module.params['revert']
sockets = module.params['sockets']
state = module.params['state']
timeout = module.params['timeout']
update = bool(module.params['update'])
vmid = module.params['vmid']
validate_certs = module.params['validate_certs']
# If password not set get it from PROXMOX_PASSWORD env
if not api_password:
try:
api_password = os.environ['PROXMOX_PASSWORD']
except KeyError as e:
module.fail_json(msg='You should set api_password param or use PROXMOX_PASSWORD environment variable')
try:
proxmox = ProxmoxAPI(api_host, user=api_user, password=api_password, verify_ssl=validate_certs)
global VZ_TYPE
global PVE_MAJOR_VERSION
PVE_MAJOR_VERSION = 3 if float(proxmox.version.get()['version']) < 4.0 else 4
except Exception as e:
module.fail_json(msg='authorization on proxmox cluster failed with exception: %s' % e)
# If vmid not set get the Next VM id from ProxmoxAPI
# If vm name is set get the VM id from ProxmoxAPI
if not vmid:
if state == 'present' and ( not update and not clone) and (not delete and not revert):
try:
vmid = get_nextvmid(proxmox)
except Exception as e:
module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name))
else:
try:
if not clone:
vmid = get_vmid(proxmox, name)[0]
else:
vmid = get_vmid(proxmox, clone)[0]
except Exception as e:
if not clone:
module.fail_json(msg="VM {} does not exist in cluster.".format(name))
else:
module.fail_json(msg="VM {} does not exist in cluster.".format(clone))
if clone is not None:
if get_vmid(proxmox, name):
module.exit_json(changed=False, msg="VM with name <%s> already exists" % name)
if vmid is not None:
vm = get_vm(proxmox, vmid)
if not vm:
module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid)
if not newid:
try:
newid = get_nextvmid(proxmox)
except Exception as e:
module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name))
else:
vm = get_vm(proxmox, newid)
if vm:
module.exit_json(changed=False, msg="vmid %s with VM name %s already exists" % (newid, name))
if delete is not None:
try:
settings(module, proxmox, vmid, node, name, timeout, delete=delete)
module.exit_json(changed=True, msg="Settings has deleted on VM {} with vmid {}".format(name, vmid))
except Exception as e:
module.fail_json(msg='Unable to delete settings on VM {} with vimd {}: '.format(name, vmid) + str(e))
elif revert is not None:
try:
settings(module, proxmox, vmid, node, name, timeout, revert=revert)
module.exit_json(changed=True, msg="Settings has reverted on VM {} with vmid {}".format(name, vmid))
except Exception as e:
module.fail_json(msg='Unable to revert settings on VM {} with vimd {}: Maybe is not a pending task... '.format(name, vmid) + str(e))
if state == 'present':
try:
if get_vm(proxmox, vmid) and not (update or clone):
module.exit_json(changed=False, msg="VM with vmid <%s> already exists" % vmid)
elif get_vmid(proxmox, name) and not (update or clone):
module.exit_json(changed=False, msg="VM with name <%s> already exists" % name)
elif not (node, name):
module.fail_json(msg='node, name is mandatory for creating/updating vm')
elif not node_check(proxmox, node):
module.fail_json(msg="node '%s' does not exist in cluster" % node)
create_vm(module, proxmox, vmid, newid, node, name, memory, cpu, cores, sockets, timeout, update,
acpi = module.params['acpi'],
agent = module.params['agent'],
autostart = module.params['autostart'],
balloon = module.params['balloon'],
bios = module.params['bios'],
boot = module.params['boot'],
bootdisk = module.params['bootdisk'],
cpulimit = module.params['cpulimit'],
cpuunits = module.params['cpuunits'],
description = module.params['description'],
digest = module.params['digest'],
force = module.params['force'],
freeze = module.params['freeze'],
hostpci = module.params['hostpci'],
hotplug = module.params['hotplug'],
hugepages = module.params['hugepages'],
ide = module.params['ide'],
keyboard = module.params['keyboard'],
kvm = module.params['kvm'],
localtime = module.params['localtime'],
lock = module.params['lock'],
machine = module.params['machine'],
migrate_downtime = module.params['migrate_downtime'],
migrate_speed = module.params['migrate_speed'],
net = module.params['net'],
numa = module.params['numa'],
numa_enabled = module.params['numa_enabled'],
onboot = module.params['onboot'],
ostype = module.params['ostype'],
parallel = module.params['parallel'],
pool = module.params['pool'],
protection = module.params['protection'],
reboot = module.params['reboot'],
sata = module.params['sata'],
scsi = module.params['scsi'],
scsihw = module.params['scsihw'],
serial = module.params['serial'],
shares = module.params['shares'],
skiplock = module.params['skiplock'],
smbios1 = module.params['smbios'],
snapname = module.params['snapname'],
startdate = module.params['startdate'],
startup = module.params['startup'],
tablet = module.params['tablet'],
target = module.params['target'],
tdf = module.params['tdf'],
template = module.params['template'],
vcpus = module.params['vcpus'],
vga = module.params['vga'],
virtio = module.params['virtio'],
watchdog = module.params['watchdog'])
if not clone:
get_vminfo(module, proxmox, node, vmid,
ide = module.params['ide'],
net = module.params['net'],
sata = module.params['sata'],
scsi = module.params['scsi'],
virtio = module.params['virtio'])
if update:
module.exit_json(changed=True, msg="VM %s with vmid %s updated" % (name, vmid))
elif clone is not None:
module.exit_json(changed=True, msg="VM %s with newid %s cloned from vm with vmid %s" % (name, newid, vmid))
else:
module.exit_json(changed=True, msg="VM %s with vmid %s deployed" % (name, vmid), **results)
except Exception as e:
if update:
module.fail_json(msg="Unable to update vm {} with vimd {}=".format(name, vmid) + str(e))
elif clone is not None:
module.fail_json(msg="Unable to clone vm {} from vimd {}=".format(name, vmid) + str(e))
else:
module.fail_json(msg="creation of %s VM %s with vmid %s failed with exception=%s" % (VZ_TYPE, name, vmid, e))
elif state == 'started':
try:
vm = get_vm(proxmox, vmid)
if not vm:
module.fail_json(msg='VM with vmid <%s> does not exist in cluster' % vmid)
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'running':
module.exit_json(changed=False, msg="VM %s is already running" % vmid)
if start_vm(module, proxmox, vm, vmid, timeout):
module.exit_json(changed=True, msg="VM %s started" % vmid)
except Exception as e:
module.fail_json(msg="starting of VM %s failed with exception: %s" % (vmid, e))
elif state == 'stopped':
try:
vm = get_vm(proxmox, vmid)
if not vm:
module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid)
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
module.exit_json(changed=False, msg="VM %s is already stopped" % vmid)
if stop_vm(module, proxmox, vm, vmid, timeout, force = module.params['force']):
module.exit_json(changed=True, msg="VM %s is shutting down" % vmid)
except Exception as e:
module.fail_json(msg="stopping of VM %s failed with exception: %s" % (vmid, e))
elif state == 'restarted':
try:
vm = get_vm(proxmox, vmid)
if not vm:
module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid)
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
module.exit_json(changed=False, msg="VM %s is not running" % vmid)
if (stop_vm(module, proxmox, vm, vmid, timeout, force = module.params['force'])
and start_vm(module, proxmox, vm, vmid, timeout)):
module.exit_json(changed=True, msg="VM %s is restarted" % vmid)
except Exception as e:
module.fail_json(msg="restarting of VM %s failed with exception: %s" % ( vmid, e ))
elif state == 'absent':
try:
vm = get_vm(proxmox, vmid)
if not vm:
module.exit_json(changed=False, msg="VM %s does not exist" % vmid)
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'running':
module.exit_json(changed=False, msg="VM %s is running. Stop it before deletion." % vmid)
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE).delete(vmid)
while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped'
and proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK' ):
module.exit_json(changed=True, msg="VM %s removed" % vmid)
timeout = timeout - 1
if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for removing VM. Last line in task before timeout: %s'
% proxmox_node.tasks(taskid).log.get()[:1])
time.sleep(1)
except Exception as e:
module.fail_json(msg="deletion of VM %s failed with exception: %s" % (vmid, e))
elif state == 'current':
status = {}
try:
vm = get_vm(proxmox, vmid)
if not vm:
module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid)
current = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status']
status['status'] = current
if status:
module.exit_json(changed=False, msg="VM %s with vmid = %s is %s" % (name, vmid, current), **status)
except Exception as e:
module.fail_json(msg="Unable to get vm {} with vmid = {} status: ".format(name, vmid) + str(e))
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| gpl-3.0 |
nirmeshk/oh-mainline | vendor/packages/Django/django/contrib/gis/db/models/manager.py | 505 | 3578 | from django.db.models.manager import Manager
from django.contrib.gis.db.models.query import GeoQuerySet
class GeoManager(Manager):
"Overrides Manager to return Geographic QuerySets."
# This manager should be used for queries on related fields
# so that geometry columns on Oracle and MySQL are selected
# properly.
use_for_related_fields = True
def get_query_set(self):
return GeoQuerySet(self.model, using=self._db)
def area(self, *args, **kwargs):
return self.get_query_set().area(*args, **kwargs)
def centroid(self, *args, **kwargs):
return self.get_query_set().centroid(*args, **kwargs)
def collect(self, *args, **kwargs):
return self.get_query_set().collect(*args, **kwargs)
def difference(self, *args, **kwargs):
return self.get_query_set().difference(*args, **kwargs)
def distance(self, *args, **kwargs):
return self.get_query_set().distance(*args, **kwargs)
def envelope(self, *args, **kwargs):
return self.get_query_set().envelope(*args, **kwargs)
def extent(self, *args, **kwargs):
return self.get_query_set().extent(*args, **kwargs)
def extent3d(self, *args, **kwargs):
return self.get_query_set().extent3d(*args, **kwargs)
def force_rhr(self, *args, **kwargs):
return self.get_query_set().force_rhr(*args, **kwargs)
def geohash(self, *args, **kwargs):
return self.get_query_set().geohash(*args, **kwargs)
def geojson(self, *args, **kwargs):
return self.get_query_set().geojson(*args, **kwargs)
def gml(self, *args, **kwargs):
return self.get_query_set().gml(*args, **kwargs)
def intersection(self, *args, **kwargs):
return self.get_query_set().intersection(*args, **kwargs)
def kml(self, *args, **kwargs):
return self.get_query_set().kml(*args, **kwargs)
def length(self, *args, **kwargs):
return self.get_query_set().length(*args, **kwargs)
def make_line(self, *args, **kwargs):
return self.get_query_set().make_line(*args, **kwargs)
def mem_size(self, *args, **kwargs):
return self.get_query_set().mem_size(*args, **kwargs)
def num_geom(self, *args, **kwargs):
return self.get_query_set().num_geom(*args, **kwargs)
def num_points(self, *args, **kwargs):
return self.get_query_set().num_points(*args, **kwargs)
def perimeter(self, *args, **kwargs):
return self.get_query_set().perimeter(*args, **kwargs)
def point_on_surface(self, *args, **kwargs):
return self.get_query_set().point_on_surface(*args, **kwargs)
def reverse_geom(self, *args, **kwargs):
return self.get_query_set().reverse_geom(*args, **kwargs)
def scale(self, *args, **kwargs):
return self.get_query_set().scale(*args, **kwargs)
def snap_to_grid(self, *args, **kwargs):
return self.get_query_set().snap_to_grid(*args, **kwargs)
def svg(self, *args, **kwargs):
return self.get_query_set().svg(*args, **kwargs)
def sym_difference(self, *args, **kwargs):
return self.get_query_set().sym_difference(*args, **kwargs)
def transform(self, *args, **kwargs):
return self.get_query_set().transform(*args, **kwargs)
def translate(self, *args, **kwargs):
return self.get_query_set().translate(*args, **kwargs)
def union(self, *args, **kwargs):
return self.get_query_set().union(*args, **kwargs)
def unionagg(self, *args, **kwargs):
return self.get_query_set().unionagg(*args, **kwargs)
| agpl-3.0 |
ff94315/hiwifi-openwrt-HC5661-HC5761 | staging_dir/host/lib/scons-2.1.0/SCons/Tool/mslib.py | 21 | 2227 | """SCons.Tool.mslib
Tool-specific initialization for lib (MicroSoft library archiver).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/mslib.py 5357 2011/09/09 21:31:03 bdeegan"
import SCons.Defaults
import SCons.Tool
import SCons.Tool.msvs
import SCons.Tool.msvc
import SCons.Util
from MSCommon import msvc_exists, msvc_setup_env_once
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
# Set-up ms tools paths
msvc_setup_env_once(env)
env['AR'] = 'lib'
env['ARFLAGS'] = SCons.Util.CLVar('/nologo')
env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}"
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
def exists(env):
return msvc_exists()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| gpl-2.0 |
avlasov-mos-de/mos-tempest-runner | setup.py | 608 | 1045 | #!/usr/bin/env python
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr'],
pbr=True)
| apache-2.0 |
fnouama/intellij-community | python/testData/inspections/PyMissingConstructorInspection/py3k.py | 83 | 1072 | class A(object):
def __init__(self):
pass
class AA(A):
def __init__(self):
A.__init__(self)
print("Constructor AA was called")
class B(A):
def <warning descr="Call to __init__ of super class is missed">__init__</warning>(self):
print("Constructor B was called")
class C(B):
def __init__(self):
super(C, self).__init__()
print("Constructor C was called")
class A2:
def __init__(self):
print("A2 __init__")
class B2(A2):
def __init__(self):
A2.__init__(self)
print("Constructor B was called")
class C2(B2):
def <warning descr="Call to __init__ of super class is missed">__init__</warning>(self):
print("Constructor C2 was called")
class D2(C2):
def __init__(self):
super(C2, self).__init__()
print("Constructor D2 was called")
class E2(A2):
def __init__(self):
super().__init__()
print("Constructor E2 was called")
class F2(A2):
def <warning descr="Call to __init__ of super class is missed">__init__</warning>(self):
super(D2, self).__init__()
print("Constructor F2 was called") | apache-2.0 |
EdLogan18/logan-repository | plugin.video.MediaPlay-TV/pkcs7.py | 111 | 1943 | import binascii
import StringIO
class PKCS7Encoder(object):
'''
RFC 2315: PKCS#7 page 21
Some content-encryption algorithms assume the
input length is a multiple of k octets, where k > 1, and
let the application define a method for handling inputs
whose lengths are not a multiple of k octets. For such
algorithms, the method shall be to pad the input at the
trailing end with k - (l mod k) octets all having value k -
(l mod k), where l is the length of the input. In other
words, the input is padded at the trailing end with one of
the following strings:
01 -- if l mod k = k-1
02 02 -- if l mod k = k-2
.
.
.
k k ... k k -- if l mod k = 0
The padding can be removed unambiguously since all input is
padded and no padding string is a suffix of another. This
padding method is well-defined if and only if k < 256;
methods for larger k are an open issue for further study.
'''
def __init__(self, k=16):
self.k = k
## @param text The padded text for which the padding is to be removed.
# @exception ValueError Raised when the input padding is missing or corrupt.
def decode(self, text):
'''
Remove the PKCS#7 padding from a text string
'''
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')
l = nl - val
return text[:l]
## @param text The text to encode.
def encode(self, text):
'''
Pad an input string according to PKCS#7
'''
l = len(text)
output = StringIO.StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
output.write('%02x' % val)
return text + binascii.unhexlify(output.getvalue()) | gpl-2.0 |
priyaganti/rockstor-core | src/rockstor/smart_manager/replication/listener_broker.py | 2 | 15022 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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.
RockStor 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 multiprocessing import Process
import zmq
import os
import json
import time
from storageadmin.models import (NetworkConnection, Appliance)
from smart_manager.models import (ReplicaTrail, ReplicaShare, Replica, Service)
from django.conf import settings
from sender import Sender
from receiver import Receiver
from util import ReplicationMixin
from cli import APIWrapper
import logging
logger = logging.getLogger(__name__)
class ReplicaScheduler(ReplicationMixin, Process):
def __init__(self):
self.ppid = os.getpid()
self.senders = {} # Active Sender(outgoing) process map.
self.receivers = {} # Active Receiver process map.
self.remote_senders = {} # Active incoming/remote Sender/client map.
self.MAX_ATTEMPTS = settings.REPLICATION.get('max_send_attempts')
self.uuid = self.listener_interface = self.listener_port = None
self.trail_prune_time = None
super(ReplicaScheduler, self).__init__()
def _prune_workers(self, workers):
for wd in workers:
for w in wd.keys():
if (wd[w].exitcode is not None):
del(wd[w])
logger.debug('deleted worker: %s' % w)
return workers
def _prune_senders(self):
for s in self.senders.keys():
ecode = self.senders[s].exitcode
if (ecode is not None):
del self.senders[s]
logger.debug('Sender(%s) exited. exitcode: %s' % (s, ecode))
if (len(self.senders) > 0):
logger.debug('Active Senders: %s' % self.senders.keys())
def _delete_receivers(self):
active_msgs = []
for r in self.local_receivers.keys():
msg_count = self.remote_senders.get(r, 0)
ecode = self.local_receivers[r].exitcode
if (ecode is not None):
del self.local_receivers[r]
if (r in self.remote_senders):
del self.remote_senders[r]
logger.debug('Receiver(%s) exited. exitcode: %s. Total '
'messages processed: %d. Removing from the list.'
% (r, ecode, msg_count))
else:
active_msgs.append('Active Receiver: %s. Total messages '
'processed: %d' % (r, msg_count))
for m in active_msgs:
logger.debug(m)
def _get_receiver_ip(self, replica):
if (replica.replication_ip is not None):
return replica.replication_ip
try:
appliance = Appliance.objects.get(uuid=replica.appliance)
return appliance.ip
except Exception as e:
msg = ('Failed to get receiver ip. Is the receiver '
'appliance added?. Exception: %s' % e.__str__())
logger.error(msg)
raise Exception(msg)
def _process_send(self, replica):
sender_key = ('%s_%s' % (self.uuid, replica.id))
if (sender_key in self.senders):
# If the sender exited but hasn't been removed from the dict,
# remove and proceed.
ecode = self.senders[sender_key].exitcode
if (ecode is not None):
del self.senders[sender_key]
logger.debug('Sender(%s) exited. exitcode: %s. Forcing '
'removal.' % (sender_key, ecode))
else:
raise Exception('There is live sender for(%s). Will not start '
'a new one.' % sender_key)
receiver_ip = self._get_receiver_ip(replica)
rt_qs = ReplicaTrail.objects.filter(replica=replica).order_by('-id')
last_rt = rt_qs[0] if (len(rt_qs) > 0) else None
if (last_rt is None):
logger.debug('Starting a new Sender(%s).' % sender_key)
self.senders[sender_key] = Sender(self.uuid, receiver_ip, replica)
elif (last_rt.status == 'succeeded'):
logger.debug('Starting a new Sender(%s)' % sender_key)
self.senders[sender_key] = Sender(self.uuid, receiver_ip, replica,
last_rt)
elif (last_rt.status == 'pending'):
msg = ('Replica trail shows a pending Sender(%s), but it is not '
'alive. Marking it as failed. Will not start a new one.' %
sender_key)
logger.error(msg)
data = {'status': 'failed',
'error': msg, }
self.update_replica_status(last_rt.id, data)
raise Exception(msg)
elif (last_rt.status == 'failed'):
# if num_failed attempts > 10, disable the replica
num_tries = 0
for rto in rt_qs:
if (rto.status != 'failed' or
num_tries >= self.MAX_ATTEMPTS or
rto.end_ts < replica.ts):
break
num_tries = num_tries + 1
if (num_tries >= self.MAX_ATTEMPTS):
msg = ('Maximum attempts(%d) reached for Sender(%s). '
'A new one '
'will not be started and the Replica task will be '
'disabled.' % (self.MAX_ATTEMPTS, sender_key))
logger.error(msg)
self.disable_replica(replica.id)
raise Exception(msg)
logger.debug('previous backup failed for Sender(%s). '
'Starting a new one. Attempt %d/%d.' %
(sender_key, num_tries, self.MAX_ATTEMPTS))
try:
last_success_rt = ReplicaTrail.objects.filter(
replica=replica, status='succeeded').latest('id')
except ReplicaTrail.DoesNotExist:
logger.debug('No record of last successful ReplicaTrail for '
'Sender(%s). Will start a new Full Sender.' %
sender_key)
last_success_rt = None
self.senders[sender_key] = Sender(self.uuid, receiver_ip, replica,
last_success_rt)
else:
msg = ('Unexpected ReplicaTrail status(%s) for Sender(%s). '
'Will not start a new one.' % (last_rt.status, sender_key))
raise Exception(msg)
# to kill all senders in case scheduler dies.
self.senders[sender_key].daemon = True
self.senders[sender_key].start()
def run(self):
self.law = APIWrapper()
try:
so = Service.objects.get(name='replication')
config_d = json.loads(so.config)
self.listener_port = int(config_d['listener_port'])
nco = NetworkConnection.objects.get(
name=config_d['network_interface'])
self.listener_interface = nco.ipaddr
except NetworkConnection.DoesNotExist:
self.listener_interface = '0.0.0.0'
except Exception as e:
msg = ('Failed to fetch network interface for Listner/Broker. '
'Exception: %s' % e.__str__())
return logger.error(msg)
try:
self.uuid = Appliance.objects.get(current_appliance=True).uuid
except Exception as e:
msg = ('Failed to get uuid of current appliance. Aborting. '
'Exception: %s' % e.__str__())
return logger.error(msg)
ctx = zmq.Context()
frontend = ctx.socket(zmq.ROUTER)
frontend.set_hwm(10)
frontend.bind('tcp://%s:%d'
% (self.listener_interface, self.listener_port))
backend = ctx.socket(zmq.ROUTER)
backend.bind('ipc://%s' % settings.REPLICATION.get('ipc_socket'))
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)
self.local_receivers = {}
iterations = 10
poll_interval = 6000 # 6 seconds
msg_count = 0
while True:
# This loop may still continue even if replication service
# is terminated, as long as data is coming in.
socks = dict(poller.poll(timeout=poll_interval))
if (frontend in socks and socks[frontend] == zmq.POLLIN):
address, command, msg = frontend.recv_multipart()
if (address not in self.remote_senders):
self.remote_senders[address] = 1
else:
self.remote_senders[address] += 1
msg_count += 1
if (msg_count == 1000):
msg_count = 0
for rs, count in self.remote_senders.items():
logger.debug('Active Receiver: %s. Messages processed:'
'%d' % (rs, count))
if (command == 'sender-ready'):
logger.debug('initial greeting from %s' % address)
# Start a new receiver and send the appropriate response
try:
start_nr = True
if (address in self.local_receivers):
start_nr = False
ecode = self.local_receivers[address].exitcode
if (ecode is not None):
del self.local_receivers[address]
logger.debug('Receiver(%s) exited. exitcode: '
'%s. Forcing removal from broker '
'list.' % (address, ecode))
start_nr = True
else:
msg = ('Receiver(%s) already exists. '
'Will not start a new one.' %
address)
logger.error(msg)
# @todo: There may be a different way to handle
# this. For example, we can pass the message to
# the active receiver and factor into it's
# retry/robust logic. But that is for later.
frontend.send_multipart(
[address, 'receiver-init-error', msg])
if (start_nr):
nr = Receiver(address, msg)
nr.daemon = True
nr.start()
logger.debug('New Receiver(%s) started.' % address)
self.local_receivers[address] = nr
continue
except Exception as e:
msg = ('Exception while starting the '
'new receiver for %s: %s'
% (address, e.__str__()))
logger.error(msg)
frontend.send_multipart(
[address, 'receiver-init-error', msg])
else:
# do we hit hwm? is the dealer still connected?
backend.send_multipart([address, command, msg])
elif (backend in socks and socks[backend] == zmq.POLLIN):
address, command, msg = backend.recv_multipart()
if (command == 'new-send'):
rid = int(msg)
logger.debug('new-send request received for %d' % rid)
rcommand = 'ERROR'
try:
replica = Replica.objects.get(id=rid)
if (replica.enabled):
self._process_send(replica)
msg = ('A new Sender started successfully for '
'Replication Task(%d).' % rid)
rcommand = 'SUCCESS'
else:
msg = ('Failed to start a new Sender for '
'Replication '
'Task(%d) because it is disabled.' % rid)
except Exception as e:
msg = ('Failed to start a new Sender for Replication '
'Task(%d). Exception: %s' % (rid, e.__str__()))
logger.error(msg)
finally:
backend.send_multipart([address, rcommand, str(msg)])
elif (address in self.remote_senders):
if (command in ('receiver-ready', 'receiver-error', 'btrfs-recv-finished')): # noqa E501
logger.debug('Identitiy: %s command: %s'
% (address, command))
backend.send_multipart([address, b'ACK', ''])
# a new receiver has started. reply to the sender that
# must be waiting
frontend.send_multipart([address, command, msg])
else:
iterations -= 1
if (iterations == 0):
iterations = 10
self._prune_senders()
self._delete_receivers()
cur_time = time.time()
if (self.trail_prune_time is None or
(cur_time - self.trail_prune_time) > 3600):
# prune send/receive trails every hour or so.
self.trail_prune_time = cur_time
map(self.prune_replica_trail, Replica.objects.filter())
map(self.prune_receive_trail,
ReplicaShare.objects.filter())
logger.debug('Replica trails are truncated '
'successfully.')
if (os.getppid() != self.ppid):
logger.error('Parent exited. Aborting.')
ctx.destroy()
# do some cleanup of senders before quitting?
break
def main():
rs = ReplicaScheduler()
rs.start()
rs.join()
| gpl-3.0 |
cfchou/choreography | choreography/launcher.py | 1 | 2392 |
import sys
import asyncio
import os
import types
import functools
from collections import namedtuple
from collections.abc import Iterator
import abc
from typing import List, Union, NamedTuple
import uuid
import yaml
import logging
log = logging.getLogger(__name__)
Fire = NamedTuple('Fire', [('rate', int), ('duration', int),
('supervisor', str)])
Idle = NamedTuple('Idle', [])
Terminate = NamedTuple('Terminate', [])
RunnerHistoryItem = NamedTuple('RunnerHistoryItem',
[('at', int), ('succeeded', int),
('failed', int)])
class LauncherResp(object):
def __init__(self, action: Union[Fire, Idle], opaque=None):
self.action = action
self.opaque = opaque
def is_fire(self):
return isinstance(self.action, Fire)
def is_idle(self):
return isinstance(self.action, Idle)
def is_terminate(self):
return isinstance(self.action, Terminate)
class RunnerContext(object):
def __init__(self, host: str, history: List[RunnerHistoryItem]):
self.host = host
self._history = [] if history is None else history
self.opaque = None
def update(self, prev_resp: LauncherResp, history: List[RunnerHistoryItem]):
self._history = history
self.opaque = prev_resp.opaque
@staticmethod
def new_conext(host: str=''):
if not host:
host = uuid.uuid1().hex
return RunnerContext(host, [])
class Launcher(metaclass=abc.ABCMeta):
@abc.abstractmethod
def ask_next(self, runner_ctx: RunnerContext) -> LauncherResp:
"""
:param runner_ctx:
:return:
"""
class IdleLancher(Launcher):
def ask_next(self, runner_ctx: RunnerContext) -> LauncherResp:
log.debug('runner_ctx:{}'.format(runner_ctx))
return LauncherResp(Idle())
class OneShotLancher(Launcher):
def ask_next(self, runner_ctx: RunnerContext) -> LauncherResp:
log.debug('runner_ctx:{}'.format(runner_ctx.__dict__))
if runner_ctx.opaque is not None:
return LauncherResp(Terminate())
else:
#return LauncherResp(Fire(rate=1, start=0, end=10, supervisor=''),
# opaque=1)
return LauncherResp(Fire(rate=1, duration=1, supervisor=''),
opaque=1)
| bsd-3-clause |
ahotam/micropython | tests/basics/gen_yield_from_ducktype.py | 107 | 1034 | class MyGen:
def __init__(self):
self.v = 0
def __iter__(self):
return self
def __next__(self):
self.v += 1
if self.v > 5:
raise StopIteration
return self.v
def gen():
yield from MyGen()
def gen2():
yield from gen()
print(list(gen()))
print(list(gen2()))
class Incrementer:
def __iter__(self):
return self
def __next__(self):
return self.send(None)
def send(self, val):
if val is None:
return "Incrementer initialized"
return val + 1
def gen3():
yield from Incrementer()
g = gen3()
print(next(g))
print(g.send(5))
print(g.send(100))
#
# Test proper handling of StopIteration vs other exceptions
#
class MyIter:
def __iter__(self):
return self
def __next__(self):
raise StopIteration(42)
def gen4():
global ret
ret = yield from MyIter()
1//0
ret = None
try:
print(list(gen4()))
except ZeroDivisionError:
print("ZeroDivisionError")
print(ret)
| mit |
kalyanjvn1/selenium | py/selenium/webdriver/remote/errorhandler.py | 14 | 9131 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.common.exceptions import (ElementNotInteractableException,
ElementNotSelectableException,
ElementNotVisibleException,
ErrorInResponseException,
InvalidElementStateException,
InvalidSelectorException,
ImeNotAvailableException,
ImeActivationFailedException,
MoveTargetOutOfBoundsException,
NoSuchElementException,
NoSuchFrameException,
NoSuchWindowException,
NoAlertPresentException,
StaleElementReferenceException,
TimeoutException,
UnexpectedAlertPresentException,
WebDriverException)
try:
basestring
except NameError: # Python 3.x
basestring = str
class ErrorCode(object):
"""
Error codes defined in the WebDriver wire protocol.
"""
# Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h
SUCCESS = 0
NO_SUCH_ELEMENT = [7, 'no such element']
NO_SUCH_FRAME = [8, 'no such frame']
UNKNOWN_COMMAND = [9, 'unknown command']
STALE_ELEMENT_REFERENCE = [10, 'stale element reference']
ELEMENT_NOT_VISIBLE = [11, 'element not visible']
INVALID_ELEMENT_STATE = [12, 'invalid element state']
UNKNOWN_ERROR = [13, 'unknown error']
ELEMENT_NOT_INTERACTABLE = ["element not interactable"]
ELEMENT_IS_NOT_SELECTABLE = [15, 'element not selectable']
JAVASCRIPT_ERROR = [17, 'javascript error']
XPATH_LOOKUP_ERROR = [19, 'invalid selector']
TIMEOUT = [21, 'timeout']
NO_SUCH_WINDOW = [23, 'no such window']
INVALID_COOKIE_DOMAIN = [24, 'invalid cookie domain']
UNABLE_TO_SET_COOKIE = [25, 'unable to set cookie']
UNEXPECTED_ALERT_OPEN = [26, 'unexpected alert open']
NO_ALERT_OPEN = [27, 'no such alert']
SCRIPT_TIMEOUT = [28, 'script timeout']
INVALID_ELEMENT_COORDINATES = [29, 'invalid element coordinates']
IME_NOT_AVAILABLE = [30, 'ime not available']
IME_ENGINE_ACTIVATION_FAILED = [31, 'ime engine activation failed']
INVALID_SELECTOR = [32, 'invalid selector']
MOVE_TARGET_OUT_OF_BOUNDS = [34, 'move target out of bounds']
INVALID_XPATH_SELECTOR = [51, 'invalid selector']
INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, 'invalid selector']
METHOD_NOT_ALLOWED = [405, 'unsupported operation']
class ErrorHandler(object):
"""
Handles errors returned by the WebDriver server.
"""
def check_response(self, response):
"""
Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message.
"""
status = response.get('status', None)
if status is None or status == ErrorCode.SUCCESS:
return
value = None
message = response.get("message", "")
screen = response.get("screen", "")
stacktrace = None
if isinstance(status, int):
value_json = response.get('value', None)
if value_json and isinstance(value_json, basestring):
import json
try:
value = json.loads(value_json)
if len(value.keys()) == 1:
value = value['value']
status = value.get('error', None)
if status is None:
status = value["status"]
message = value["value"]
if not isinstance(message, basestring):
value = message
message = message.get('message')
else:
message = value.get('message', None)
except ValueError:
pass
exception_class = ErrorInResponseException
if status in ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status in ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status in ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status in ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status in ErrorCode.INVALID_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectorException
elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
exception_class = ElementNotInteractableException
elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = WebDriverException
elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = WebDriverException
elif status in ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
exception_class = UnexpectedAlertPresentException
elif status in ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status in ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ImeActivationFailedException
elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
exception_class = MoveTargetOutOfBoundsException
else:
exception_class = WebDriverException
if value == '' or value is None:
value = response['value']
if isinstance(value, basestring):
if exception_class == ErrorInResponseException:
raise exception_class(response, value)
raise exception_class(value)
if message == "" and 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
stacktrace = []
try:
for frame in value['stackTrace']:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
except TypeError:
pass
if exception_class == ErrorInResponseException:
raise exception_class(response, message)
elif exception_class == UnexpectedAlertPresentException and 'alert' in value:
raise exception_class(message, screen, stacktrace, value['alert'].get('text'))
raise exception_class(message, screen, stacktrace)
def _value_or_default(self, obj, key, default):
return obj[key] if key in obj else default
| apache-2.0 |
bpsinc-native/src_third_party_scons-2.0.1 | engine/SCons/Tool/dvi.py | 61 | 2388 | """SCons.Tool.dvi
Common DVI Builder definition for various other Tool modules that use it.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/dvi.py 5134 2010/08/16 23:02:40 bdeegan"
import SCons.Builder
import SCons.Tool
DVIBuilder = None
def generate(env):
try:
env['BUILDERS']['DVI']
except KeyError:
global DVIBuilder
if DVIBuilder is None:
# The suffix is hard-coded to '.dvi', not configurable via a
# construction variable like $DVISUFFIX, because the output
# file name is hard-coded within TeX.
DVIBuilder = SCons.Builder.Builder(action = {},
source_scanner = SCons.Tool.LaTeXScanner,
suffix = '.dvi',
emitter = {},
source_ext_match = None)
env['BUILDERS']['DVI'] = DVIBuilder
def exists(env):
# This only puts a skeleton Builder in place, so if someone
# references this Tool directly, it's always "available."
return 1
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| mit |
Vimjas/covimerage | tests/test_coveragepy.py | 1 | 8791 | import sys
import attr
import coverage
import pytest
from covimerage._compat import StringIO
def test_filereporter():
from covimerage.coveragepy import FileReporter
f = FileReporter('/doesnotexist')
assert repr(f) == "<CovimerageFileReporter '/doesnotexist'>"
with pytest.raises(coverage.misc.NoSource) as excinfo:
f.lines()
assert excinfo.value.args == (
"[Errno 2] No such file or directory: '/doesnotexist'",)
def test_filereporter_source_handles_latin1(tmpdir):
from covimerage.coveragepy import FileReporter
with tmpdir.as_cwd():
with open('iso.txt', 'wb') as f:
f.write(b'Hellstr\xf6m')
with open('utf8.txt', 'wb') as f:
f.write(b'Hellstr\xc3\xb6m')
assert FileReporter('iso.txt').source().encode(
'utf-8') == b'Hellstr\xc3\xb6m'
assert FileReporter('iso.txt').source().encode(
'utf-8') == b'Hellstr\xc3\xb6m'
@pytest.mark.skipif(sys.version_info[0] == 3 and sys.version_info[1] < 5,
reason='Failed to patch open with py33/py34.')
def test_filereporter_source_exception(mocker, devnull):
from covimerage.coveragepy import CoverageWrapperException, FileReporter
class CustomException(Exception):
pass
m = mocker.mock_open()
m.return_value.read.side_effect = CustomException
mocker.patch('covimerage.coveragepy.open', m)
f = FileReporter(devnull.name)
with pytest.raises(CoverageWrapperException) as excinfo:
f.source()
assert isinstance(excinfo.value.orig_exc, CustomException)
@pytest.fixture
def coverage_fileobj():
return StringIO('\n'.join(['!coverage.py: This is a private format, don\'t read it directly!{"lines":{"/test_plugin/conditional_function.vim":[17,3,23,8,9,11,13,14,15]},"file_tracers":{"/test_plugin/conditional_function.vim":"covimerage.CoveragePlugin"}}']))
def test_coveragedata(coverage_fileobj):
import coverage
from covimerage.coveragepy import (
CoverageData, CoveragePyData, CoverageWrapperException)
with pytest.raises(TypeError) as excinfo:
CoverageData(data_file='foo', cov_data=CoveragePyData())
assert excinfo.value.args == (
'data and data_file are mutually exclusive.',)
data = CoverageData()
try:
from coverage.data import CoverageJsonData
except ImportError:
assert isinstance(data.cov_data, coverage.data.CoverageData)
else:
assert isinstance(data.cov_data, CoverageJsonData)
with pytest.raises(TypeError) as excinfo:
CoverageData(cov_data='foo')
try:
from coverage.data import CoverageJsonData
except ImportError:
assert excinfo.value.args == (
'data needs to be of type coverage.data.CoverageData',)
else:
assert excinfo.value.args == (
'data needs to be of type coverage.data.CoverageJsonData',)
with pytest.raises(CoverageWrapperException) as excinfo:
CoverageData(data_file='/does/not/exist')
assert excinfo.value.args == (
'Coverage could not read data_file: /does/not/exist',)
assert isinstance(excinfo.value.orig_exc, coverage.misc.CoverageException)
f = StringIO()
with pytest.raises(CoverageWrapperException) as excinfo:
CoverageData(data_file=f)
e = excinfo.value
assert isinstance(e.orig_exc, coverage.misc.CoverageException)
assert e.message == 'Coverage could not read data_file: %s' % f
assert e.format_message() == "%s (CoverageException: Doesn't seem to be a coverage.py data file)" % (e.message,)
assert str(e) == e.format_message()
assert repr(e) == 'CoverageWrapperException(message=%r, orig_exc=%r)' % (
e.message, e.orig_exc)
cov_data = CoverageData(data_file=coverage_fileobj)
with pytest.raises(attr.exceptions.FrozenInstanceError):
cov_data.data = 'foo'
assert cov_data.lines == {
'/test_plugin/conditional_function.vim': [
3, 8, 9, 11, 13, 14, 15, 17, 23]}
def test_coveragedata_empty(covdata_empty):
from covimerage.coveragepy import CoverageData
f = StringIO()
data = CoverageData()
try:
write_fileobj = data.cov_data.write_fileobj
except AttributeError:
# coveragepy 5
write_fileobj = data.cov_data._write_fileobj
write_fileobj(f)
f.seek(0)
assert f.read() == covdata_empty
def test_coveragewrapper(coverage_fileobj, devnull):
import coverage
from covimerage.coveragepy import (
CoverageData, CoveragePyData, CoverageWrapper, CoverageWrapperException)
cov_data = CoverageWrapper()
assert cov_data.lines == {}
assert isinstance(cov_data.data, CoverageData)
cov_data = CoverageWrapper(data=CoveragePyData())
assert cov_data.lines == {}
assert isinstance(cov_data.data, CoverageData)
with pytest.raises(TypeError):
CoverageWrapper(data_file='foo', data='bar')
with pytest.raises(TypeError):
CoverageWrapper(data_file='foo', data=CoveragePyData())
cov = CoverageWrapper(data_file=coverage_fileobj)
with pytest.raises(attr.exceptions.FrozenInstanceError):
cov.data = 'foo'
assert cov.lines == {
'/test_plugin/conditional_function.vim': [
3, 8, 9, 11, 13, 14, 15, 17, 23]}
assert isinstance(cov._cov_obj, coverage.control.Coverage)
if hasattr(cov._cov_obj, '_data'):
# coveragepy 5
assert cov._cov_obj._data is cov.data.cov_data
else:
assert cov._cov_obj.data is cov.data.cov_data
with pytest.raises(CoverageWrapperException) as excinfo:
CoverageWrapper(data_file=devnull.name)
assert excinfo.value.args == (
'Coverage could not read data_file: /dev/null',)
f = StringIO()
with pytest.raises(CoverageWrapperException) as excinfo:
CoverageWrapper(data_file=f)
e = excinfo.value
assert isinstance(e.orig_exc, coverage.misc.CoverageException)
assert e.message == 'Coverage could not read data_file: %s' % f
assert e.format_message() == "%s (CoverageException: Doesn't seem to be a coverage.py data file)" % (e.message,)
assert str(e) == e.format_message()
assert repr(e) == 'CoverageWrapperException(message=%r, orig_exc=%r)' % (
e.message, e.orig_exc)
def test_coveragewrapper_requires_jsondata():
pytest.importorskip('coverage.sqldata')
from covimerage.coveragepy import CoverageWrapper
with pytest.raises(TypeError) as excinfo:
CoverageWrapper(data=coverage.sqldata.CoverageSqliteData())
assert excinfo.value.args[0] == (
'data needs to be of type coverage.data.CoverageJsonData')
def test_coveragewrapper_uses_config_file(tmpdir, capfd):
from covimerage.coveragepy import CoverageWrapper, CoverageWrapperException
with tmpdir.as_cwd() as old_dir:
vim_src = '%s/tests/test_plugin/conditional_function.vim' % old_dir
coverage_fileobj = StringIO('!coverage.py: This is a private format, don\'t read it directly!{"lines":{"%s":[17,3,23,8,9,11,13,14,15]},"file_tracers":{"%s":"covimerage.CoveragePlugin"}}' % (vim_src, vim_src))
cov = CoverageWrapper(data_file=coverage_fileobj)
assert cov._cov_obj.config.report_include is None
assert cov.lines == {vim_src: [3, 8, 9, 11, 13, 14, 15, 17, 23]}
cov.report()
out, err = capfd.readouterr()
assert 'test_plugin/conditional_function.vim' in out
assert err == ''
coveragerc = str(tmpdir.join('.coveragerc'))
with open(coveragerc, 'w') as f:
f.write('[report]\ninclude = foo/*,bar/*')
coverage_fileobj.seek(0)
cov = CoverageWrapper(data_file=coverage_fileobj)
assert cov._cov_obj.config.report_include == ['foo/*', 'bar/*']
with pytest.raises(CoverageWrapperException) as excinfo:
cov.report()
assert excinfo.value.args == ('No data to report. (CoverageException)',)
out, err = capfd.readouterr()
assert out.splitlines() == [
'Name Stmts Miss Cover',
'---------------------------']
assert err == ''
def test_coveragewrapper_accepts_data():
from covimerage.coveragepy import CoverageData, CoverageWrapper
data = CoverageData()
cov = CoverageWrapper(data=data)
assert cov.data is data
def test_coveragewrapperexception():
from covimerage.coveragepy import CoverageWrapperException
assert CoverageWrapperException('foo').format_message() == 'foo'
with pytest.raises(CoverageWrapperException) as excinfo:
try:
raise Exception('orig')
except Exception as orig_exc:
raise CoverageWrapperException('bar', orig_exc=orig_exc)
assert excinfo.value.format_message() == "bar (Exception: orig)"
| mit |
CloverHealth/airflow | airflow/operators/redshift_to_s3_operator.py | 8 | 5885 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.hooks.postgres_hook import PostgresHook
from airflow.hooks.S3_hook import S3Hook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class RedshiftToS3Transfer(BaseOperator):
"""
Executes an UNLOAD command to s3 as a CSV with headers
:param schema: reference to a specific schema in redshift database
:type schema: string
:param table: reference to a specific table in redshift database
:type table: string
:param s3_bucket: reference to a specific S3 bucket
:type s3_bucket: string
:param s3_key: reference to a specific S3 key
:type s3_key: string
:param redshift_conn_id: reference to a specific redshift database
:type redshift_conn_id: string
:param aws_conn_id: reference to a specific S3 connection
:type aws_conn_id: string
:param unload_options: reference to a list of UNLOAD options
:type unload_options: list
"""
template_fields = ()
template_ext = ()
ui_color = '#ededed'
@apply_defaults
def __init__(
self,
schema,
table,
s3_bucket,
s3_key,
redshift_conn_id='redshift_default',
aws_conn_id='aws_default',
unload_options=tuple(),
autocommit=False,
parameters=None,
include_header=False,
*args, **kwargs):
super(RedshiftToS3Transfer, self).__init__(*args, **kwargs)
self.schema = schema
self.table = table
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.redshift_conn_id = redshift_conn_id
self.aws_conn_id = aws_conn_id
self.unload_options = unload_options
self.autocommit = autocommit
self.parameters = parameters
self.include_header = include_header
if self.include_header and \
'PARALLEL OFF' not in [uo.upper().strip() for uo in unload_options]:
self.unload_options = list(unload_options) + ['PARALLEL OFF', ]
def execute(self, context):
self.hook = PostgresHook(postgres_conn_id=self.redshift_conn_id)
self.s3 = S3Hook(aws_conn_id=self.aws_conn_id)
credentials = self.s3.get_credentials()
unload_options = '\n\t\t\t'.join(self.unload_options)
if self.include_header:
self.log.info("Retrieving headers from %s.%s...",
self.schema, self.table)
columns_query = """SELECT column_name
FROM information_schema.columns
WHERE table_schema = '{schema}'
AND table_name = '{table}'
ORDER BY ordinal_position
""".format(schema=self.schema,
table=self.table)
cursor = self.hook.get_conn().cursor()
cursor.execute(columns_query)
rows = cursor.fetchall()
columns = [row[0] for row in rows]
column_names = ', '.join("{0}".format(c) for c in columns)
column_headers = ', '.join("\\'{0}\\'".format(c) for c in columns)
column_castings = ', '.join("CAST({0} AS text) AS {0}".format(c)
for c in columns)
select_query = """SELECT {column_names} FROM
(SELECT 2 sort_order, {column_castings}
FROM {schema}.{table}
UNION ALL
SELECT 1 sort_order, {column_headers})
ORDER BY sort_order"""\
.format(column_names=column_names,
column_castings=column_castings,
column_headers=column_headers,
schema=self.schema,
table=self.table)
else:
select_query = "SELECT * FROM {schema}.{table}"\
.format(schema=self.schema,
table=self.table)
unload_query = """
UNLOAD ('{select_query}')
TO 's3://{s3_bucket}/{s3_key}/{table}_'
with credentials
'aws_access_key_id={access_key};aws_secret_access_key={secret_key}'
{unload_options};
""".format(select_query=select_query,
table=self.table,
s3_bucket=self.s3_bucket,
s3_key=self.s3_key,
access_key=credentials.access_key,
secret_key=credentials.secret_key,
unload_options=unload_options)
self.log.info('Executing UNLOAD command...')
self.hook.run(unload_query, self.autocommit)
self.log.info("UNLOAD command complete...")
| apache-2.0 |
sw25sw25/Docker | pip/_vendor/distlib/locators.py | 203 | 48796 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2014 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import gzip
from io import BytesIO
import json
import logging
import os
import posixpath
import re
try:
import threading
except ImportError:
import dummy_threading as threading
import zlib
from . import DistlibException
from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,
queue, quote, unescape, string_types, build_opener,
HTTPRedirectHandler as BaseRedirectHandler,
Request, HTTPError, URLError)
from .database import Distribution, DistributionPath, make_dist
from .metadata import Metadata
from .util import (cached_property, parse_credentials, ensure_slash,
split_filename, get_project_data, parse_requirement,
parse_name_and_version, ServerProxy)
from .version import get_scheme, UnsupportedVersionError
from .wheel import Wheel, is_compatible
logger = logging.getLogger(__name__)
HASHER_HASH = re.compile('^(\w+)=([a-f0-9]+)')
CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I)
HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')
DEFAULT_INDEX = 'http://python.org/pypi'
def get_all_distribution_names(url=None):
"""
Return all distribution names known by an index.
:param url: The URL of the index.
:return: A list of all known distribution names.
"""
if url is None:
url = DEFAULT_INDEX
client = ServerProxy(url, timeout=3.0)
return client.list_packages()
class RedirectHandler(BaseRedirectHandler):
"""
A class to work around a bug in some Python 3.2.x releases.
"""
# There's a bug in the base version for some 3.2.x
# (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header
# returns e.g. /abc, it bails because it says the scheme ''
# is bogus, when actually it should use the request's
# URL for the scheme. See Python issue #13696.
def http_error_302(self, req, fp, code, msg, headers):
# Some servers (incorrectly) return multiple Location headers
# (so probably same goes for URI). Use first header.
newurl = None
for key in ('location', 'uri'):
if key in headers:
newurl = headers[key]
break
if newurl is None:
return
urlparts = urlparse(newurl)
if urlparts.scheme == '':
newurl = urljoin(req.get_full_url(), newurl)
if hasattr(headers, 'replace_header'):
headers.replace_header(key, newurl)
else:
headers[key] = newurl
return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,
headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
class Locator(object):
"""
A base class for locators - things that locate distributions.
"""
source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
binary_extensions = ('.egg', '.exe', '.whl')
excluded_extensions = ('.pdf',)
# A list of tags indicating which wheels you want to match. The default
# value of None matches against the tags compatible with the running
# Python. If you want to match other values, set wheel_tags on a locator
# instance to a list of tuples (pyver, abi, arch) which you want to match.
wheel_tags = None
downloadable_extensions = source_extensions + ('.whl',)
def __init__(self, scheme='default'):
"""
Initialise an instance.
:param scheme: Because locators look for most recent versions, they
need to know the version scheme to use. This specifies
the current PEP-recommended scheme - use ``'legacy'``
if you need to support existing distributions on PyPI.
"""
self._cache = {}
self.scheme = scheme
# Because of bugs in some of the handlers on some of the platforms,
# we use our own opener rather than just using urlopen.
self.opener = build_opener(RedirectHandler())
# If get_project() is called from locate(), the matcher instance
# is set from the requirement passed to locate(). See issue #18 for
# why this can be useful to know.
self.matcher = None
def clear_cache(self):
self._cache.clear()
def _get_scheme(self):
return self._scheme
def _set_scheme(self, value):
self._scheme = value
scheme = property(_get_scheme, _set_scheme)
def _get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This should be implemented in subclasses.
If called from a locate() request, self.matcher will be set to a
matcher for the requirement to satisfy, otherwise it will be None.
"""
raise NotImplementedError('Please implement in the subclass')
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Please implement in the subclass')
def get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top.
"""
if self._cache is None:
result = self._get_project(name)
elif name in self._cache:
result = self._cache[name]
else:
result = self._get_project(name)
self._cache[name] = result
return result
def score_url(self, url):
"""
Give an url a score which can be used to choose preferred URLs
for a given project release.
"""
t = urlparse(url)
return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
posixpath.basename(t.path))
def prefer_url(self, url1, url2):
"""
Choose one of two URLs where both are candidates for distribution
archives for the same version of a distribution (for example,
.tar.gz vs. zip).
The current implement favours http:// URLs over https://, archives
from PyPI over those from other locations and then the archive name.
"""
result = url2
if url1:
s1 = self.score_url(url1)
s2 = self.score_url(url2)
if s1 > s2:
result = url1
if result != url2:
logger.debug('Not replacing %r with %r', url1, url2)
else:
logger.debug('Replacing %r with %r', url1, url2)
return result
def split_filename(self, filename, project_name):
"""
Attempt to split a filename in project name, version and Python version.
"""
return split_filename(filename, project_name)
def convert_url_to_download_info(self, url, project_name):
"""
See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, None is returned.
"""
def same_project(name1, name2):
name1, name2 = name1.lower(), name2.lower()
if name1 == name2:
result = True
else:
# distribute replaces '-' by '_' in project names, so it
# can tell where the version starts in a filename.
result = name1.replace('_', '-') == name2.replace('_', '-')
return result
result = None
scheme, netloc, path, params, query, frag = urlparse(url)
if frag.lower().startswith('egg='):
logger.debug('%s: version hint in fragment: %r',
project_name, frag)
m = HASHER_HASH.match(frag)
if m:
algo, digest = m.groups()
else:
algo, digest = None, None
origpath = path
if path and path[-1] == '/':
path = path[:-1]
if path.endswith('.whl'):
try:
wheel = Wheel(path)
if is_compatible(wheel, self.wheel_tags):
if project_name is None:
include = True
else:
include = same_project(wheel.name, project_name)
if include:
result = {
'name': wheel.name,
'version': wheel.version,
'filename': wheel.filename,
'url': urlunparse((scheme, netloc, origpath,
params, query, '')),
'python-version': ', '.join(
['.'.join(list(v[2:])) for v in wheel.pyver]),
}
except Exception as e:
logger.warning('invalid path for wheel: %s', path)
elif path.endswith(self.downloadable_extensions):
path = filename = posixpath.basename(path)
for ext in self.downloadable_extensions:
if path.endswith(ext):
path = path[:-len(ext)]
t = self.split_filename(path, project_name)
if not t:
logger.debug('No match for project/version: %s', path)
else:
name, version, pyver = t
if not project_name or same_project(project_name, name):
result = {
'name': name,
'version': version,
'filename': filename,
'url': urlunparse((scheme, netloc, origpath,
params, query, '')),
#'packagetype': 'sdist',
}
if pyver:
result['python-version'] = pyver
break
if result and algo:
result['%s_digest' % algo] = digest
return result
def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
"""
result = None
for algo in ('sha256', 'md5'):
key = '%s_digest' % algo
if key in info:
result = (algo, info[key])
break
return result
def _update_version_data(self, result, info):
"""
Update a result dictionary (the final result from _get_project) with a
dictionary for a specific version, which typically holds information
gleaned from a filename or URL for an archive for the distribution.
"""
name = info.pop('name')
version = info.pop('version')
if version in result:
dist = result[version]
md = dist.metadata
else:
dist = make_dist(name, version, scheme=self.scheme)
md = dist.metadata
dist.digest = digest = self._get_digest(info)
url = info['url']
result['digests'][url] = digest
if md.source_url != info['url']:
md.source_url = self.prefer_url(md.source_url, url)
result['urls'].setdefault(version, set()).add(url)
dist.locator = self
result[version] = dist
def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
"""
result = None
r = parse_requirement(requirement)
if r is None:
raise DistlibException('Not a valid requirement: %r' % requirement)
scheme = get_scheme(self.scheme)
self.matcher = matcher = scheme.matcher(r.requirement)
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
versions = self.get_project(r.name)
if versions:
# sometimes, versions are invalid
slist = []
vcls = matcher.version_class
for k in versions:
try:
if not matcher.match(k):
logger.debug('%s did not match %r', matcher, k)
else:
if prereleases or not vcls(k).is_prerelease:
slist.append(k)
else:
logger.debug('skipping pre-release '
'version %s of %s', k, matcher.name)
except Exception:
logger.warning('error matching %s with %r', matcher, k)
pass # slist.append(k)
if len(slist) > 1:
slist = sorted(slist, key=scheme.key)
if slist:
logger.debug('sorted list: %s', slist)
version = slist[-1]
result = versions[version]
if result:
if r.extras:
result.extras = r.extras
result.download_urls = versions.get('urls', {}).get(version, set())
d = {}
sd = versions.get('digests', {})
for url in result.download_urls:
if url in sd:
d[url] = sd[url]
result.digests = d
self.matcher = None
return result
class PyPIRPCLocator(Locator):
"""
This locator uses XML-RPC to locate distributions. It therefore
cannot be used with simple mirrors (that only mirror file content).
"""
def __init__(self, url, **kwargs):
"""
Initialise an instance.
:param url: The URL to use for XML-RPC.
:param kwargs: Passed to the superclass constructor.
"""
super(PyPIRPCLocator, self).__init__(**kwargs)
self.base_url = url
self.client = ServerProxy(url, timeout=3.0)
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
return set(self.client.list_packages())
def _get_project(self, name):
result = {'urls': {}, 'digests': {}}
versions = self.client.package_releases(name, True)
for v in versions:
urls = self.client.release_urls(name, v)
data = self.client.release_data(name, v)
metadata = Metadata(scheme=self.scheme)
metadata.name = data['name']
metadata.version = data['version']
metadata.license = data.get('license')
metadata.keywords = data.get('keywords', [])
metadata.summary = data.get('summary')
dist = Distribution(metadata)
if urls:
info = urls[0]
metadata.source_url = info['url']
dist.digest = self._get_digest(info)
dist.locator = self
result[v] = dist
for info in urls:
url = info['url']
digest = self._get_digest(info)
result['urls'].setdefault(v, set()).add(url)
result['digests'][url] = digest
return result
class PyPIJSONLocator(Locator):
"""
This locator uses PyPI's JSON interface. It's very limited in functionality
and probably not worth using.
"""
def __init__(self, url, **kwargs):
super(PyPIJSONLocator, self).__init__(**kwargs)
self.base_url = ensure_slash(url)
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Not available from this locator')
def _get_project(self, name):
result = {'urls': {}, 'digests': {}}
url = urljoin(self.base_url, '%s/json' % quote(name))
try:
resp = self.opener.open(url)
data = resp.read().decode() # for now
d = json.loads(data)
md = Metadata(scheme=self.scheme)
data = d['info']
md.name = data['name']
md.version = data['version']
md.license = data.get('license')
md.keywords = data.get('keywords', [])
md.summary = data.get('summary')
dist = Distribution(md)
urls = d['urls']
if urls:
info = urls[0]
md.source_url = info['url']
dist.digest = self._get_digest(info)
dist.locator = self
result[md.version] = dist
for info in urls:
url = info['url']
result['urls'].setdefault(md.version, set()).add(url)
result['digests'][url] = digest
except Exception as e:
logger.exception('JSON fetch failed: %s', e)
return result
class Page(object):
"""
This class represents a scraped HTML page.
"""
# The following slightly hairy-looking regex just looks for the contents of
# an anchor link, which has an attribute "href" either immediately preceded
# or immediately followed by a "rel" attribute. The attribute values can be
# declared with double quotes, single quotes or no quotes - which leads to
# the length of the expression.
_href = re.compile("""
(rel\s*=\s*(?:"(?P<rel1>[^"]*)"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\s\n]*))\s+)?
href\s*=\s*(?:"(?P<url1>[^"]*)"|'(?P<url2>[^']*)'|(?P<url3>[^>\s\n]*))
(\s+rel\s*=\s*(?:"(?P<rel4>[^"]*)"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\s\n]*)))?
""", re.I | re.S | re.X)
_base = re.compile(r"""<base\s+href\s*=\s*['"]?([^'">]+)""", re.I | re.S)
def __init__(self, data, url):
"""
Initialise an instance with the Unicode page contents and the URL they
came from.
"""
self.data = data
self.base_url = self.url = url
m = self._base.search(self.data)
if m:
self.base_url = m.group(1)
_clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
@cached_property
def links(self):
"""
Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping.
"""
def clean(url):
"Tidy up an URL."
scheme, netloc, path, params, query, frag = urlparse(url)
return urlunparse((scheme, netloc, quote(path),
params, query, frag))
result = set()
for match in self._href.finditer(self.data):
d = match.groupdict('')
rel = (d['rel1'] or d['rel2'] or d['rel3'] or
d['rel4'] or d['rel5'] or d['rel6'])
url = d['url1'] or d['url2'] or d['url3']
url = urljoin(self.base_url, url)
url = unescape(url)
url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
result.add((url, rel))
# We sort the result, hoping to bring the most recent versions
# to the front
result = sorted(result, key=lambda t: t[0], reverse=True)
return result
class SimpleScrapingLocator(Locator):
"""
A locator which scrapes HTML pages to locate downloads for a distribution.
This runs multiple threads to do the I/O; performance is at least as good
as pip's PackageFinder, which works in an analogous fashion.
"""
# These are used to deal with various Content-Encoding schemes.
decoders = {
'deflate': zlib.decompress,
'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(d)).read(),
'none': lambda b: b,
}
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
"""
Initialise an instance.
:param url: The root URL to use for scraping.
:param timeout: The timeout, in seconds, to be applied to requests.
This defaults to ``None`` (no timeout specified).
:param num_workers: The number of worker threads you want to do I/O,
This defaults to 10.
:param kwargs: Passed to the superclass.
"""
super(SimpleScrapingLocator, self).__init__(**kwargs)
self.base_url = ensure_slash(url)
self.timeout = timeout
self._page_cache = {}
self._seen = set()
self._to_fetch = queue.Queue()
self._bad_hosts = set()
self.skip_externals = False
self.num_workers = num_workers
self._lock = threading.RLock()
# See issue #45: we need to be resilient when the locator is used
# in a thread, e.g. with concurrent.futures. We can't use self._lock
# as it is for coordinating our internal threads - the ones created
# in _prepare_threads.
self._gplock = threading.RLock()
def _prepare_threads(self):
"""
Threads are created only when get_project is called, and terminate
before it returns. They are there primarily to parallelise I/O (i.e.
fetching web pages).
"""
self._threads = []
for i in range(self.num_workers):
t = threading.Thread(target=self._fetch)
t.setDaemon(True)
t.start()
self._threads.append(t)
def _wait_threads(self):
"""
Tell all the threads to terminate (by sending a sentinel value) and
wait for them to do so.
"""
# Note that you need two loops, since you can't say which
# thread will get each sentinel
for t in self._threads:
self._to_fetch.put(None) # sentinel
for t in self._threads:
t.join()
self._threads = []
def _get_project(self, name):
result = {'urls': {}, 'digests': {}}
with self._gplock:
self.result = result
self.project_name = name
url = urljoin(self.base_url, '%s/' % quote(name))
self._seen.clear()
self._page_cache.clear()
self._prepare_threads()
try:
logger.debug('Queueing %s', url)
self._to_fetch.put(url)
self._to_fetch.join()
finally:
self._wait_threads()
del self.result
return result
platform_dependent = re.compile(r'\b(linux-(i\d86|x86_64|arm\w+)|'
r'win(32|-amd64)|macosx-?\d+)\b', re.I)
def _is_platform_dependent(self, url):
"""
Does an URL refer to a platform-specific download?
"""
return self.platform_dependent.search(url)
def _process_download(self, url):
"""
See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value.
"""
if self._is_platform_dependent(url):
info = None
else:
info = self.convert_url_to_download_info(url, self.project_name)
logger.debug('process_download: %s -> %s', url, info)
if info:
with self._lock: # needed because self.result is shared
self._update_version_data(self.result, info)
return info
def _should_queue(self, link, referrer, rel):
"""
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.
"""
scheme, netloc, path, _, _, _ = urlparse(link)
if path.endswith(self.source_extensions + self.binary_extensions +
self.excluded_extensions):
result = False
elif self.skip_externals and not link.startswith(self.base_url):
result = False
elif not referrer.startswith(self.base_url):
result = False
elif rel not in ('homepage', 'download'):
result = False
elif scheme not in ('http', 'https', 'ftp'):
result = False
elif self._is_platform_dependent(link):
result = False
else:
host = netloc.split(':', 1)[0]
if host.lower() == 'localhost':
result = False
else:
result = True
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
referrer, result)
return result
def _fetch(self):
"""
Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread.
"""
while True:
url = self._to_fetch.get()
try:
if url:
page = self.get_page(url)
if page is None: # e.g. after an error
continue
for link, rel in page.links:
if link not in self._seen:
self._seen.add(link)
if (not self._process_download(link) and
self._should_queue(link, url, rel)):
logger.debug('Queueing %s from %s', link, url)
self._to_fetch.put(link)
finally:
# always do this, to avoid hangs :-)
self._to_fetch.task_done()
if not url:
#logger.debug('Sentinel seen, quitting.')
break
def get_page(self, url):
"""
Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).
"""
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
scheme, netloc, path, _, _, _ = urlparse(url)
if scheme == 'file' and os.path.isdir(url2pathname(path)):
url = urljoin(ensure_slash(url), 'index.html')
if url in self._page_cache:
result = self._page_cache[url]
logger.debug('Returning %s from cache: %s', url, result)
else:
host = netloc.split(':', 1)[0]
result = None
if host in self._bad_hosts:
logger.debug('Skipping %s due to bad host %s', url, host)
else:
req = Request(url, headers={'Accept-encoding': 'identity'})
try:
logger.debug('Fetching %s', url)
resp = self.opener.open(req, timeout=self.timeout)
logger.debug('Fetched %s', url)
headers = resp.info()
content_type = headers.get('Content-Type', '')
if HTML_CONTENT_TYPE.match(content_type):
final_url = resp.geturl()
data = resp.read()
encoding = headers.get('Content-Encoding')
if encoding:
decoder = self.decoders[encoding] # fail if not found
data = decoder(data)
encoding = 'utf-8'
m = CHARSET.search(content_type)
if m:
encoding = m.group(1)
try:
data = data.decode(encoding)
except UnicodeError:
data = data.decode('latin-1') # fallback
result = Page(data, final_url)
self._page_cache[final_url] = result
except HTTPError as e:
if e.code != 404:
logger.exception('Fetch failed: %s: %s', url, e)
except URLError as e:
logger.exception('Fetch failed: %s: %s', url, e)
with self._lock:
self._bad_hosts.add(host)
except Exception as e:
logger.exception('Fetch failed: %s: %s', url, e)
finally:
self._page_cache[url] = result # even if None (failure)
return result
_distname_re = re.compile('<a href=[^>]*>([^<]+)<')
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
page = self.get_page(self.base_url)
if not page:
raise DistlibException('Unable to get %s' % self.base_url)
for match in self._distname_re.finditer(page.data):
result.add(match.group(1))
return result
class DirectoryLocator(Locator):
"""
This class locates distributions in a directory tree.
"""
def __init__(self, path, **kwargs):
"""
Initialise an instance.
:param path: The root of the directory tree to search.
:param kwargs: Passed to the superclass constructor,
except for:
* recursive - if True (the default), subdirectories are
recursed into. If False, only the top-level directory
is searched,
"""
self.recursive = kwargs.pop('recursive', True)
super(DirectoryLocator, self).__init__(**kwargs)
path = os.path.abspath(path)
if not os.path.isdir(path):
raise DistlibException('Not a directory: %r' % path)
self.base_dir = path
def should_include(self, filename, parent):
"""
Should a filename be considered as a candidate for a distribution
archive? As well as the filename, the directory which contains it
is provided, though not used by the current implementation.
"""
return filename.endswith(self.downloadable_extensions)
def _get_project(self, name):
result = {'urls': {}, 'digests': {}}
for root, dirs, files in os.walk(self.base_dir):
for fn in files:
if self.should_include(fn, root):
fn = os.path.join(root, fn)
url = urlunparse(('file', '',
pathname2url(os.path.abspath(fn)),
'', '', ''))
info = self.convert_url_to_download_info(url, name)
if info:
self._update_version_data(result, info)
if not self.recursive:
break
return result
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for root, dirs, files in os.walk(self.base_dir):
for fn in files:
if self.should_include(fn, root):
fn = os.path.join(root, fn)
url = urlunparse(('file', '',
pathname2url(os.path.abspath(fn)),
'', '', ''))
info = self.convert_url_to_download_info(url, None)
if info:
result.add(info['name'])
if not self.recursive:
break
return result
class JSONLocator(Locator):
"""
This locator uses special extended metadata (not available on PyPI) and is
the basis of performant dependency resolution in distlib. Other locators
require archive downloads before dependencies can be determined! As you
might imagine, that can be slow.
"""
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
raise NotImplementedError('Not available from this locator')
def _get_project(self, name):
result = {'urls': {}, 'digests': {}}
data = get_project_data(name)
if data:
for info in data.get('files', []):
if info['ptype'] != 'sdist' or info['pyversion'] != 'source':
continue
# We don't store summary in project metadata as it makes
# the data bigger for no benefit during dependency
# resolution
dist = make_dist(data['name'], info['version'],
summary=data.get('summary',
'Placeholder for summary'),
scheme=self.scheme)
md = dist.metadata
md.source_url = info['url']
# TODO SHA256 digest
if 'digest' in info and info['digest']:
dist.digest = ('md5', info['digest'])
md.dependencies = info.get('requirements', {})
dist.exports = info.get('exports', {})
result[dist.version] = dist
result['urls'].setdefault(dist.version, set()).add(info['url'])
return result
class DistPathLocator(Locator):
"""
This locator finds installed distributions in a path. It can be useful for
adding to an :class:`AggregatingLocator`.
"""
def __init__(self, distpath, **kwargs):
"""
Initialise an instance.
:param distpath: A :class:`DistributionPath` instance to search.
"""
super(DistPathLocator, self).__init__(**kwargs)
assert isinstance(distpath, DistributionPath)
self.distpath = distpath
def _get_project(self, name):
dist = self.distpath.get_distribution(name)
if dist is None:
result = {}
else:
result = {
dist.version: dist,
'urls': {dist.version: set([dist.source_url])}
}
return result
class AggregatingLocator(Locator):
"""
This class allows you to chain and/or merge a list of locators.
"""
def __init__(self, *locators, **kwargs):
"""
Initialise an instance.
:param locators: The list of locators to search.
:param kwargs: Passed to the superclass constructor,
except for:
* merge - if False (the default), the first successful
search from any of the locators is returned. If True,
the results from all locators are merged (this can be
slow).
"""
self.merge = kwargs.pop('merge', False)
self.locators = locators
super(AggregatingLocator, self).__init__(**kwargs)
def clear_cache(self):
super(AggregatingLocator, self).clear_cache()
for locator in self.locators:
locator.clear_cache()
def _set_scheme(self, value):
self._scheme = value
for locator in self.locators:
locator.scheme = value
scheme = property(Locator.scheme.fget, _set_scheme)
def _get_project(self, name):
result = {}
for locator in self.locators:
d = locator.get_project(name)
if d:
if self.merge:
files = result.get('urls', {})
digests = result.get('digests', {})
# next line could overwrite result['urls'], result['digests']
result.update(d)
df = result.get('urls')
if files and df:
for k, v in files.items():
if k in df:
df[k] |= v
else:
df[k] = v
dd = result.get('digests')
if digests and dd:
dd.update(digests)
else:
# See issue #18. If any dists are found and we're looking
# for specific constraints, we only return something if
# a match is found. For example, if a DirectoryLocator
# returns just foo (1.0) while we're looking for
# foo (>= 2.0), we'll pretend there was nothing there so
# that subsequent locators can be queried. Otherwise we
# would just return foo (1.0) which would then lead to a
# failure to find foo (>= 2.0), because other locators
# weren't searched. Note that this only matters when
# merge=False.
if self.matcher is None:
found = True
else:
found = False
for k in d:
if self.matcher.match(k):
found = True
break
if found:
result = d
break
return result
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for locator in self.locators:
try:
result |= locator.get_distribution_names()
except NotImplementedError:
pass
return result
# We use a legacy scheme simply because most of the dists on PyPI use legacy
# versions which don't conform to PEP 426 / PEP 440.
default_locator = AggregatingLocator(
JSONLocator(),
SimpleScrapingLocator('https://pypi.python.org/simple/',
timeout=3.0),
scheme='legacy')
locate = default_locator.locate
NAME_VERSION_RE = re.compile(r'(?P<name>[\w-]+)\s*'
r'\(\s*(==\s*)?(?P<ver>[^)]+)\)$')
class DependencyFinder(object):
"""
Locate dependencies for distributions.
"""
def __init__(self, locator=None):
"""
Initialise an instance, using the specified locator
to locate distributions.
"""
self.locator = locator or default_locator
self.scheme = get_scheme(self.locator.scheme)
def add_distribution(self, dist):
"""
Add a distribution to the finder. This will update internal information
about who provides what.
:param dist: The distribution to add.
"""
logger.debug('adding distribution %s', dist)
name = dist.key
self.dists_by_name[name] = dist
self.dists[(name, dist.version)] = dist
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
self.provided.setdefault(name, set()).add((version, dist))
def remove_distribution(self, dist):
"""
Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.
"""
logger.debug('removing distribution %s', dist)
name = dist.key
del self.dists_by_name[name]
del self.dists[(name, dist.version)]
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
s = self.provided[name]
s.remove((version, dist))
if not s:
del self.provided[name]
def get_matcher(self, reqt):
"""
Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).
"""
try:
matcher = self.scheme.matcher(reqt)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
name = reqt.split()[0]
matcher = self.scheme.matcher(name)
return matcher
def find_providers(self, reqt):
"""
Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.
"""
matcher = self.get_matcher(reqt)
name = matcher.key # case-insensitive
result = set()
provided = self.provided
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
result.add(provider)
break
return result
def try_to_replace(self, provider, other, problems):
"""
Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet all the requirements
which ``other`` fulfills.
:param provider: The provider we are trying to replace with.
:param other: The provider we're trying to replace.
:param problems: If False is returned, this will contain what
problems prevented replacement. This is currently
a tuple of the literal string 'cantreplace',
``provider``, ``other`` and the set of requirements
that ``provider`` couldn't fulfill.
:return: True if we can replace ``other`` with ``provider``, else
False.
"""
rlist = self.reqts[other]
unmatched = set()
for s in rlist:
matcher = self.get_matcher(s)
if not matcher.match(provider.version):
unmatched.add(s)
if unmatched:
# can't replace other with provider
problems.add(('cantreplace', provider, other,
frozenset(unmatched)))
result = False
else:
# can replace other with provider
self.remove_distribution(other)
del self.reqts[other]
for s in rlist:
self.reqts.setdefault(provider, set()).add(s)
self.add_distribution(provider)
result = True
return result
def find(self, requirement, meta_extras=None, prereleases=False):
"""
Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:param prereleases: If ``True``, allow pre-release versions to be
returned - otherwise, don't return prereleases
unless they're all that's available.
Return a set of :class:`Distribution` instances and a set of
problems.
The distributions returned should be such that they have the
:attr:`required` attribute set to ``True`` if they were
from the ``requirement`` passed to ``find()``, and they have the
:attr:`build_time_dependency` attribute set to ``True`` unless they
are post-installation dependencies of the ``requirement``.
The problems should be a tuple consisting of the string
``'unsatisfied'`` and the requirement which couldn't be satisfied
by any distribution known to the locator.
"""
self.provided = {}
self.dists = {}
self.dists_by_name = {}
self.reqts = {}
meta_extras = set(meta_extras or [])
if ':*:' in meta_extras:
meta_extras.remove(':*:')
# :meta: and :run: are implicitly included
meta_extras |= set([':test:', ':build:', ':dev:'])
if isinstance(requirement, Distribution):
dist = odist = requirement
logger.debug('passed %s as requirement', odist)
else:
dist = odist = self.locator.locate(requirement,
prereleases=prereleases)
if dist is None:
raise DistlibException('Unable to locate %r' % requirement)
logger.debug('located %s', odist)
dist.requested = True
problems = set()
todo = set([dist])
install_dists = set([odist])
while todo:
dist = todo.pop()
name = dist.key # case-insensitive
if name not in self.dists_by_name:
self.add_distribution(dist)
else:
#import pdb; pdb.set_trace()
other = self.dists_by_name[name]
if other != dist:
self.try_to_replace(dist, other, problems)
ireqts = dist.run_requires | dist.meta_requires
sreqts = dist.build_requires
ereqts = set()
if dist in install_dists:
for key in ('test', 'build', 'dev'):
e = ':%s:' % key
if e in meta_extras:
ereqts |= getattr(dist, '%s_requires' % key)
all_reqts = ireqts | sreqts | ereqts
for r in all_reqts:
providers = self.find_providers(r)
if not providers:
logger.debug('No providers found for %r', r)
provider = self.locator.locate(r, prereleases=prereleases)
# If no provider is found and we didn't consider
# prereleases, consider them now.
if provider is None and not prereleases:
provider = self.locator.locate(r, prereleases=True)
if provider is None:
logger.debug('Cannot satisfy %r', r)
problems.add(('unsatisfied', r))
else:
n, v = provider.key, provider.version
if (n, v) not in self.dists:
todo.add(provider)
providers.add(provider)
if r in ireqts and dist in install_dists:
install_dists.add(provider)
logger.debug('Adding %s to install_dists',
provider.name_and_version)
for p in providers:
name = p.key
if name not in self.dists_by_name:
self.reqts.setdefault(p, set()).add(r)
else:
other = self.dists_by_name[name]
if other != p:
# see if other can be replaced by p
self.try_to_replace(p, other, problems)
dists = set(self.dists.values())
for dist in dists:
dist.build_time_dependency = dist not in install_dists
if dist.build_time_dependency:
logger.debug('%s is a build-time dependency only.',
dist.name_and_version)
logger.debug('find done for %s', odist)
return dists, problems
| mit |
mirrax/detekt | utils.py | 7 | 1117 | # Copyright (C) 2014 Claudio Guarnieri.
# This file is part of Detekt - https://github.com/botherder/detekt
# See the file 'LICENSE' for copying permission.
import os
import sys
import ctypes
def get_resource(relative):
# First try from the local directory. This might come handy in case we want
# to provide updates or allow the user to run custom signatures.
path = os.path.join(os.getcwd(), relative)
# In case the resource doesn't exist in the current directory, we'll try
# from the actual resources.
if not os.path.exists(path):
if hasattr(sys, '_MEIPASS'):
path = os.path.join(sys._MEIPASS, relative)
return path
# Not currently used. Might use this in the future to automatically determine
# which language to use for logging messages.
#def get_language():
# return ctypes.windll.kernel32.GetUserDefaultUILanguage()
def check_connection():
# Check if there is an active Internet connection.
# This might not be 100% reliable.
if ctypes.windll.wininet.InternetGetConnectedState(None, None):
return True
else:
return False
| gpl-3.0 |
yuxiang-zhou/menpofit | menpofit/aps/base.py | 2 | 39189 | from __future__ import division
import warnings
import numpy as np
from scipy.stats import multivariate_normal
from menpo.base import name_of_callable
from menpo.feature import no_op
from menpo.visualize import print_dynamic, print_progress
from menpo.model import GMRFModel
from menpo.shape import (DirectedGraph, UndirectedGraph, Tree, PointTree,
PointDirectedGraph, PointUndirectedGraph)
from menpofit import checks
from menpofit.base import batch
from menpofit.modelinstance import OrthoPDM
from menpofit.builder import (compute_features, scale_images, align_shapes,
rescale_images_to_reference_shape,
extract_patches, MenpoFitBuilderWarning,
compute_reference_shape)
class GenerativeAPS(object):
r"""
Class for training a multi-scale Generative Active Pictorial Structures
model. Please see the references for a basic list of relevant papers.
Parameters
----------
images : `list` of `menpo.image.Image`
The `list` of training images.
group : `str` or ``None``, optional
The landmark group that will be used to train the AAM. If ``None`` and
the images only have a single landmark group, then that is the one
that will be used. Note that all the training images need to have the
specified landmark group.
appearance_graph : `list` of graphs or a single graph or ``None``, optional
The graph to be used for the appearance `menpo.model.GMRFModel` training.
It must be a `menpo.shape.UndirectedGraph`. If ``None``, then a
`menpo.model.PCAModel` is used instead.
shape_graph : `list` of graphs or a single graph or ``None``, optional
The graph to be used for the shape `menpo.model.GMRFModel` training. It
must be a `menpo.shape.UndirectedGraph`. If ``None``, then the shape
model is built using `menpo.model.PCAModel`.
deformation_graph : `list` of graphs or a single graph or ``None``, optional
The graph to be used for the deformation `menpo.model.GMRFModel`
training. It must be either a `menpo.shape.DirectedGraph` or a
`menpo.shape.Tree`. If ``None``, then the minimum spanning tree of the
data is computed.
holistic_features : `closure` or `list` of `closure`, optional
The features that will be extracted from the training images. Note
that the features are extracted before warping the images to the
reference shape. If `list`, then it must define a feature function per
scale. Please refer to `menpo.feature` for a list of potential features.
reference_shape : `menpo.shape.PointCloud` or ``None``, optional
The reference shape that will be used for building the APS. The purpose
of the reference shape is to normalise the size of the training images.
The normalization is performed by rescaling all the training images
so that the scale of their ground truth shapes matches the scale of
the reference shape. Note that the reference shape is rescaled with
respect to the `diagonal` before performing the normalisation. If
``None``, then the mean shape will be used.
diagonal : `int` or ``None``, optional
This parameter is used to rescale the reference shape so that the
diagonal of its bounding box matches the provided value. In other
words, this parameter controls the size of the model at the highest
scale. If ``None``, then the reference shape does not get rescaled.
scales : `float` or `tuple` of `float`, optional
The scale value of each scale. They must provided in ascending order,
i.e. from lowest to highest scale. If `float`, then a single scale is
assumed.
patch_shape : (`int`, `int`) or `list` of (`int`, `int`), optional
The shape of the patches to be extracted. If a `list` is provided,
then it defines a patch shape per scale.
patch_normalisation : `list` of `callable` or a single `callable`, optional
The normalisation function to be applied on the extracted patches. If
`list`, then it must have length equal to the number of scales. If a
single patch normalization `callable`, then this is the one applied to
all scales.
use_procrustes : `bool`, optional
If ``True``, then Generalized Procrustes Alignment is applied before
building the deformation model.
precision_dtype : `numpy.dtype`, optional
The data type of the appearance GMRF's precision matrix. For example, it
can be set to `numpy.float32` for single precision or to `numpy.float64`
for double precision. Even though the precision matrix is stored as a
`scipy.sparse` matrix, this parameter has a big impact on the amount of
memory required by the model.
max_shape_components : `int`, `float`, `list` of those or ``None``, optional
The number of shape components to keep. If `int`, then it sets the exact
number of components. If `float`, then it defines the variance
percentage that will be kept. If `list`, then it should
define a value per scale. If a single number, then this will be
applied to all scales. If ``None``, then all the components are kept.
Note that the unused components will be permanently trimmed.
n_appearance_components : `list` of `int` or `int` or ``None``, optional
The number of appearance components used for building the appearance
`menpo.shape.GMRFModel`. If `list`, then it must have length equal to
the number of scales. If a single `int`, then this is the one applied
to all scales. If ``None``, the covariance matrix of each edge is
inverted using `np.linalg.inv`. If `int`, it is inverted using
truncated SVD using the specified number of components.
can_be_incremented : `bool`, optional
In case you intend to incrementally update the model in the future,
then this flag must be set to ``True`` from the first place. Note
that if ``True``, the appearance and deformation `menpo.shape.GMRFModel`
models will occupy double memory.
verbose : `bool`, optional
If ``True``, then the progress of building the APS will be printed.
batch_size : `int` or ``None``, optional
If an `int` is provided, then the training is performed in an
incremental fashion on image batches of size equal to the provided
value. If ``None``, then the training is performed directly on the
all the images.
References
----------
.. [1] E. Antonakos, J. Alabort-i-Medina, and S. Zafeiriou, "Active
Pictorial Structures", Proceedings of the IEEE Conference on Computer
Vision and Pattern Recognition (CVPR), Boston, MA, USA, pp. 1872-1882,
June 2015.
"""
def __init__(self, images, group=None, appearance_graph=None,
shape_graph=None, deformation_graph=None,
holistic_features=no_op, reference_shape=None, diagonal=None,
scales=(0.5, 1.0), patch_shape=(17, 17),
patch_normalisation=no_op, use_procrustes=True,
precision_dtype=np.float32, max_shape_components=None,
n_appearance_components=None, can_be_incremented=False,
verbose=False, batch_size=None):
# Check parameters
checks.check_diagonal(diagonal)
scales = checks.check_scales(scales)
n_scales = len(scales)
holistic_features = checks.check_callable(holistic_features, n_scales)
patch_shape = checks.check_patch_shape(patch_shape, n_scales)
patch_normalisation = checks.check_callable(patch_normalisation,
n_scales)
max_shape_components = checks.check_max_components(
max_shape_components, n_scales, 'max_shape_components')
n_appearance_components = checks.check_max_components(
n_appearance_components, n_scales, 'n_appearance_components')
# Assign attributes
self.diagonal = diagonal
self.scales = scales
self.holistic_features = holistic_features
self.patch_shape = patch_shape
self.patch_normalisation = patch_normalisation
self.reference_shape = reference_shape
self.use_procrustes = use_procrustes
self.is_incremental = can_be_incremented
self.precision_dtype = precision_dtype
self.max_shape_components = max_shape_components
self.n_appearance_components = n_appearance_components
# Check provided graphs
self.appearance_graph = checks.check_graph(
appearance_graph, UndirectedGraph, 'appearance_graph', n_scales)
self.shape_graph = checks.check_graph(shape_graph, UndirectedGraph,
'shape_graph', n_scales)
self.deformation_graph = checks.check_graph(
deformation_graph, [DirectedGraph, Tree], 'deformation_graph',
n_scales)
# Initialize models' lists
self.shape_models = []
self.appearance_models = []
self.deformation_models = []
# Train APS
self._train(images, increment=False, group=group, batch_size=batch_size,
verbose=verbose)
def _train(self, images, increment=False, group=None, batch_size=None,
verbose=False):
# If batch_size is not None, then we may have a generator, else we
# assume we have a list.
if batch_size is not None:
# Create a generator of fixed sized batches. Will still work even
# on an infinite list.
image_batches = batch(images, batch_size)
else:
image_batches = [list(images)]
for k, image_batch in enumerate(image_batches):
if k == 0:
if self.reference_shape is None:
# If no reference shape was given, use the mean of the first
# batch
if batch_size is not None:
warnings.warn('No reference shape was provided. The '
'mean of the first batch will be the '
'reference shape. If the batch mean is '
'not representative of the true mean, '
'this may cause issues.',
MenpoFitBuilderWarning)
self.reference_shape = compute_reference_shape(
[i.landmarks[group].lms for i in image_batch],
self.diagonal, verbose=verbose)
# After the first batch, we are incrementing the model
if k > 0:
increment = True
if verbose:
print('Computing batch {}'.format(k))
# Train each batch
self._train_batch(
image_batch, increment=increment, group=group, verbose=verbose)
def _train_batch(self, image_batch, increment=False, group=None,
verbose=False):
# Rescale to existing reference shape
image_batch = rescale_images_to_reference_shape(
image_batch, group, self.reference_shape, verbose=verbose)
# If the deformation graph was not provided (None given), then compute
# the MST
if None in self.deformation_graph:
graph_shapes = [i.landmarks[group].lms for i in image_batch]
deformation_mst = _compute_minimum_spanning_tree(
graph_shapes, root_vertex=0, prefix='- ', verbose=verbose)
self.deformation_graph = [deformation_mst if g is None else g
for g in self.deformation_graph]
# Build models at each scale
if verbose:
print_dynamic('- Building models\n')
feature_images = []
# for each scale (low --> high)
for j in range(self.n_scales):
if verbose:
if len(self.scales) > 1:
scale_prefix = ' - Scale {}: '.format(j)
else:
scale_prefix = ' - '
else:
scale_prefix = None
# Handle holistic features
if j == 0 and self.holistic_features[j] == no_op:
# Saves a lot of memory
feature_images = image_batch
elif (j == 0 or self.holistic_features[j] is not
self.holistic_features[j - 1]):
# Compute features only if this is the first pass through
# the loop or the features at this scale are different from
# the features at the previous scale
feature_images = compute_features(image_batch,
self.holistic_features[j],
prefix=scale_prefix,
verbose=verbose)
# handle scales
if self.scales[j] != 1:
# Scale feature images only if scale is different than 1
scaled_images = scale_images(feature_images, self.scales[j],
prefix=scale_prefix,
verbose=verbose)
else:
scaled_images = feature_images
# Extract potentially rescaled shapes
scale_shapes = [i.landmarks[group].lms for i in scaled_images]
# Apply procrustes to align the shapes
aligned_shapes = align_shapes(scale_shapes)
# Build the shape model using the aligned shapes
if verbose:
print_dynamic('{}Building shape model'.format(scale_prefix))
if not increment:
self.shape_models.append(self._build_shape_model(
aligned_shapes, self.shape_graph[j],
self.max_shape_components[j], verbose=verbose))
else:
self.shape_models[j].increment(aligned_shapes, verbose=verbose)
# Build the deformation model
if verbose:
print_dynamic('{}Building deformation model'.format(
scale_prefix))
if self.use_procrustes:
deformation_shapes = aligned_shapes
else:
deformation_shapes = scale_shapes
if not increment:
self.deformation_models.append(self._build_deformation_model(
deformation_shapes, self.deformation_graph[j],
verbose=verbose))
else:
self.deformation_models[j].increment(deformation_shapes,
verbose=verbose)
# Obtain warped images
warped_images = self._warp_images(scaled_images, scale_shapes,
j, scale_prefix, verbose)
# Build the appearance model
if verbose:
print_dynamic('{}Building appearance model'.format(
scale_prefix))
if not increment:
self.appearance_models.append(self._build_appearance_model(
warped_images, self.appearance_graph[j],
self.n_appearance_components[j], verbose=verbose))
else:
self._increment_appearance_model(
warped_images, self.appearance_graph[j],
self.appearance_models[j], verbose=verbose)
if verbose:
print_dynamic('{}Done\n'.format(scale_prefix))
def increment(self, images, group=None, batch_size=None, verbose=False):
r"""
Method that incrementally updates the APS model with a new batch of
training images.
Parameters
----------
images : `list` of `menpo.image.Image`
The `list` of training images.
group : `str` or ``None``, optional
The landmark group that will be used to train the APS. If ``None``
and the images only have a single landmark group, then that is the
one that will be used. Note that all the training images need to
have the specified landmark group.
batch_size : `int` or ``None``, optional
If an `int` is provided, then the training is performed in an
incremental fashion on image batches of size equal to the provided
value. If ``None``, then the training is performed directly on the
all the images.
verbose : `bool`, optional
If ``True``, then the progress of building the APS will be printed.
"""
return self._train(images, increment=True, group=group,
verbose=verbose, batch_size=batch_size)
def _build_shape_model(self, shapes, shape_graph, max_shape_components,
verbose=False):
# if the provided graph is None, then apply PCA, else use the GMRF
if shape_graph is not None:
pca_model = GMRFModel(
shapes, shape_graph, mode='concatenation', n_components=None,
dtype=np.float64, sparse=False, incremental=self.is_incremental,
verbose=verbose).principal_components_analysis()
return OrthoPDM(pca_model, max_n_components=max_shape_components)
else:
return OrthoPDM(shapes, max_n_components=max_shape_components)
def _build_deformation_model(self, shapes, deformation_graph,
verbose=False):
return GMRFModel(shapes, deformation_graph, mode='subtraction',
n_components=None, dtype=np.float64, sparse=False,
incremental=self.is_incremental, verbose=verbose)
def _build_appearance_model(self, images, appearance_graph,
n_appearance_components, verbose=False):
if appearance_graph is not None:
return GMRFModel(images, appearance_graph, mode='concatenation',
n_components=n_appearance_components,
dtype=self.precision_dtype, sparse=True,
incremental=self.is_incremental, verbose=verbose)
else:
raise NotImplementedError('The full appearance model is not '
'implemented yet.')
def _increment_appearance_model(self, images, appearance_graph,
appearance_model, verbose=False):
if appearance_graph is not None:
appearance_model.increment(images, verbose=verbose)
else:
raise NotImplementedError('The full appearance model is not '
'implemented yet.')
def _warp_images(self, images, shapes, scale_index, prefix, verbose):
return extract_patches(
images, shapes, self.patch_shape[scale_index],
normalise_function=self.patch_normalisation[scale_index],
prefix=prefix, verbose=verbose)
@property
def n_scales(self):
"""
Returns the number of scales.
:type: `int`
"""
return len(self.scales)
@property
def _str_title(self):
r"""
Returns a string containing name of the model.
:type: `str`
"""
return 'Generative Active Pictorial Structures'
def instance(self, shape_weights=None, scale_index=-1, as_graph=False):
r"""
Generates an instance of the shape model.
Parameters
----------
shape_weights : ``(n_weights,)`` `ndarray` or `list` or ``None``, optional
The weights of the shape model that will be used to create a novel
shape instance. If ``None``, the weights are assumed to be zero,
thus the mean shape is used.
scale_index : `int`, optional
The scale to be used.
as_graph : `bool`, optional
If ``True``, then the instance will be returned as a
`menpo.shape.PointTree` or a `menpo.shape.PointDirectedGraph`,
depending on the type of the deformation graph.
"""
if shape_weights is None:
shape_weights = [0]
sm = self.shape_models[scale_index].model
shape_instance = sm.instance(shape_weights, normalized_weights=True)
if as_graph:
if isinstance(self.deformation_graph[scale_index], Tree):
shape_instance = PointTree(
shape_instance.points,
self.deformation_graph[scale_index].adjacency_matrix,
self.deformation_graph[scale_index].root_vertex)
else:
shape_instance = PointDirectedGraph(
shape_instance.points,
self.deformation_graph[scale_index].adjacency_matrix)
return shape_instance
def random_instance(self, scale_index=-1, as_graph=False):
r"""
Generates a random instance of the APS.
Parameters
----------
scale_index : `int`, optional
The scale to be used.
as_graph : `bool`, optional
If ``True``, then the instance will be returned as a
`menpo.shape.PointTree` or a `menpo.shape.PointDirectedGraph`,
depending on the type of the deformation graph.
"""
shape_weights = np.random.randn(
self.shape_models[scale_index].n_active_components)
return self.instance(shape_weights, scale_index=scale_index,
as_graph=as_graph)
def view_shape_models_widget(self, n_parameters=5,
parameters_bounds=(-3.0, 3.0),
mode='multiple', figure_size=(10, 8)):
r"""
Visualizes the shape models of the APS object using an interactive
widget.
Parameters
----------
n_parameters : `int` or `list` of `int` or ``None``, optional
The number of shape principal components to be used for the
parameters sliders. If `int`, then the number of sliders per
scale is the minimum between `n_parameters` and the number of
active components per scale. If `list` of `int`, then a number of
sliders is defined per scale. If ``None``, all the active
components per scale will have a slider.
parameters_bounds : ``(float, float)``, optional
The minimum and maximum bounds, in std units, for the sliders.
mode : {``single``, ``multiple``}, optional
If ``'single'``, only a single slider is constructed along with a
drop down menu. If ``'multiple'``, a slider is constructed for
each parameter.
figure_size : (`int`, `int`), optional
The size of the rendered figure.
"""
try:
from menpowidgets import visualize_shape_model
visualize_shape_model(
[sm.model for sm in self.shape_models],
n_parameters=n_parameters, parameters_bounds=parameters_bounds,
figure_size=figure_size, mode=mode)
except ImportError:
from menpo.visualize.base import MenpowidgetsMissingError
raise MenpowidgetsMissingError()
def view_shape_graph_widget(self, scale_index=-1, figure_size=(10, 8)):
r"""
Visualize the shape graph using an interactive widget.
Parameters
----------
scale_index : `int`, optional
The scale to be used.
figure_size : (`int`, `int`), optional
The size of the rendered figure.
Raises
------
ValueError
Scale level {scale_index} uses a PCA shape model, so there is no
graph
"""
if self.shape_graph[scale_index] is not None:
PointUndirectedGraph(
self.shape_models[scale_index].model.mean().points,
self.shape_graph[scale_index].adjacency_matrix).view_widget(
figure_size=figure_size)
else:
raise ValueError("Scale level {} uses a PCA shape model, so there "
"is no graph".format(scale_index))
def view_deformation_graph_widget(self, scale_index=-1,
figure_size=(10, 8)):
r"""
Visualize the deformation graph using an interactive widget.
Parameters
----------
scale_index : `int`, optional
The scale to be used.
figure_size : (`int`, `int`), optional
The size of the rendered figure.
"""
if isinstance(self.deformation_graph[scale_index], Tree):
dg = PointTree(self.shape_models[scale_index].model.mean().points,
self.deformation_graph[scale_index].adjacency_matrix,
self.deformation_graph[scale_index].root_vertex)
else:
dg = PointDirectedGraph(
self.shape_models[scale_index].model.mean().points,
self.deformation_graph[scale_index].adjacency_matrix)
dg.view_widget(figure_size=figure_size)
def view_appearance_graph_widget(self, scale_index=-1, figure_size=(10, 8)):
r"""
Visualize the appearance graph using an interactive widget.
Parameters
----------
scale_index : `int`, optional
The scale to be used.
figure_size : (`int`, `int`), optional
The size of the rendered figure.
Raises
------
ValueError
Scale level {scale_index} uses a PCA appearance model, so there
is no graph
"""
if self.appearance_graph[scale_index] is not None:
PointUndirectedGraph(
self.shape_models[scale_index].model.mean().points,
self.appearance_graph[scale_index].adjacency_matrix).\
view_widget(figure_size=figure_size)
else:
raise ValueError("Scale level {} uses a PCA appearance model, "
"so there is no graph".format(scale_index))
def view_deformation_model(self, scale_index=-1, n_std=2,
render_colour_bar=False, colour_map='jet',
image_view=True, figure_id=None,
new_figure=False, render_graph_lines=True,
graph_line_colour='b', graph_line_style='-',
graph_line_width=1., ellipse_line_colour='r',
ellipse_line_style='-', ellipse_line_width=1.,
render_markers=True, marker_style='o',
marker_size=5, marker_face_colour='k',
marker_edge_colour='k', marker_edge_width=1.,
render_axes=False,
axes_font_name='sans-serif', axes_font_size=10,
axes_font_style='normal',
axes_font_weight='normal', crop_proportion=0.1,
figure_size=(10, 8)):
r"""
Visualize the deformation model by plotting a Gaussian ellipsis per
graph edge.
Parameters
----------
scale_index : `int`, optional
The scale to be used.
n_std : `float`, optional
This defines the size of the ellipses in terms of number of standard
deviations.
render_colour_bar : `bool`, optional
If ``True``, then the ellipses will be coloured based on their
normalized standard deviations and a colour bar will also appear on
the side. If ``False``, then all the ellipses will have the same
colour.
colour_map : `str`, optional
A valid Matplotlib colour map. For more info, please refer to
`matplotlib.cm`.
image_view : `bool`, optional
If ``True`` the ellipses will be rendered in the image coordinates
system.
figure_id : `object`, optional
The id of the figure to be used.
new_figure : `bool`, optional
If ``True``, a new figure is created.
render_graph_lines : `bool`, optional
Defines whether to plot the graph's edges.
graph_line_colour : See Below, optional
The colour of the lines of the graph's edges.
Example options::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
graph_line_style : ``{-, --, -., :}``, optional
The style of the lines of the graph's edges.
graph_line_width : `float`, optional
The width of the lines of the graph's edges.
ellipse_line_colour : See Below, optional
The colour of the lines of the ellipses.
Example options::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
ellipse_line_style : ``{-, --, -., :}``, optional
The style of the lines of the ellipses.
ellipse_line_width : `float`, optional
The width of the lines of the ellipses.
render_markers : `bool`, optional
If ``True``, the centers of the ellipses will be rendered.
marker_style : See Below, optional
The style of the centers of the ellipses. Example options ::
{., ,, o, v, ^, <, >, +, x, D, d, s, p, *, h, H, 1, 2, 3, 4, 8}
marker_size : `int`, optional
The size of the centers of the ellipses in points.
marker_face_colour : See Below, optional
The face (filling) colour of the centers of the ellipses.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_colour : See Below, optional
The edge colour of the centers of the ellipses.
Example options ::
{r, g, b, c, m, k, w}
or
(3, ) ndarray
marker_edge_width : `float`, optional
The edge width of the centers of the ellipses.
render_axes : `bool`, optional
If ``True``, the axes will be rendered.
axes_font_name : See Below, optional
The font of the axes. Example options ::
{serif, sans-serif, cursive, fantasy, monospace}
axes_font_size : `int`, optional
The font size of the axes.
axes_font_style : ``{normal, italic, oblique}``, optional
The font style of the axes.
axes_font_weight : See Below, optional
The font weight of the axes.
Example options ::
{ultralight, light, normal, regular, book, medium, roman,
semibold,demibold, demi, bold, heavy, extra bold, black}
crop_proportion : `float`, optional
The proportion to be left around the centers' pointcloud.
figure_size : (`float`, `float`) `tuple` or ``None`` optional
The size of the figure in inches.
"""
from menpo.visualize import plot_gaussian_ellipses
mean_shape = self.shape_models[scale_index].model.mean().points
deformation_graph = self.deformation_graph[scale_index]
# get covariance matrices
covariances = []
means = []
for e in range(deformation_graph.n_edges):
# find vertices
parent = deformation_graph.edges[e, 0]
child = deformation_graph.edges[e, 1]
# relative location mean
means.append(mean_shape[child, :])
# relative location cov
s1 = -self.deformation_models[scale_index].precision[2 * child,
2 * parent]
s2 = -self.deformation_models[scale_index].precision[2 * child + 1,
2 * parent + 1]
s3 = -self.deformation_models[scale_index].precision[2 * child,
2 * parent + 1]
covariances.append(np.linalg.inv(np.array([[s1, s3], [s3, s2]])))
# plot deformation graph
if isinstance(deformation_graph, Tree):
renderer = PointTree(
mean_shape,
deformation_graph.adjacency_matrix,
deformation_graph.root_vertex).view(
figure_id=figure_id, new_figure=new_figure,
image_view=image_view, render_lines=render_graph_lines,
line_colour=graph_line_colour, line_style=graph_line_style,
line_width=graph_line_width, render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_face_colour=marker_face_colour,
marker_edge_colour=marker_edge_colour,
marker_edge_width=marker_edge_width, render_axes=render_axes,
axes_font_name=axes_font_name, axes_font_size=axes_font_size,
axes_font_style=axes_font_style,
axes_font_weight=axes_font_weight, figure_size=figure_size)
else:
renderer = PointDirectedGraph(
mean_shape,
deformation_graph.adjacency_matrix).view(
figure_id=figure_id, new_figure=new_figure,
image_view=image_view, render_lines=render_graph_lines,
line_colour=graph_line_colour, line_style=graph_line_style,
line_width=graph_line_width, render_markers=render_markers,
marker_style=marker_style, marker_size=marker_size,
marker_face_colour=marker_face_colour,
marker_edge_colour=marker_edge_colour,
marker_edge_width=marker_edge_width, render_axes=render_axes,
axes_font_name=axes_font_name, axes_font_size=axes_font_size,
axes_font_style=axes_font_style,
axes_font_weight=axes_font_weight, figure_size=figure_size)
# plot ellipses
renderer = plot_gaussian_ellipses(
covariances, means, n_std=n_std,
render_colour_bar=render_colour_bar,
colour_bar_label='Normalized Standard Deviation',
colour_map=colour_map, figure_id=renderer.figure_id,
new_figure=False, image_view=image_view,
line_colour=ellipse_line_colour, line_style=ellipse_line_style,
line_width=ellipse_line_width, render_markers=render_markers,
marker_edge_colour=marker_edge_colour,
marker_face_colour=marker_face_colour,
marker_edge_width=marker_edge_width, marker_size=marker_size,
marker_style=marker_style, render_axes=render_axes,
axes_font_name=axes_font_name, axes_font_size=axes_font_size,
axes_font_style=axes_font_style, axes_font_weight=axes_font_weight,
crop_proportion=crop_proportion, figure_size=figure_size)
return renderer
def __str__(self):
return _aps_str(self)
def _compute_minimum_spanning_tree(shapes, root_vertex=0, prefix='',
verbose=False):
# initialize weights matrix
n_vertices = shapes[0].n_points
weights = np.zeros((n_vertices, n_vertices))
# print progress if requested
range1 = range(n_vertices-1)
if verbose:
range1 = print_progress(
range1, end_with_newline=False,
prefix='{}Deformation graph - Computing complete graph`s '
'weights'.format(prefix))
# compute weights
for i in range1:
for j in range(i+1, n_vertices, 1):
# create data matrix of edge
diffs_x = [s.points[i, 0] - s.points[j, 0] for s in shapes]
diffs_y = [s.points[i, 1] - s.points[j, 1] for s in shapes]
coords = np.array([diffs_x, diffs_y])
# compute mean and covariance
m = np.mean(coords, axis=1)
c = np.cov(coords)
# get weight
for im in range(len(shapes)):
weights[i, j] += -np.log(multivariate_normal.pdf(coords[:, im],
mean=m, cov=c))
weights[j, i] = weights[i, j]
# create undirected graph
complete_graph = UndirectedGraph(weights)
if verbose:
print_dynamic('{}Deformation graph - Minimum spanning graph '
'computed.\n'.format(prefix))
# compute minimum spanning graph
return complete_graph.minimum_spanning_tree(root_vertex)
def _aps_str(aps):
if aps.diagonal is not None:
diagonal = aps.diagonal
else:
y, x = aps.reference_shape.range()
diagonal = np.sqrt(x ** 2 + y ** 2)
# Compute scale info strings
scales_info = []
lvl_str_tmplt = r""" - Scale {}
- Holistic feature: {}
- Patch shape: {}
- Appearance model class: {}
- {}
- {} features per point ({} in total)
- {}
- Shape model class: {}
- {}
- {} shape components
- {} similarity transform parameters
- Deformation model class: {}
- {}"""
for k, s in enumerate(aps.scales):
comp_str = "No SVD used"
if aps.appearance_models[k].n_components is not None:
comp_str = "{} SVD components".format(aps.appearance_models[k].n_components)
shape_model_str = "Trained using PCA"
if aps.shape_graph[k] is not None:
shape_model_str = "Trained using GMRF: {}".format(aps.shape_graph[k].__str__())
scales_info.append(lvl_str_tmplt.format(
s, name_of_callable(aps.holistic_features[k]),
aps.patch_shape[k],
name_of_callable(aps.appearance_models[k]),
aps.appearance_models[k].graph.__str__(),
aps.appearance_models[k].n_features_per_vertex,
aps.appearance_models[k].n_features,
comp_str,
name_of_callable(aps.shape_models[k]),
shape_model_str,
aps.shape_models[k].model.n_components,
aps.shape_models[k].n_global_parameters,
name_of_callable(aps.deformation_models[k]),
aps.deformation_models[k].graph.__str__()))
scales_info = '\n'.join(scales_info)
cls_str = r"""{class_title}
- Images scaled to diagonal: {diagonal:.2f}
- Scales: {scales}
{scales_info}
""".format(class_title=aps._str_title,
diagonal=diagonal,
scales=aps.scales,
scales_info=scales_info)
return cls_str
| bsd-3-clause |
tartley/chronotank | pyweek12/items/greenery.py | 1 | 1100 |
from random import uniform
from .gameitem import GameItem
class Greenery(GameItem):
layer = 0 # ground level
def __init__(self, **kwargs):
GameItem.__init__(self, **kwargs)
self.randomise_position()
self.scale = uniform(0.5, 2)
self.rot = uniform(0, 360)
class Tree(Greenery):
image_name = 'bush.png'
layer = 3 # tree level
def __init__(self, **kwargs):
Greenery.__init__(self, **kwargs)
self.randomise_position(exclude_radius=400)
self.green = uniform(0.6, 1)
class Fronds(Tree):
image_name = 'fronds.png'
layer = 3 # tree level
def __init__(self, **kwargs):
Tree.__init__(self, **kwargs)
self.green = uniform(0.5, 1)
class Flower(Greenery):
image_name = 'flower.png'
def __init__(self, **kwargs):
Greenery.__init__(self, **kwargs)
self.scale = uniform(0.5, 1)
self.rot = uniform(-20, 20)
class Weed(Greenery):
image_name = 'weed.png'
def __init__(self, **kwargs):
Greenery.__init__(self, **kwargs)
self.green = uniform(0.4, 0.7)
| bsd-3-clause |
elastic/elasticsearch-py | elasticsearch/client/ingest.py | 1 | 4784 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from .utils import SKIP_IN_PATH, NamespacedClient, _make_path, query_params
class IngestClient(NamespacedClient):
@query_params("master_timeout", "summary")
def get_pipeline(self, id=None, params=None, headers=None):
"""
Returns a pipeline.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/get-pipeline-api.html>`_
:arg id: Comma separated list of pipeline ids. Wildcards
supported
:arg master_timeout: Explicit operation timeout for connection
to master node
:arg summary: Return pipelines without their definitions
(default: false)
"""
return self.transport.perform_request(
"GET", _make_path("_ingest", "pipeline", id), params=params, headers=headers
)
@query_params("master_timeout", "timeout")
def put_pipeline(self, id, body, params=None, headers=None):
"""
Creates or updates a pipeline.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/put-pipeline-api.html>`_
:arg id: Pipeline ID
:arg body: The ingest definition
:arg master_timeout: Explicit operation timeout for connection
to master node
:arg timeout: Explicit operation timeout
"""
for param in (id, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
return self.transport.perform_request(
"PUT",
_make_path("_ingest", "pipeline", id),
params=params,
headers=headers,
body=body,
)
@query_params("master_timeout", "timeout")
def delete_pipeline(self, id, params=None, headers=None):
"""
Deletes a pipeline.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/delete-pipeline-api.html>`_
:arg id: Pipeline ID
:arg master_timeout: Explicit operation timeout for connection
to master node
:arg timeout: Explicit operation timeout
"""
if id in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'id'.")
return self.transport.perform_request(
"DELETE",
_make_path("_ingest", "pipeline", id),
params=params,
headers=headers,
)
@query_params("verbose")
def simulate(self, body, id=None, params=None, headers=None):
"""
Allows to simulate a pipeline with example documents.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/simulate-pipeline-api.html>`_
:arg body: The simulate definition
:arg id: Pipeline ID
:arg verbose: Verbose mode. Display data output for each
processor in executed pipeline
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'body'.")
return self.transport.perform_request(
"POST",
_make_path("_ingest", "pipeline", id, "_simulate"),
params=params,
headers=headers,
body=body,
)
@query_params()
def processor_grok(self, params=None, headers=None):
"""
Returns a list of the built-in patterns.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/grok-processor.html#grok-processor-rest-get>`_
"""
return self.transport.perform_request(
"GET", "/_ingest/processor/grok", params=params, headers=headers
)
@query_params()
def geo_ip_stats(self, params=None, headers=None):
"""
Returns statistical information about geoip databases
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/geoip-stats-api.html>`_
"""
return self.transport.perform_request(
"GET", "/_ingest/geoip/stats", params=params, headers=headers
)
| apache-2.0 |
ericshawlinux/bitcoin | test/functional/test_framework/socks5.py | 18 | 5690 | #!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Dummy Socks5 server for testing."""
import socket
import threading
import queue
import logging
logger = logging.getLogger("TestFramework.socks5")
# Protocol constants
class Command:
CONNECT = 0x01
class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
# Utility functions
def recvall(s, n):
"""Receive n bytes from a socket, or fail."""
rv = bytearray()
while n > 0:
d = s.recv(n)
if not d:
raise IOError('Unexpected end of stream')
rv.extend(d)
n -= len(d)
return rv
# Implementation classes
class Socks5Configuration():
"""Proxy configuration."""
def __init__(self):
self.addr = None # Bind address (must be set)
self.af = socket.AF_INET # Bind address family
self.unauth = False # Support unauthenticated
self.auth = False # Support authentication
class Socks5Command():
"""Information about an incoming socks5 command."""
def __init__(self, cmd, atyp, addr, port, username, password):
self.cmd = cmd # Command (one of Command.*)
self.atyp = atyp # Address type (one of AddressType.*)
self.addr = addr # Address
self.port = port # Port to connect to
self.username = username
self.password = password
def __repr__(self):
return 'Socks5Command(%s,%s,%s,%s,%s,%s)' % (self.cmd, self.atyp, self.addr, self.port, self.username, self.password)
class Socks5Connection():
def __init__(self, serv, conn, peer):
self.serv = serv
self.conn = conn
self.peer = peer
def handle(self):
"""Handle socks5 request according to RFC192."""
try:
# Verify socks version
ver = recvall(self.conn, 1)[0]
if ver != 0x05:
raise IOError('Invalid socks version %i' % ver)
# Choose authentication method
nmethods = recvall(self.conn, 1)[0]
methods = bytearray(recvall(self.conn, nmethods))
method = None
if 0x02 in methods and self.serv.conf.auth:
method = 0x02 # username/password
elif 0x00 in methods and self.serv.conf.unauth:
method = 0x00 # unauthenticated
if method is None:
raise IOError('No supported authentication method was offered')
# Send response
self.conn.sendall(bytearray([0x05, method]))
# Read authentication (optional)
username = None
password = None
if method == 0x02:
ver = recvall(self.conn, 1)[0]
if ver != 0x01:
raise IOError('Invalid auth packet version %i' % ver)
ulen = recvall(self.conn, 1)[0]
username = str(recvall(self.conn, ulen))
plen = recvall(self.conn, 1)[0]
password = str(recvall(self.conn, plen))
# Send authentication response
self.conn.sendall(bytearray([0x01, 0x00]))
# Read connect request
ver, cmd, _, atyp = recvall(self.conn, 4)
if ver != 0x05:
raise IOError('Invalid socks version %i in connect request' % ver)
if cmd != Command.CONNECT:
raise IOError('Unhandled command %i in connect request' % cmd)
if atyp == AddressType.IPV4:
addr = recvall(self.conn, 4)
elif atyp == AddressType.DOMAINNAME:
n = recvall(self.conn, 1)[0]
addr = recvall(self.conn, n)
elif atyp == AddressType.IPV6:
addr = recvall(self.conn, 16)
else:
raise IOError('Unknown address type %i' % atyp)
port_hi,port_lo = recvall(self.conn, 2)
port = (port_hi << 8) | port_lo
# Send dummy response
self.conn.sendall(bytearray([0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))
cmdin = Socks5Command(cmd, atyp, addr, port, username, password)
self.serv.queue.put(cmdin)
logger.info('Proxy: %s', cmdin)
# Fall through to disconnect
except Exception as e:
logger.exception("socks5 request handling failed.")
self.serv.queue.put(e)
finally:
self.conn.close()
class Socks5Server():
def __init__(self, conf):
self.conf = conf
self.s = socket.socket(conf.af)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind(conf.addr)
self.s.listen(5)
self.running = False
self.thread = None
self.queue = queue.Queue() # report connections and exceptions to client
def run(self):
while self.running:
(sockconn, peer) = self.s.accept()
if self.running:
conn = Socks5Connection(self, sockconn, peer)
thread = threading.Thread(None, conn.handle)
thread.daemon = True
thread.start()
def start(self):
assert(not self.running)
self.running = True
self.thread = threading.Thread(None, self.run)
self.thread.daemon = True
self.thread.start()
def stop(self):
self.running = False
# connect to self to end run loop
s = socket.socket(self.conf.af)
s.connect(self.conf.addr)
s.close()
self.thread.join()
| mit |
weidongxu84/info-gatherer | requests/__init__.py | 62 | 1863 | # -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('http://python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>.
:copyright: (c) 2013 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""
__title__ = 'requests'
__version__ = '1.2.3'
__build__ = 0x010203
__author__ = 'Kenneth Reitz'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Kenneth Reitz'
# Attempt to enable urllib3's SNI support, if possible
try:
from requests.packages.urllib3.contrib import pyopenssl
pyopenssl.inject_into_urllib3()
except ImportError:
pass
from . import utils
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
RequestException, Timeout, URLRequired,
TooManyRedirects, HTTPError, ConnectionError
)
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
| mit |
aimas/TuniErp-8.0 | addons/base_report_designer/plugin/openerp_report_designer/bin/script/ConvertFieldsToBraces.py | 384 | 2324 | #########################################################################
#
# Copyright (c) 2003-2004 Danny Brewer d29583@groovegarden.com
# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).
#
# 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
#
# See: http://www.gnu.org/licenses/lgpl.html
#
#############################################################################
import uno
import unohelper
import string
import re
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from LoginTest import *
database="test"
uid = 3
class ConvertFieldsToBraces( unohelper.Base, XJobExecutor ):
def __init__(self, ctx):
self.ctx = ctx
self.module = "openerp_report"
self.version = "0.1"
LoginTest()
if not loginstatus and __name__=="package":
exit(1)
self.aReportSyntex=[]
self.getFields()
def getFields(self):
desktop=getDesktop()
doc = desktop.getCurrentComponent()
oParEnum = doc.getTextFields().createEnumeration()
while oParEnum.hasMoreElements():
oPar = oParEnum.nextElement()
if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
oPar.getAnchor().Text.insertString(oPar.getAnchor(),oPar.Items[1],False)
oPar.dispose()
if __name__<>"package":
ConvertFieldsToBraces(None)
else:
g_ImplementationHelper.addImplementation( ConvertFieldsToBraces, "org.openoffice.openerp.report.convertFB", ("com.sun.star.task.Job",),)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
hbrunn/OpenUpgrade | addons/base_action_rule/__init__.py | 438 | 1098 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 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/>.
#
##############################################################################
import base_action_rule
import test_models
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
WilliamXIII/cuda-convnet2 | python_util/options.py | 180 | 16577 | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from getopt import getopt
import os
import re
#import types
TERM_BOLD_START = "\033[1m"
TERM_BOLD_END = "\033[0m"
class Option:
def __init__(self, letter, name, desc, parser, set_once, default, excuses, requires, save):
assert not name is None
self.letter = letter
self.name = name
self.desc = desc
self.parser = parser
self.set_once = set_once
self.default = default
self.excuses = excuses
self.requires = requires
self.save = save
self.value = None
self.value_given = False
self.prefixed_letter = min(2, len(letter)) * '-' + letter
def set_value(self, value, parse=True):
try:
self.value = self.parser.parse(value) if parse else value
self.value_given = True
# print self.name, self.value
except OptionException, e:
raise OptionException("Unable to parse option %s (%s): %s" % (self.prefixed_letter, self.desc, e))
def set_default(self):
if not self.default is None:
self.value = self.default
def eval_expr_default(self, env):
try:
if isinstance(self.default, OptionExpression) and not self.value_given:
self.value = self.default.evaluate(env)
if not self.parser.is_type(self.value):
raise OptionException("expression result %s is not of right type (%s)" % (self.value, self.parser.get_type_str()))
except Exception, e:
raise OptionException("Unable to set default value for option %s (%s): %s" % (self.prefixed_letter, self.desc, e))
def get_str_value(self, get_default_str=False):
val = self.value
if get_default_str: val = self.default
if val is None: return ""
if isinstance(val, OptionExpression):
return val.expr
return self.parser.to_string(val)
class OptionsParser:
"""An option parsing class. All options without default values are mandatory, unless a excuses
option (usually a load file) is given.
Does not support options without arguments."""
SORT_LETTER = 1
SORT_DESC = 2
SORT_EXPR_LAST = 3
EXCUSE_ALL = "all"
def __init__(self):
self.options = {}
def add_option(self, letter, name, parser, desc, set_once=False, default=None, excuses=[], requires=[], save=True):
"""
The letter parameter is the actual parameter that the user will have to supply on the command line.
The name parameter is some name to be given to this option and must be a valid python variable name.
An explanation of the "default" parameter:
The default value, if specified, should have the same type as the option.
You can also specify an expression as the default value. In this case, the default value of the parameter
will be the output of the expression. The expression may assume all other option names
as local variables. For example, you can define the hidden bias
learning rate to be 10 times the weight learning rate by setting this default:
default=OptionExpression("eps_w * 10") (assuming an option named eps_w exists).
However, it is up to you to make sure you do not make any circular expression definitions.
Note that the order in which the options are parsed is arbitrary.
In particular, expression default values that depend on other expression default values
will often raise errors (depending on the order in which they happen to be parsed).
Therefore it is best not to make the default value of one variable depend on the value
of another if the other variable's default value is itself an expression.
An explanation of the "excuses" parameter:
All options are mandatory, but certain options can exclude other options from being mandatory.
For example, if the excuses parameter for option "load_file" is ["num_hid", "num_vis"],
then the options num_hid and num_vis are not mandatory as long as load_file is specified.
Use the special flag EXCUSE_ALL to allow an option to make all other options optional.
"""
assert name not in self.options
self.options[name] = Option(letter, name, desc, parser, set_once, default, excuses, requires, save)
def set_value(self, name, value, parse=True):
self.options[name].set_value(value, parse=parse)
def get_value(self, name):
return self.options[name].value
def delete_option(self, name):
if name in self.options:
del self.options[name]
def parse(self, eval_expr_defaults=False):
"""Parses the options in sys.argv based on the options added to this parser. The
default behavior is to leave any expression default options as OptionExpression objects.
Set eval_expr_defaults=True to circumvent this."""
short_opt_str = ''.join(["%s:" % self.options[name].letter for name in self.options if len(self.options[name].letter) == 1])
long_opts = ["%s=" % self.options[name].letter for name in self.options if len(self.options[name].letter) > 1]
(go, ga) = getopt(sys.argv[1:], short_opt_str, longopts=long_opts)
dic = dict(go)
for o in self.get_options_list(sort_order=self.SORT_EXPR_LAST):
if o.prefixed_letter in dic:
o.set_value(dic[o.prefixed_letter])
else:
# check if excused or has default
excused = max([o2.prefixed_letter in dic for o2 in self.options.values() if o2.excuses == self.EXCUSE_ALL or o.name in o2.excuses])
if not excused and o.default is None:
raise OptionMissingException("Option %s (%s) not supplied" % (o.prefixed_letter, o.desc))
o.set_default()
# check requirements
if o.prefixed_letter in dic:
for o2 in self.get_options_list(sort_order=self.SORT_LETTER):
if o2.name in o.requires and o2.prefixed_letter not in dic:
raise OptionMissingException("Option %s (%s) requires option %s (%s)" % (o.prefixed_letter, o.desc,
o2.prefixed_letter, o2.desc))
if eval_expr_defaults:
self.eval_expr_defaults()
return self.options
def merge_from(self, op2):
"""Merges the options in op2 into this instance, but does not overwrite
this instances's SET options with op2's default values."""
for name, o in self.options.iteritems():
if name in op2.options and ((op2.options[name].value_given and op2.options[name].value != self.options[name].value) or not op2.options[name].save):
if op2.options[name].set_once:
raise OptionException("Option %s (%s) cannot be changed" % (op2.options[name].prefixed_letter, op2.options[name].desc))
self.options[name] = op2.options[name]
for name in op2.options:
if name not in self.options:
self.options[name] = op2.options[name]
def eval_expr_defaults(self):
env = dict([(name, o.value) for name, o in self.options.iteritems()])
for o in self.options.values():
o.eval_expr_default(env)
def all_values_given(self):
return max([o.value_given for o in self.options.values() if o.default is not None])
def get_options_list(self, sort_order=SORT_LETTER):
""" Returns the list of Option objects in this OptionParser,
sorted as specified"""
cmp = lambda x, y: (x.desc < y.desc and -1 or 1)
if sort_order == self.SORT_LETTER:
cmp = lambda x, y: (x.letter < y.letter and -1 or 1)
elif sort_order == self.SORT_EXPR_LAST:
cmp = lambda x, y: (type(x.default) == OptionExpression and 1 or -1)
return sorted(self.options.values(), cmp=cmp)
def print_usage(self, print_constraints=False):
print "%s usage:" % os.path.basename(sys.argv[0])
opslist = self.get_options_list()
usage_strings = []
num_def = 0
for o in opslist:
excs = ' '
if o.default is None:
excs = ', '.join(sorted([o2.prefixed_letter for o2 in self.options.values() if o2.excuses == self.EXCUSE_ALL or o.name in o2.excuses]))
reqs = ', '.join(sorted([o2.prefixed_letter for o2 in self.options.values() if o2.name in o.requires]))
usg = (OptionsParser._bold(o.prefixed_letter) + " <%s>" % o.parser.get_type_str(), o.desc, ("[%s]" % o.get_str_value(get_default_str=True)) if not o.default is None else None, excs, reqs)
if o.default is None:
usage_strings += [usg]
else:
usage_strings.insert(num_def, usg)
num_def += 1
col_widths = [self._longest_value(usage_strings, key=lambda x:x[i]) for i in range(len(usage_strings[0]) - 1)]
col_names = [" Option", "Description", "Default"]
if print_constraints:
col_names += ["Excused by", "Requires"]
for i, s in enumerate(col_names):
print self._bold(s.ljust(col_widths[i])),
print ""
for l, d, de, ex, req in usage_strings:
if de is None:
de = ' '
print (" %s -" % l.ljust(col_widths[0])), d.ljust(col_widths[1]), de.ljust(col_widths[2]),
else:
print (" [%s] -" % l.ljust(col_widths[0])), d.ljust(col_widths[1]), de.ljust(col_widths[2]),
if print_constraints:
print ex.ljust(col_widths[3]), req
else:
print ""
def print_values(self):
longest_desc = self._longest_value(self.options.values(), key=lambda x:x.desc)
longest_def_value = self._longest_value([v for v in self.options.values() if not v.value_given and not v.default is None],
key=lambda x:x.get_str_value())
for o in self.get_options_list(sort_order=self.SORT_DESC):
print "%s: %s %s" % (o.desc.ljust(longest_desc), o.get_str_value().ljust(longest_def_value), (not o.value_given and not o.default is None) and "[DEFAULT]" or "")
@staticmethod
def _longest_value(values, key=lambda x:x):
mylen = lambda x: 0 if x is None else len(x)
return mylen(key(max(values, key=lambda x:mylen(key(x)))))
@staticmethod
def _bold(str):
return TERM_BOLD_START + str + TERM_BOLD_END
class OptionException(Exception):
pass
class OptionMissingException(OptionException):
pass
class OptionParser:
@staticmethod
def parse(value):
return str(value)
@staticmethod
def to_string(value):
return str(value)
@staticmethod
def get_type_str():
pass
class IntegerOptionParser(OptionParser):
@staticmethod
def parse(value):
try:
return int(value)
except:
raise OptionException("argument is not an integer")
@staticmethod
def get_type_str():
return "int"
@staticmethod
def is_type(value):
return type(value) == int
class BooleanOptionParser(OptionParser):
@staticmethod
def parse(value):
try:
v = int(value)
if not v in (0,1):
raise OptionException
return v
except:
raise OptionException("argument is not a boolean")
@staticmethod
def get_type_str():
return "0/1"
@staticmethod
def is_type(value):
return type(value) == int and value in (0, 1)
class StringOptionParser(OptionParser):
@staticmethod
def get_type_str():
return "string"
@staticmethod
def is_type(value):
return type(value) == str
class FloatOptionParser(OptionParser):
@staticmethod
def parse(value):
try:
return float(value)
except:
raise OptionException("argument is not a float")
@staticmethod
def to_string(value):
return "%.6g" % value
@staticmethod
def get_type_str():
return "float"
@staticmethod
def is_type(value):
return type(value) == float
class RangeOptionParser(OptionParser):
@staticmethod
def parse(value):
m = re.match("^(\d+)\-(\d+)$", value)
try:
if m: return range(int(m.group(1)), int(m.group(2)) + 1)
return [int(value)]
except:
raise OptionException("argument is neither an integer nor a range")
@staticmethod
def to_string(value):
return "%d-%d" % (value[0], value[-1])
@staticmethod
def get_type_str():
return "int[-int]"
@staticmethod
def is_type(value):
return type(value) == list
class ListOptionParser(OptionParser):
"""
A parser that parses a delimited list of items. If the "parsers"
argument is a list of parsers, then the list of items must have the form and length
specified by that list.
Example:
ListOptionParser([FloatOptionParser, IntegerOptionParser])
would parse "0.5,3" but not "0.5,3,0.6" or "0.5" or "3,0.5".
If the "parsers" argument is another parser, then the list of items may be of
arbitrary length, but each item must be parseable by the given parser.
Example:
ListOptionParser(FloatOptionParser)
would parse "0.5" and "0.5,0.3" and "0.5,0.3,0.6", etc.
"""
def __init__(self, parsers, sepchar=','):
self.parsers = parsers
self.sepchar = sepchar
def parse(self, value):
values = value.split(self.sepchar)
if type(self.parsers) == list and len(values) != len(self.parsers):
raise OptionException("requires %d arguments, given %d" % (len(self.parsers), len(values)))
try:
if type(self.parsers) == list:
return [p.parse(v) for p, v in zip(self.parsers, values)]
return [self.parsers.parse(v) for v in values]
except:
raise OptionException("argument is not of the form %s" % self.get_type_str())
def to_string(self, value):
if type(self.parsers) == list:
return self.sepchar.join([p.to_string(v) for p, v in zip(self.parsers, value)])
return self.sepchar.join([self.parsers.to_string(v) for v in value])
def get_type_str(self):
if type(self.parsers) == list:
return self.sepchar.join([p.get_type_str() for p in self.parsers])
return "%s%s..." % (self.parsers.get_type_str(), self.sepchar)
@staticmethod
def is_type(value):
return type(value) == list
class OptionExpression:
"""
This allows you to specify option values in terms of other option values.
Example:
op.add_option("eps-w", "eps_w", ListOptionParser(FloatOptionParser), "Weight learning rates for each layer")
op.add_option("eps-b", "eps_b", ListOptionParser(FloatOptionParser), "Bias learning rates for each layer", default=OptionExpression("[o * 10 for o in eps_w]"))
This says: the default bias learning rate for each layer is 10
times the weight learning rate for that layer.
"""
def __init__(self, expr):
self.expr = expr
def evaluate(self, options):
locals().update(options)
try:
return eval(self.expr)
except Exception, e:
raise OptionException("expression '%s': unable to parse: %s" % (self.expr, e))
| apache-2.0 |
skosukhin/spack | var/spack/repos/builtin/packages/r-affyrnadegradation/package.py | 1 | 2026 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RAffyrnadegradation(RPackage):
"""The package helps with the assessment and correction of
RNA degradation effects in Affymetrix 3' expression arrays.
The parameter d gives a robust and accurate measure of RNA
integrity. The correction removes the probe positional bias,
and thus improves comparability of samples that are affected
by RNA degradation."""
homepage = "https://www.bioconductor.org/packages/AffyRNADegradation/"
url = "https://git.bioconductor.org/packages/AffyRNADegradation"
version('1.22.0', git='https://git.bioconductor.org/packages/AffyRNADegradation', commit='0fa78f8286494711a239ded0ba587b0de47c15d3')
depends_on('r@3.4.0:3.4.9', when='@1.22.0')
depends_on('r-affy', type=('build', 'run'))
| lgpl-2.1 |
praba230890/PYPOWER | doc/conf.py | 2 | 6328 | # -*- coding: utf-8 -*-
#
# PYPOWER documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 7 17:48:32 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['ipython_console_highlighting']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PYPOWER'
copyright = u'2011, Richard Lincoln'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '5.0'
# The full version, including alpha/beta/rc tags.
release = '5.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['.build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['.static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'PYPOWERdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'PYPOWER.tex', u'PYPOWER Documentation',
u'Richard Lincoln', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| bsd-3-clause |
naitikshukla/drone | vanish_point/main.py | 1 | 2937 | from VanishingPoint import *
import os
import time
def direction(img,xa,ya,xb,yb,width,height):
#xa,ya,xb,yb=point[0],point[1],point[2],point[3]
cenx = xa+(xb-xa)/2
ceny = ya+(yb-ya)/2
centerx=width/2
centery = height/2
timeout = time.time() + 5
#while True:
#_,img = cam.read()
print("image center are :", centerx,centery)
#img=cv2.blur(img, (3,3))
cv2.circle(img, (centerx,centery), 4, (0,0,123), thickness=3, lineType=7, shift=0) #Screen centre
cv2.circle(img, (cenx,ceny), 4, (0,232,123), thickness=1, lineType=7, shift=0) #new box centre
cv2.rectangle(img, (int(centerx-centery/4), centery+centerx/5), (int(centerx+centery/4), centery-centerx/5), (255, 123, 11), 3) #range rectangle
#cv2.rectangle(img, (xa,ya), (xb,yb), (34, 123, 145), 1) #Object rectangle
#if time.time() > timeout:
# break
if cenx < centerx-centery/4: #for left
print ("Go Right")
print ("left and right boundaries",(centerx-centery/3,centerx+centery/3))
txt='Left'
loc = (xa+2,ya+(yb-ya)/2)
cv2.putText(img, txt, loc , cv2.FONT_HERSHEY_SIMPLEX, 1, (123,255,255), 3)
if (cenx > centerx-centery/4 and cenx < centerx+centery/4): # For Centre
print ("center")
txt = "Center"
loc = (xa,ya+2)
cv2.putText(img, txt, loc , cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,123), 3)
if (cenx > centerx+centery/4): # For Right
print ("Go Left")
txt = "Right"
loc = (xa,ya+2)
cv2.putText(img, txt, loc , cv2.FONT_HERSHEY_SIMPLEX, 1, (255,123,255), 3)
#cv2.imshow("tracker", img)
cv2.imwrite("C:/Users/naiti/Desktop/vanishingpoint/pictures/output/final.jpg", img)
cv2.waitKey(1)
#return img
filepath = os.path.abspath("C:/Users/naiti/Desktop/vanishingpoint/pictures/input/corridor_6.jpg")
img = cv2.imread(filepath)
hough_lines = hough_transform(img)
if hough_lines:
random_sample = sample_lines(hough_lines, 100)
intersections = find_intersections(random_sample, img)
for x,y in intersections:
cv2.circle(img,(x,y), 5, (124,0,255), -1)
cv2.imwrite("C:/Users/naiti/Desktop/vanishingpoint/pictures/output/circle.jpg", img)
if intersections:
grid_size = min(img.shape[0], img.shape[1]) // 3
print img.shape[0],img.shape[1],img.shape[0]//3,grid_size
best_cell = find_vanishing_point(img, grid_size, intersections)
#print vanishing_point[0],vanishing_point[1]
rx1 = best_cell[0] - grid_size / 2
ry1 = best_cell[1] - grid_size / 2
rx2 = best_cell[0] + grid_size / 2
ry2 = best_cell[1] + grid_size / 2
cv2.circle(img,(rx1,ry1), 5, (124,111,255), 2) #left point on best cell
cv2.circle(img,(rx2,ry2), 5, (124,111,255), 2) # right point on best cell
cv2.circle(img,(best_cell[0],best_cell[1]), 5, (124,111,255), 2) # centre point on best cell
#cv2.imshow("vanishing_point",best_cell)
#cv2.waitKey(10)
filename = "C:/Users/naiti/Desktop/vanishingpoint/pictures/output/corridor_6.jpg"
cv2.imwrite(filename, img)
direction(img,rx1,ry1,rx2,ry2,img.shape[1],img.shape[0])
| unlicense |
goliveirab/openacademy-project | openacademy/__openerp__.py | 1 | 1205 | # -*- coding: utf-8 -*-
{
'name': "Open Academy",
'summary': """Manage trainings""",
# 'description': """
# Open Academy module for managing trainings:
# - training courses
# - training sessions
# - attendees registration
'author': "Vauxoo",
'website': "http://www.vauxoo.com",
# Categories can be used to filter modules in modules listing
# for the full list
'category': 'Test',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base', 'board', 'account_asset'],
# always loaded
'data': [
'security/openacademy_security.xml',
'security/ir.model.access.csv',
'view/openacademy_course_view.xml',
'view/openacademy_session_view.xml',
'view/openacademy_partner_view.xml',
'workflow/openacademy_session_workflow.xml',
'report/openacademy_session_report.xml',
'view/openacademy_session_board.xml',
'view/openacademy_account_asset_view.xml',
# 'security/ir.model.access.csv',
# 'templates.xml',
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
'installable': True
}
| gpl-3.0 |
angelapper/odoo | addons/sale_stock/sale_stock.py | 2 | 16690 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from openerp import api, fields, models, _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare
from openerp.exceptions import UserError
class SaleOrder(models.Model):
_inherit = "sale.order"
@api.model
def _default_warehouse_id(self):
company = self.env.user.company_id.id
warehouse_ids = self.env['stock.warehouse'].search([('company_id', '=', company)], limit=1)
return warehouse_ids
incoterm = fields.Many2one('stock.incoterms', 'Incoterms', help="International Commercial Terms are a series of predefined commercial terms used in international transactions.")
picking_policy = fields.Selection([
('direct', 'Deliver each product when available'),
('one', 'Deliver all products at once')],
string='Shipping Policy', required=True, readonly=True, default='direct',
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse',
required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
default=_default_warehouse_id)
picking_ids = fields.Many2many('stock.picking', compute='_compute_picking_ids', string='Picking associated to this sale')
delivery_count = fields.Integer(string='Delivery Orders', compute='_compute_picking_ids')
@api.multi
@api.depends('procurement_group_id')
def _compute_picking_ids(self):
for order in self:
order.picking_ids = self.env['stock.picking'].search([('group_id', '=', order.procurement_group_id.id)]) if order.procurement_group_id else []
order.delivery_count = len(order.picking_ids)
@api.onchange('warehouse_id')
def _onchange_warehouse_id(self):
if self.warehouse_id.company_id:
self.company_id = self.warehouse_id.company_id.id
@api.multi
def action_view_delivery(self):
'''
This function returns an action that display existing delivery orders
of given sales order ids. It can either be a in a list or in a form
view, if there is only one delivery order to show.
'''
action = self.env.ref('stock.action_picking_tree_all')
result = {
'name': action.name,
'help': action.help,
'type': action.type,
'view_type': action.view_type,
'view_mode': action.view_mode,
'target': action.target,
'context': action.context,
'res_model': action.res_model,
}
pick_ids = sum([order.picking_ids.ids for order in self], [])
if len(pick_ids) > 1:
result['domain'] = "[('id','in',["+','.join(map(str, pick_ids))+"])]"
elif len(pick_ids) == 1:
form = self.env.ref('stock.view_picking_form', False)
form_id = form.id if form else False
result['views'] = [(form_id, 'form')]
result['res_id'] = pick_ids[0]
return result
@api.multi
def action_cancel(self):
self.order_line.mapped('procurement_ids').cancel()
super(SaleOrder, self).action_cancel()
@api.multi
def _prepare_invoice(self):
invoice_vals = super(SaleOrder, self)._prepare_invoice()
invoice_vals['incoterms_id'] = self.incoterm.id or False
return invoice_vals
@api.model
def _prepare_procurement_group(self):
res = super(SaleOrder, self)._prepare_procurement_group()
res.update({'move_type': self.picking_policy, 'partner_id': self.partner_shipping_id.id})
return res
@api.model
def _get_customer_lead(self, product_tmpl_id):
super(SaleOrder, self)._get_customer_lead(product_tmpl_id)
return product_tmpl_id.sale_delay
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
product_packaging = fields.Many2one('product.packaging', string='Packaging', default=False)
route_id = fields.Many2one('stock.location.route', string='Route', domain=[('sale_selectable', '=', True)])
product_tmpl_id = fields.Many2one('product.template', related='product_id.product_tmpl_id', string='Product Template', readonly=True)
@api.depends('order_id.state')
def _compute_invoice_status(self):
super(SaleOrderLine, self)._compute_invoice_status()
for line in self:
# We handle the following specific situation: a physical product is partially delivered,
# but we would like to set its invoice status to 'Fully Invoiced'. The use case is for
# products sold by weight, where the delivered quantity rarely matches exactly the
# quantity ordered.
if line.order_id.state == 'done'\
and line.invoice_status == 'no'\
and line.product_id.type in ['consu', 'product']\
and line.product_id.invoice_policy == 'delivery'\
and line.procurement_ids.mapped('move_ids')\
and all(move.state in ['done', 'cancel'] for move in line.procurement_ids.mapped('move_ids')):
line.invoice_status = 'invoiced'
@api.multi
@api.depends('product_id')
def _compute_qty_delivered_updateable(self):
for line in self:
if line.product_id.type not in ('consu', 'product'):
return super(SaleOrderLine, self)._compute_qty_delivered_updateable()
line.qty_delivered_updateable = False
@api.onchange('product_id')
def _onchange_product_id_set_customer_lead(self):
self.customer_lead = self.product_id.sale_delay
return {}
@api.onchange('product_packaging')
def _onchange_product_packaging(self):
if self.product_packaging:
return self._check_package()
return {}
@api.onchange('product_id')
def _onchange_product_id_uom_check_availability(self):
if not self.product_uom or (self.product_id.uom_id.category_id.id != self.product_uom.category_id.id):
self.product_uom = self.product_id.uom_id
self._onchange_product_id_check_availability()
@api.onchange('product_uom_qty', 'product_uom', 'route_id')
def _onchange_product_id_check_availability(self):
if not self.product_id or not self.product_uom_qty or not self.product_uom:
self.product_packaging = False
return {}
if self.product_id.type == 'product':
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
product_qty = self.env['product.uom']._compute_qty_obj(self.product_uom, self.product_uom_qty, self.product_id.uom_id)
if float_compare(self.product_id.virtual_available, product_qty, precision_digits=precision) == -1:
is_available = self._check_routing()
if not is_available:
warning_mess = {
'title': _('Not enough inventory!'),
'message' : _('You plan to sell %.2f %s but you only have %.2f %s available!\nThe stock on hand is %.2f %s.') % \
(self.product_uom_qty, self.product_uom.name, self.product_id.virtual_available, self.product_id.uom_id.name, self.product_id.qty_available, self.product_id.uom_id.name)
}
return {'warning': warning_mess}
return {}
@api.onchange('product_uom_qty')
def _onchange_product_uom_qty(self):
if self.state == 'sale' and self.product_id.type in ['product', 'consu'] and self.product_uom_qty < self._origin.product_uom_qty:
warning_mess = {
'title': _('Ordered quantity decreased!'),
'message' : _('You are decreasing the ordered quantity! Do not forget to manually update the delivery order if needed.'),
}
return {'warning': warning_mess}
return {}
@api.multi
def _prepare_order_line_procurement(self, group_id=False):
vals = super(SaleOrderLine, self)._prepare_order_line_procurement(group_id=group_id)
date_planned = datetime.strptime(self.order_id.date_order, DEFAULT_SERVER_DATETIME_FORMAT)\
+ timedelta(days=self.customer_lead or 0.0) - timedelta(days=self.order_id.company_id.security_lead)
vals.update({
'date_planned': date_planned.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
'location_id': self.order_id.partner_shipping_id.property_stock_customer.id,
'route_ids': self.route_id and [(4, self.route_id.id)] or [],
'warehouse_id': self.order_id.warehouse_id and self.order_id.warehouse_id.id or False,
'partner_dest_id': self.order_id.partner_shipping_id.id,
'sale_line_id': self.id,
})
return vals
@api.multi
def _get_delivered_qty(self):
"""Computes the delivered quantity on sale order lines, based on done stock moves related to its procurements
"""
self.ensure_one()
super(SaleOrderLine, self)._get_delivered_qty()
qty = 0.0
for move in self.procurement_ids.mapped('move_ids').filtered(lambda r: r.state == 'done' and not r.scrapped):
#Note that we don't decrease quantity for customer returns on purpose: these are exeptions that must be treated manually. Indeed,
#modifying automatically the delivered quantity may trigger an automatic reinvoicing (refund) of the SO, which is definitively not wanted
if move.location_dest_id.usage == "customer":
qty += self.env['product.uom']._compute_qty_obj(move.product_uom, move.product_uom_qty, self.product_uom)
return qty
@api.multi
def _check_package(self):
default_uom = self.product_id.uom_id
pack = self.product_packaging
qty = self.product_uom_qty
q = self.env['product.uom']._compute_qty_obj(default_uom, pack.qty, self.product_uom)
if qty and q and (qty % q):
newqty = qty - (qty % q) + q
return {
'warning': {
'title': _('Warning'),
'message': _("This product is packaged by %d . You should sell %d .") % (pack.qty, newqty),
},
}
return {}
def _check_routing(self):
""" Verify the route of the product based on the warehouse
return True if the product availibility in stock does not need to be verified,
which is the case in MTO, Cross-Dock or Drop-Shipping
"""
is_available = False
product_routes = self.route_id or (self.product_id.route_ids + self.product_id.categ_id.total_route_ids)
# Check MTO
wh_mto_route = self.order_id.warehouse_id.mto_pull_id.route_id
if wh_mto_route and wh_mto_route <= product_routes:
is_available = True
else:
mto_route_id = False
try:
mto_route_id = self.env['stock.warehouse']._get_mto_route()
except UserError:
# if route MTO not found in ir_model_data, we treat the product as in MTS
pass
if mto_route_id and mto_route_id in product_routes.ids:
is_available = True
# Check Drop-Shipping
if not is_available:
for pull_rule in product_routes.mapped('pull_ids'):
if pull_rule.picking_type_id.sudo().default_location_src_id.usage == 'supplier' and\
pull_rule.picking_type_id.sudo().default_location_dest_id.usage == 'customer':
is_available = True
break
return is_available
class StockLocationRoute(models.Model):
_inherit = "stock.location.route"
sale_selectable = fields.Boolean(string="Selectable on Sales Order Line")
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
incoterms_id = fields.Many2one('stock.incoterms', string="Incoterms",
help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices.",
readonly=True, states={'draft': [('readonly', False)]})
class ProcurementOrder(models.Model):
_inherit = "procurement.order"
@api.model
def _run_move_create(self, procurement):
vals = super(ProcurementOrder, self)._run_move_create(procurement)
if self.sale_line_id:
vals.update({'sequence': self.sale_line_id.sequence})
return vals
class StockMove(models.Model):
_inherit = "stock.move"
@api.multi
def action_done(self):
result = super(StockMove, self).action_done()
# Update delivered quantities on sale order lines
todo = self.env['sale.order.line']
for move in self:
if (move.procurement_id.sale_line_id) and (move.product_id.invoice_policy in ('order', 'delivery')):
todo |= move.procurement_id.sale_line_id
for line in todo:
line.qty_delivered = line._get_delivered_qty()
return result
class StockPicking(models.Model):
_inherit = 'stock.picking'
@api.depends('move_lines')
def _compute_sale_id(self):
for picking in self:
sale_order = False
for move in picking.move_lines:
if move.procurement_id.sale_line_id:
sale_order = move.procurement_id.sale_line_id.order_id
break
picking.sale_id = sale_order.id if sale_order else False
sale_id = fields.Many2one(comodel_name='sale.order', string="Sale Order", compute='_compute_sale_id')
class AccountInvoiceLine(models.Model):
_inherit = "account.invoice.line"
def _get_anglo_saxon_price_unit(self):
price_unit = super(AccountInvoiceLine,self)._get_anglo_saxon_price_unit()
# in case of anglo saxon with a product configured as invoiced based on delivery, with perpetual
# valuation and real price costing method, we must find the real price for the cost of good sold
uom_obj = self.env['product.uom']
if self.product_id.invoice_policy == "delivery":
for s_line in self.sale_line_ids:
# qtys already invoiced
qty_done = sum([uom_obj._compute_qty_obj(x.uom_id, x.quantity, x.product_id.uom_id) for x in s_line.invoice_lines if x.invoice_id.state in ('open', 'paid')])
quantity = uom_obj._compute_qty_obj(self.uom_id, self.quantity, self.product_id.uom_id)
# Put moves in fixed order by date executed
moves = self.env['stock.move']
for procurement in s_line.procurement_ids:
moves |= procurement.move_ids
moves.sorted(lambda x: x.date)
# Go through all the moves and do nothing until you get to qty_done
# Beyond qty_done we need to calculate the average of the price_unit
# on the moves we encounter.
average_price_unit = self._compute_average_price(qty_done, quantity, moves)
price_unit = average_price_unit or price_unit
price_unit = uom_obj._compute_qty_obj(self.uom_id, price_unit, self.product_id.uom_id, round=False)
return price_unit
def _compute_average_price(self, qty_done, quantity, moves):
average_price_unit = 0
qty_delivered = 0
invoiced_qty = 0
for move in moves:
if move.state != 'done':
continue
invoiced_qty += move.product_qty
if invoiced_qty <= qty_done:
continue
qty_to_consider = move.product_qty
if invoiced_qty - move.product_qty < qty_done:
qty_to_consider = invoiced_qty - qty_done
qty_to_consider = min(qty_to_consider, quantity - qty_delivered)
qty_delivered += qty_to_consider
average_price_unit = (average_price_unit * (qty_delivered - qty_to_consider) + move.price_unit * qty_to_consider) / qty_delivered
if qty_delivered == quantity:
break
return average_price_unit
class ProductProduct(models.Model):
_inherit = 'product.product'
@api.multi
def _need_procurement(self):
for product in self:
if product.type not in ['service', 'digital']:
return True
return super(ProductProduct, self)._need_procurement()
| agpl-3.0 |
GunoH/intellij-community | python/helpers/py2only/docutils/parsers/rst/tableparser.py | 112 | 21007 | # $Id: tableparser.py 7320 2012-01-19 22:33:02Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
This module defines table parser classes,which parse plaintext-graphic tables
and produce a well-formed data structure suitable for building a CALS table.
:Classes:
- `GridTableParser`: Parse fully-formed tables represented with a grid.
- `SimpleTableParser`: Parse simple tables, delimited by top & bottom
borders.
:Exception class: `TableMarkupError`
:Function:
`update_dict_of_lists()`: Merge two dictionaries containing list values.
"""
__docformat__ = 'reStructuredText'
import re
import sys
from docutils import DataError
from docutils.utils import strip_combining_chars
class TableMarkupError(DataError):
"""
Raise if there is any problem with table markup.
The keyword argument `offset` denotes the offset of the problem
from the table's start line.
"""
def __init__(self, *args, **kwargs):
self.offset = kwargs.pop('offset', 0)
DataError.__init__(self, *args)
class TableParser:
"""
Abstract superclass for the common parts of the syntax-specific parsers.
"""
head_body_separator_pat = None
"""Matches the row separator between head rows and body rows."""
double_width_pad_char = '\x00'
"""Padding character for East Asian double-width text."""
def parse(self, block):
"""
Analyze the text `block` and return a table data structure.
Given a plaintext-graphic table in `block` (list of lines of text; no
whitespace padding), parse the table, construct and return the data
necessary to construct a CALS table or equivalent.
Raise `TableMarkupError` if there is any problem with the markup.
"""
self.setup(block)
self.find_head_body_sep()
self.parse_table()
structure = self.structure_from_cells()
return structure
def find_head_body_sep(self):
"""Look for a head/body row separator line; store the line index."""
for i in range(len(self.block)):
line = self.block[i]
if self.head_body_separator_pat.match(line):
if self.head_body_sep:
raise TableMarkupError(
'Multiple head/body row separators '
'(table lines %s and %s); only one allowed.'
% (self.head_body_sep+1, i+1), offset=i)
else:
self.head_body_sep = i
self.block[i] = line.replace('=', '-')
if self.head_body_sep == 0 or self.head_body_sep == (len(self.block)
- 1):
raise TableMarkupError('The head/body row separator may not be '
'the first or last line of the table.',
offset=i)
class GridTableParser(TableParser):
"""
Parse a grid table using `parse()`.
Here's an example of a grid table::
+------------------------+------------+----------+----------+
| Header row, column 1 | Header 2 | Header 3 | Header 4 |
+========================+============+==========+==========+
| body row 1, column 1 | column 2 | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2 | Cells may span columns. |
+------------------------+------------+---------------------+
| body row 3 | Cells may | - Table cells |
+------------------------+ span rows. | - contain |
| body row 4 | | - body elements. |
+------------------------+------------+---------------------+
Intersections use '+', row separators use '-' (except for one optional
head/body row separator, which uses '='), and column separators use '|'.
Passing the above table to the `parse()` method will result in the
following data structure::
([24, 12, 10, 10],
[[(0, 0, 1, ['Header row, column 1']),
(0, 0, 1, ['Header 2']),
(0, 0, 1, ['Header 3']),
(0, 0, 1, ['Header 4'])]],
[[(0, 0, 3, ['body row 1, column 1']),
(0, 0, 3, ['column 2']),
(0, 0, 3, ['column 3']),
(0, 0, 3, ['column 4'])],
[(0, 0, 5, ['body row 2']),
(0, 2, 5, ['Cells may span columns.']),
None,
None],
[(0, 0, 7, ['body row 3']),
(1, 0, 7, ['Cells may', 'span rows.', '']),
(1, 1, 7, ['- Table cells', '- contain', '- body elements.']),
None],
[(0, 0, 9, ['body row 4']), None, None, None]])
The first item is a list containing column widths (colspecs). The second
item is a list of head rows, and the third is a list of body rows. Each
row contains a list of cells. Each cell is either None (for a cell unused
because of another cell's span), or a tuple. A cell tuple contains four
items: the number of extra rows used by the cell in a vertical span
(morerows); the number of extra columns used by the cell in a horizontal
span (morecols); the line offset of the first line of the cell contents;
and the cell contents, a list of lines of text.
"""
head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$')
def setup(self, block):
self.block = block[:] # make a copy; it may be modified
self.block.disconnect() # don't propagate changes to parent
self.bottom = len(block) - 1
self.right = len(block[0]) - 1
self.head_body_sep = None
self.done = [-1] * len(block[0])
self.cells = []
self.rowseps = {0: [0]}
self.colseps = {0: [0]}
def parse_table(self):
"""
Start with a queue of upper-left corners, containing the upper-left
corner of the table itself. Trace out one rectangular cell, remember
it, and add its upper-right and lower-left corners to the queue of
potential upper-left corners of further cells. Process the queue in
top-to-bottom order, keeping track of how much of each text column has
been seen.
We'll end up knowing all the row and column boundaries, cell positions
and their dimensions.
"""
corners = [(0, 0)]
while corners:
top, left = corners.pop(0)
if top == self.bottom or left == self.right \
or top <= self.done[left]:
continue
result = self.scan_cell(top, left)
if not result:
continue
bottom, right, rowseps, colseps = result
update_dict_of_lists(self.rowseps, rowseps)
update_dict_of_lists(self.colseps, colseps)
self.mark_done(top, left, bottom, right)
cellblock = self.block.get_2D_block(top + 1, left + 1,
bottom, right)
cellblock.disconnect() # lines in cell can't sync with parent
cellblock.replace(self.double_width_pad_char, '')
self.cells.append((top, left, bottom, right, cellblock))
corners.extend([(top, right), (bottom, left)])
corners.sort()
if not self.check_parse_complete():
raise TableMarkupError('Malformed table; parse incomplete.')
def mark_done(self, top, left, bottom, right):
"""For keeping track of how much of each text column has been seen."""
before = top - 1
after = bottom - 1
for col in range(left, right):
assert self.done[col] == before
self.done[col] = after
def check_parse_complete(self):
"""Each text column should have been completely seen."""
last = self.bottom - 1
for col in range(self.right):
if self.done[col] != last:
return False
return True
def scan_cell(self, top, left):
"""Starting at the top-left corner, start tracing out a cell."""
assert self.block[top][left] == '+'
result = self.scan_right(top, left)
return result
def scan_right(self, top, left):
"""
Look for the top-right corner of the cell, and make note of all column
boundaries ('+').
"""
colseps = {}
line = self.block[top]
for i in range(left + 1, self.right + 1):
if line[i] == '+':
colseps[i] = [top]
result = self.scan_down(top, left, i)
if result:
bottom, rowseps, newcolseps = result
update_dict_of_lists(colseps, newcolseps)
return bottom, i, rowseps, colseps
elif line[i] != '-':
return None
return None
def scan_down(self, top, left, right):
"""
Look for the bottom-right corner of the cell, making note of all row
boundaries.
"""
rowseps = {}
for i in range(top + 1, self.bottom + 1):
if self.block[i][right] == '+':
rowseps[i] = [right]
result = self.scan_left(top, left, i, right)
if result:
newrowseps, colseps = result
update_dict_of_lists(rowseps, newrowseps)
return i, rowseps, colseps
elif self.block[i][right] != '|':
return None
return None
def scan_left(self, top, left, bottom, right):
"""
Noting column boundaries, look for the bottom-left corner of the cell.
It must line up with the starting point.
"""
colseps = {}
line = self.block[bottom]
for i in range(right - 1, left, -1):
if line[i] == '+':
colseps[i] = [bottom]
elif line[i] != '-':
return None
if line[left] != '+':
return None
result = self.scan_up(top, left, bottom, right)
if result is not None:
rowseps = result
return rowseps, colseps
return None
def scan_up(self, top, left, bottom, right):
"""
Noting row boundaries, see if we can return to the starting point.
"""
rowseps = {}
for i in range(bottom - 1, top, -1):
if self.block[i][left] == '+':
rowseps[i] = [left]
elif self.block[i][left] != '|':
return None
return rowseps
def structure_from_cells(self):
"""
From the data collected by `scan_cell()`, convert to the final data
structure.
"""
rowseps = self.rowseps.keys() # list of row boundaries
rowseps.sort()
rowindex = {}
for i in range(len(rowseps)):
rowindex[rowseps[i]] = i # row boundary -> row number mapping
colseps = self.colseps.keys() # list of column boundaries
colseps.sort()
colindex = {}
for i in range(len(colseps)):
colindex[colseps[i]] = i # column boundary -> col number map
colspecs = [(colseps[i] - colseps[i - 1] - 1)
for i in range(1, len(colseps))] # list of column widths
# prepare an empty table with the correct number of rows & columns
onerow = [None for i in range(len(colseps) - 1)]
rows = [onerow[:] for i in range(len(rowseps) - 1)]
# keep track of # of cells remaining; should reduce to zero
remaining = (len(rowseps) - 1) * (len(colseps) - 1)
for top, left, bottom, right, block in self.cells:
rownum = rowindex[top]
colnum = colindex[left]
assert rows[rownum][colnum] is None, (
'Cell (row %s, column %s) already used.'
% (rownum + 1, colnum + 1))
morerows = rowindex[bottom] - rownum - 1
morecols = colindex[right] - colnum - 1
remaining -= (morerows + 1) * (morecols + 1)
# write the cell into the table
rows[rownum][colnum] = (morerows, morecols, top + 1, block)
assert remaining == 0, 'Unused cells remaining.'
if self.head_body_sep: # separate head rows from body rows
numheadrows = rowindex[self.head_body_sep]
headrows = rows[:numheadrows]
bodyrows = rows[numheadrows:]
else:
headrows = []
bodyrows = rows
return (colspecs, headrows, bodyrows)
class SimpleTableParser(TableParser):
"""
Parse a simple table using `parse()`.
Here's an example of a simple table::
===== =====
col 1 col 2
===== =====
1 Second column of row 1.
2 Second column of row 2.
Second line of paragraph.
3 - Second column of row 3.
- Second item in bullet
list (row 3, column 2).
4 is a span
------------
5
===== =====
Top and bottom borders use '=', column span underlines use '-', column
separation is indicated with spaces.
Passing the above table to the `parse()` method will result in the
following data structure, whose interpretation is the same as for
`GridTableParser`::
([5, 25],
[[(0, 0, 1, ['col 1']),
(0, 0, 1, ['col 2'])]],
[[(0, 0, 3, ['1']),
(0, 0, 3, ['Second column of row 1.'])],
[(0, 0, 4, ['2']),
(0, 0, 4, ['Second column of row 2.',
'Second line of paragraph.'])],
[(0, 0, 6, ['3']),
(0, 0, 6, ['- Second column of row 3.',
'',
'- Second item in bullet',
' list (row 3, column 2).'])],
[(0, 1, 10, ['4 is a span'])],
[(0, 0, 12, ['5']),
(0, 0, 12, [''])]])
"""
head_body_separator_pat = re.compile('=[ =]*$')
span_pat = re.compile('-[ -]*$')
def setup(self, block):
self.block = block[:] # make a copy; it will be modified
self.block.disconnect() # don't propagate changes to parent
# Convert top & bottom borders to column span underlines:
self.block[0] = self.block[0].replace('=', '-')
self.block[-1] = self.block[-1].replace('=', '-')
self.head_body_sep = None
self.columns = []
self.border_end = None
self.table = []
self.done = [-1] * len(block[0])
self.rowseps = {0: [0]}
self.colseps = {0: [0]}
def parse_table(self):
"""
First determine the column boundaries from the top border, then
process rows. Each row may consist of multiple lines; accumulate
lines until a row is complete. Call `self.parse_row` to finish the
job.
"""
# Top border must fully describe all table columns.
self.columns = self.parse_columns(self.block[0], 0)
self.border_end = self.columns[-1][1]
firststart, firstend = self.columns[0]
offset = 1 # skip top border
start = 1
text_found = None
while offset < len(self.block):
line = self.block[offset]
if self.span_pat.match(line):
# Column span underline or border; row is complete.
self.parse_row(self.block[start:offset], start,
(line.rstrip(), offset))
start = offset + 1
text_found = None
elif line[firststart:firstend].strip():
# First column not blank, therefore it's a new row.
if text_found and offset != start:
self.parse_row(self.block[start:offset], start)
start = offset
text_found = 1
elif not text_found:
start = offset + 1
offset += 1
def parse_columns(self, line, offset):
"""
Given a column span underline, return a list of (begin, end) pairs.
"""
cols = []
end = 0
while True:
begin = line.find('-', end)
end = line.find(' ', begin)
if begin < 0:
break
if end < 0:
end = len(line)
cols.append((begin, end))
if self.columns:
if cols[-1][1] != self.border_end:
raise TableMarkupError('Column span incomplete in table '
'line %s.' % (offset+1),
offset=offset)
# Allow for an unbounded rightmost column:
cols[-1] = (cols[-1][0], self.columns[-1][1])
return cols
def init_row(self, colspec, offset):
i = 0
cells = []
for start, end in colspec:
morecols = 0
try:
assert start == self.columns[i][0]
while end != self.columns[i][1]:
i += 1
morecols += 1
except (AssertionError, IndexError):
raise TableMarkupError('Column span alignment problem '
'in table line %s.' % (offset+2),
offset=offset+1)
cells.append([0, morecols, offset, []])
i += 1
return cells
def parse_row(self, lines, start, spanline=None):
"""
Given the text `lines` of a row, parse it and append to `self.table`.
The row is parsed according to the current column spec (either
`spanline` if provided or `self.columns`). For each column, extract
text from each line, and check for text in column margins. Finally,
adjust for insignificant whitespace.
"""
if not (lines or spanline):
# No new row, just blank lines.
return
if spanline:
columns = self.parse_columns(*spanline)
span_offset = spanline[1]
else:
columns = self.columns[:]
span_offset = start
self.check_columns(lines, start, columns)
row = self.init_row(columns, start)
for i in range(len(columns)):
start, end = columns[i]
cellblock = lines.get_2D_block(0, start, len(lines), end)
cellblock.disconnect() # lines in cell can't sync with parent
cellblock.replace(self.double_width_pad_char, '')
row[i][3] = cellblock
self.table.append(row)
def check_columns(self, lines, first_line, columns):
"""
Check for text in column margins and text overflow in the last column.
Raise TableMarkupError if anything but whitespace is in column margins.
Adjust the end value for the last column if there is text overflow.
"""
# "Infinite" value for a dummy last column's beginning, used to
# check for text overflow:
columns.append((sys.maxint, None))
lastcol = len(columns) - 2
# combining characters do not contribute to the column width
lines = [strip_combining_chars(line) for line in lines]
for i in range(len(columns) - 1):
start, end = columns[i]
nextstart = columns[i+1][0]
offset = 0
for line in lines:
if i == lastcol and line[end:].strip():
text = line[start:].rstrip()
new_end = start + len(text)
columns[i] = (start, new_end)
main_start, main_end = self.columns[-1]
if new_end > main_end:
self.columns[-1] = (main_start, new_end)
elif line[end:nextstart].strip():
raise TableMarkupError('Text in column margin '
'in table line %s.' % (first_line+offset+1),
offset=first_line+offset)
offset += 1
columns.pop()
def structure_from_cells(self):
colspecs = [end - start for start, end in self.columns]
first_body_row = 0
if self.head_body_sep:
for i in range(len(self.table)):
if self.table[i][0][2] > self.head_body_sep:
first_body_row = i
break
return (colspecs, self.table[:first_body_row],
self.table[first_body_row:])
def update_dict_of_lists(master, newdata):
"""
Extend the list values of `master` with those from `newdata`.
Both parameters must be dictionaries containing list values.
"""
for key, values in newdata.items():
master.setdefault(key, []).extend(values)
| apache-2.0 |
takinbo/rapidsms-borno | apps/django_extensions/management/commands/runjob.py | 5 | 1965 | from django.core.management.base import LabelCommand
from optparse import make_option
from extensions.management.jobs import get_job, print_jobs
class Command(LabelCommand):
option_list = LabelCommand.option_list + (
make_option('--list', '-l', action="store_true", dest="list_jobs",
help="List all jobs with there description"),
make_option('--verbose', '-v', action="store_true", dest="verbose",
help="Verbose messages"),
)
help = "Run a single maintenance job."
args = "[app_name] job_name"
label = ""
requires_model_validation = True
def runjob(self, app_name, job_name, options):
if options.get('verbose', False):
print "Executing job: %s (app: %s)" % (job_name, app_name)
try:
job = get_job(app_name, job_name)
except KeyError, e:
if app_name:
print "Error: Job %s for applabel %s not found" % (app_name, job_name)
else:
print "Error: Job %s not found" % job_name
print "Use -l option to view all the available jobs"
return
try:
job().execute()
except Exception, e:
import traceback
print "ERROR OCCURED IN JOB: %s (APP: %s)" % (job_name, app_name)
print "START TRACEBACK:"
traceback.print_exc()
print "END TRACEBACK\n"
def handle(self, *args, **options):
app_name = None
job_name = None
if len(args)==1:
job_name = args[0]
elif len(args)==2:
app_name, job_name = args
if options.get('list_jobs'):
print_jobs(only_scheduled=False, show_when=True, show_appname=True)
else:
if not job_name:
print "Run a single maintenance job. Please specify the name of the job."
return
self.runjob(app_name, job_name, options)
| lgpl-3.0 |
etanoox/agyrion | share/qt/make_spinner.py | 4415 | 1035 | #!/usr/bin/env python
# W.J. van der Laan, 2011
# Make spinning .mng animation from a .png
# Requires imagemagick 6.7+
from __future__ import division
from os import path
from PIL import Image
from subprocess import Popen
SRC='img/reload_scaled.png'
DST='../../src/qt/res/movies/update_spinner.mng'
TMPDIR='/tmp'
TMPNAME='tmp-%03i.png'
NUMFRAMES=35
FRAMERATE=10.0
CONVERT='convert'
CLOCKWISE=True
DSIZE=(16,16)
im_src = Image.open(SRC)
if CLOCKWISE:
im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT)
def frame_to_filename(frame):
return path.join(TMPDIR, TMPNAME % frame)
frame_files = []
for frame in xrange(NUMFRAMES):
rotation = (frame + 0.5) / NUMFRAMES * 360.0
if CLOCKWISE:
rotation = -rotation
im_new = im_src.rotate(rotation, Image.BICUBIC)
im_new.thumbnail(DSIZE, Image.ANTIALIAS)
outfile = frame_to_filename(frame)
im_new.save(outfile, 'png')
frame_files.append(outfile)
p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST])
p.communicate()
| mit |
blooparksystems/odoo | addons/account/wizard/account_report_aged_partner_balance.py | 19 | 1759 | # -*- coding: utf-8 -*-
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp import api, fields, models, _
from openerp.exceptions import UserError
class AccountAgedTrialBalance(models.TransientModel):
_name = 'account.aged.trial.balance'
_inherit = 'account.common.partner.report'
_description = 'Account Aged Trial balance Report'
period_length = fields.Integer(string='Period Length (days)', required=True, default=30)
journal_ids = fields.Many2many('account.journal', string='Journals', required=True)
date_from = fields.Date(default=lambda *a: time.strftime('%Y-%m-%d'))
def _print_report(self, data):
res = {}
data = self.pre_print_report(data)
data['form'].update(self.read(['period_length'])[0])
period_length = data['form']['period_length']
if period_length<=0:
raise UserError(_('You must set a period length greater than 0.'))
if not data['form']['date_from']:
raise UserError(_('You must set a start date.'))
start = datetime.strptime(data['form']['date_from'], "%Y-%m-%d")
for i in range(5)[::-1]:
stop = start - relativedelta(days=period_length)
res[str(i)] = {
'name': (i!=0 and (str((5-(i+1)) * period_length) + '-' + str((5-i) * period_length)) or ('+'+str(4 * period_length))),
'stop': start.strftime('%Y-%m-%d'),
'start': (i!=0 and stop.strftime('%Y-%m-%d') or False),
}
start = stop - relativedelta(days=1)
data['form'].update(res)
return self.env['report'].with_context(landscape=True).get_action(self, 'account.report_agedpartnerbalance', data=data)
| gpl-3.0 |
sander76/home-assistant | homeassistant/components/file/notify.py | 14 | 1682 | """Support for file notification."""
import os
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONF_FILENAME
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
CONF_TIMESTAMP = "timestamp"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_FILENAME): cv.string,
vol.Optional(CONF_TIMESTAMP, default=False): cv.boolean,
}
)
def get_service(hass, config, discovery_info=None):
"""Get the file notification service."""
filename = config[CONF_FILENAME]
timestamp = config[CONF_TIMESTAMP]
return FileNotificationService(hass, filename, timestamp)
class FileNotificationService(BaseNotificationService):
"""Implement the notification service for the File service."""
def __init__(self, hass, filename, add_timestamp):
"""Initialize the service."""
self.filepath = os.path.join(hass.config.config_dir, filename)
self.add_timestamp = add_timestamp
def send_message(self, message="", **kwargs):
"""Send a message to a file."""
with open(self.filepath, "a") as file:
if os.stat(self.filepath).st_size == 0:
title = f"{kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)} notifications (Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n"
file.write(title)
if self.add_timestamp:
text = f"{dt_util.utcnow().isoformat()} {message}\n"
else:
text = f"{message}\n"
file.write(text)
| apache-2.0 |
xs2maverick/adhocracy3.mercator | src/adhocracy_core/adhocracy_core/catalog/test_index.py | 2 | 8335 | """Test custom catalog index."""
from unittest.mock import Mock
from pyramid import testing
from pytest import fixture
from pytest import raises
class TestField:
_marker = object()
@fixture
def inst(self):
from hypatia.field import FieldIndex
from BTrees import family64
def _discriminator(obj, default):
if obj is self._marker:
return default
return obj
return FieldIndex(_discriminator, family64)
def test_sort_integer_strings(self, inst):
inst.index_doc(0, '-1')
inst.index_doc(3, '10')
inst.index_doc(1, '1')
assert [x for x in inst.sort([0, 3, 1])] == [0, 1, 3]
class TestReference:
@fixture
def catalog(self):
from substanced.interfaces import IService
catalog = testing.DummyResource(__provides__=IService,
__is_service__=True)
return catalog
@fixture
def context(self, pool_graph, catalog):
pool_graph['catalogs'] = catalog
return pool_graph
def make_one(self):
from .index import ReferenceIndex
index = ReferenceIndex()
return index
def test_create(self):
from zope.interface.verify import verifyObject
from hypatia.interfaces import IIndex
inst = self.make_one()
assert IIndex.providedBy(inst)
assert verifyObject(IIndex, inst)
def test_reset(self):
inst = self.make_one()
inst._not_indexed.add(1)
inst.reset()
assert 1 not in inst._not_indexed
def test_document_repr(self, context, catalog):
from substanced.util import get_oid
inst = self.make_one()
catalog['index'] = inst
assert inst.document_repr(get_oid(context)) == ('',)
def test_document_repr_missing(self, context, catalog):
inst = self.make_one()
catalog['index'] = inst
assert inst.document_repr(1) is None
def test_index_doc(self):
inst = self.make_one()
assert inst.index_doc(1, None) is None
def test_unindex_doc(self):
inst = self.make_one()
assert inst.unindex_doc(1) is None
def test_reindex_doc(self):
inst = self.make_one()
assert inst.reindex_doc(1, None) is None
def test_docids(self, context, catalog):
inst = self.make_one()
catalog['index'] = inst
assert list(inst.docids()) == []
def test_not_indexed(self):
inst = self.make_one()
assert list(inst.not_indexed()) == []
def test_search_raise_if_source_and_target_is_none(self):
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import ISheet
inst = self.make_one()
reference = Reference(None, ISheet, '', None)
with raises(ValueError):
inst._search(reference)
def test_search_raise_if_source_and_target_is_not_none(self):
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import ISheet
inst = self.make_one()
reference = Reference(object(), ISheet, '', object())
with raises(ValueError):
inst._search(reference)
def test_search_sources(self, mock_graph, mock_objectmap):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import SheetToSheet
target = testing.DummyResource()
inst = self.make_one()
inst.__graph__ = mock_graph
mock_graph.get_reftypes.return_value = [(ISheet, '', SheetToSheet)]
oid1, oid2 = 1, 2
mock_objectmap.sourceids.return_value = [oid2, oid1]
inst._objectmap = mock_objectmap
reference = Reference(None, ISheet, '', target)
result = inst._search(reference)
mock_objectmap.sourceids.assert_called_with(target, SheetToSheet)
assert list(result) == [oid1, oid2] # order is not preserved
def test_search_targets(self, mock_graph, mock_objectmap):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import SheetToSheet
source = testing.DummyResource()
inst = self.make_one()
inst.__graph__ = mock_graph
mock_graph.get_reftypes.return_value = [(ISheet, '', SheetToSheet)]
oid1, oid2 = 1, 2
mock_objectmap.targetids.return_value = [oid2, oid1]
inst._objectmap = mock_objectmap
reference = Reference(source, ISheet, '', None)
result = inst._search(reference)
mock_objectmap.targetids.assert_called_with(source, SheetToSheet)
assert list(result) == [oid1, oid2] # order is not preserver
def test_search_with_order_targets(self, mock_graph, mock_objectmap):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import SheetToSheet
source = testing.DummyResource()
inst = self.make_one()
inst.__graph__ = mock_graph
mock_graph.get_reftypes.return_value = [(ISheet, '', SheetToSheet)]
oid1, oid2 = 1, 2
mock_objectmap.targetids.return_value = [oid2, oid1]
inst._objectmap = mock_objectmap
reference = Reference(source, ISheet, '', None)
result = inst.search_with_order(reference)
mock_objectmap.targetids.assert_called_with(source, SheetToSheet)
assert list(result) == [oid2, oid1]
def test_search_with_order_sources(self, mock_graph, mock_objectmap):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import SheetToSheet
target = testing.DummyResource()
inst = self.make_one()
inst.__graph__ = mock_graph
mock_graph.get_reftypes.return_value = [(ISheet, '', SheetToSheet)]
oid1, oid2 = 1, 2
mock_objectmap.sourceids.return_value = [oid2, oid1]
inst._objectmap = mock_objectmap
reference = Reference(None, ISheet, '', target)
result = inst.search_with_order(reference)
mock_objectmap.sourceids.assert_called_with(target, SheetToSheet)
assert list(result) == [oid2, oid1]
def test_apply_with_valid_query(self, mock_graph, mock_objectmap):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.interfaces import SheetToSheet
mock_objectmap.sourceids.return_value = set([1])
inst = self.make_one()
inst._objectmap = mock_objectmap
mock_graph.get_reftypes.return_value = [(ISheet, '', SheetToSheet)]
inst.__graph__ = mock_graph
target = testing.DummyResource()
reference = Reference(None, ISheet, '', target)
query = {'reference': reference}
result = inst.apply(query)
assert list(result) == [1]
def test_apply_with_invalid_query(self):
inst = self.make_one()
query = {'WRONG': ''}
with raises(KeyError):
inst.apply(query)
def test_apply_intersect_reference_not_exists(self, mock_objectmap):
# actually we test the default implementation in hypatia.util
import BTrees
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
from adhocracy_core.graph import ObjectMap
mock_objectmap.sourceids.return_value = set()
inst = self.make_one()
inst._mock_objectmap = mock_objectmap
target = testing.DummyResource()
reference = Reference(None, ISheet, '', target)
query = {'reference': reference}
other_result = BTrees.family64.IF.Set([1])
result = inst.apply_intersect(query, other_result)
assert list(result) == []
def test_eq(self):
from adhocracy_core.interfaces import ISheet
from adhocracy_core.interfaces import Reference
inst = self.make_one()
target = testing.DummyResource()
reference = Reference(None, ISheet, '', target)
result = inst.eq(reference)
assert result._value == {'reference': reference}
| agpl-3.0 |
technomalogical/suds | suds/xsd/query.py | 202 | 6451 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) 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.
#
# 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 Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser 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.
# written by: Jeff Ortel ( jortel@redhat.com )
"""
The I{query} module defines a class for performing schema queries.
"""
from logging import getLogger
from suds import *
from suds.sudsobject import *
from suds.xsd import qualify, isqref
from suds.xsd.sxbuiltin import Factory
log = getLogger(__name__)
class Query(Object):
"""
Schema query base class.
"""
def __init__(self, ref=None):
"""
@param ref: The schema reference being queried.
@type ref: qref
"""
Object.__init__(self)
self.id = objid(self)
self.ref = ref
self.history = []
self.resolved = False
if not isqref(self.ref):
raise Exception('%s, must be qref' % tostr(self.ref))
def execute(self, schema):
"""
Execute this query using the specified schema.
@param schema: The schema associated with the query. The schema
is used by the query to search for items.
@type schema: L{schema.Schema}
@return: The item matching the search criteria.
@rtype: L{sxbase.SchemaObject}
"""
raise Exception, 'not-implemented by subclass'
def filter(self, result):
"""
Filter the specified result based on query criteria.
@param result: A potential result.
@type result: L{sxbase.SchemaObject}
@return: True if result should be excluded.
@rtype: boolean
"""
if result is None:
return True
reject = ( result in self.history )
if reject:
log.debug('result %s, rejected by\n%s', Repr(result), self)
return reject
def result(self, result):
"""
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
"""
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result.resolve()
log.debug('%s, found as: %s', self.ref, Repr(result))
self.history.append(result)
return result
class BlindQuery(Query):
"""
Schema query class that I{blindly} searches for a reference in
the specified schema. It may be used to find Elements and Types but
will match on an Element first. This query will also find builtins.
"""
def execute(self, schema):
if schema.builtin(self.ref):
name = self.ref[0]
b = Factory.create(schema, name)
log.debug('%s, found builtin (%s)', self.id, name)
return b
result = None
for d in (schema.elements, schema.types):
result = d.get(self.ref)
if self.filter(result):
result = None
else:
break
if result is None:
eq = ElementQuery(self.ref)
eq.history = self.history
result = eq.execute(schema)
return self.result(result)
class TypeQuery(Query):
"""
Schema query class that searches for Type references in
the specified schema. Matches on root types only.
"""
def execute(self, schema):
if schema.builtin(self.ref):
name = self.ref[0]
b = Factory.create(schema, name)
log.debug('%s, found builtin (%s)', self.id, name)
return b
result = schema.types.get(self.ref)
if self.filter(result):
result = None
return self.result(result)
class GroupQuery(Query):
"""
Schema query class that searches for Group references in
the specified schema.
"""
def execute(self, schema):
result = schema.groups.get(self.ref)
if self.filter(result):
result = None
return self.result(result)
class AttrQuery(Query):
"""
Schema query class that searches for Attribute references in
the specified schema. Matches on root Attribute by qname first, then searches
deep into the document.
"""
def execute(self, schema):
result = schema.attributes.get(self.ref)
if self.filter(result):
result = self.__deepsearch(schema)
return self.result(result)
def __deepsearch(self, schema):
from suds.xsd.sxbasic import Attribute
result = None
for e in schema.all:
result = e.find(self.ref, (Attribute,))
if self.filter(result):
result = None
else:
break
return result
class AttrGroupQuery(Query):
"""
Schema query class that searches for attributeGroup references in
the specified schema.
"""
def execute(self, schema):
result = schema.agrps.get(self.ref)
if self.filter(result):
result = None
return self.result(result)
class ElementQuery(Query):
"""
Schema query class that searches for Element references in
the specified schema. Matches on root Elements by qname first, then searches
deep into the document.
"""
def execute(self, schema):
result = schema.elements.get(self.ref)
if self.filter(result):
result = self.__deepsearch(schema)
return self.result(result)
def __deepsearch(self, schema):
from suds.xsd.sxbasic import Element
result = None
for e in schema.all:
result = e.find(self.ref, (Element,))
if self.filter(result):
result = None
else:
break
return result | lgpl-3.0 |
semio/zipline | tests/test_events_through_risk.py | 17 | 11560 | #
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import datetime
import pytz
import numpy as np
from zipline.finance.trading import SimulationParameters
from zipline.finance import trading
from zipline.algorithm import TradingAlgorithm
from zipline.protocol import (
Event,
DATASOURCE_TYPE
)
class BuyAndHoldAlgorithm(TradingAlgorithm):
SID_TO_BUY_AND_HOLD = 1
def initialize(self):
self.holding = False
def handle_data(self, data):
if not self.holding:
self.order(self.sid(self.SID_TO_BUY_AND_HOLD), 100)
self.holding = True
class TestEventsThroughRisk(unittest.TestCase):
def test_daily_buy_and_hold(self):
start_date = datetime.datetime(
year=2006,
month=1,
day=3,
hour=0,
minute=0,
tzinfo=pytz.utc)
end_date = datetime.datetime(
year=2006,
month=1,
day=5,
hour=0,
minute=0,
tzinfo=pytz.utc)
sim_params = SimulationParameters(
period_start=start_date,
period_end=end_date,
data_frequency='daily',
emission_rate='daily'
)
algo = BuyAndHoldAlgorithm(
identifiers=[1],
sim_params=sim_params)
first_date = datetime.datetime(2006, 1, 3, tzinfo=pytz.utc)
second_date = datetime.datetime(2006, 1, 4, tzinfo=pytz.utc)
third_date = datetime.datetime(2006, 1, 5, tzinfo=pytz.utc)
trade_bar_data = [
Event({
'open_price': 10,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': first_date,
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 15,
'close_price': 20,
'price': 20,
'volume': 2000,
'sid': 1,
'dt': second_date,
'source_id': 'test_list',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 20,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': third_date,
'source_id': 'test_list',
'type': DATASOURCE_TYPE.TRADE
}),
]
benchmark_data = [
Event({
'returns': 0.1,
'dt': first_date,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
Event({
'returns': 0.2,
'dt': second_date,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
Event({
'returns': 0.4,
'dt': third_date,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
]
algo.benchmark_return_source = benchmark_data
algo.set_sources(list([trade_bar_data]))
gen = algo._create_generator(sim_params)
# TODO: Hand derive these results.
# Currently, the output from the time of this writing to
# at least be an early warning against changes.
expected_algorithm_returns = {
first_date: 0.0,
second_date: -0.000350,
third_date: -0.050018
}
# TODO: Hand derive these results.
# Currently, the output from the time of this writing to
# at least be an early warning against changes.
expected_sharpe = {
first_date: np.nan,
second_date: -22.322677,
third_date: -9.353741
}
for bar in gen:
current_dt = algo.datetime
crm = algo.perf_tracker.cumulative_risk_metrics
dt_loc = crm.cont_index.get_loc(current_dt)
np.testing.assert_almost_equal(
crm.algorithm_returns[dt_loc],
expected_algorithm_returns[current_dt],
decimal=6)
np.testing.assert_almost_equal(
crm.sharpe[dt_loc],
expected_sharpe[current_dt],
decimal=6,
err_msg="Mismatch at %s" % (current_dt,))
def test_minute_buy_and_hold(self):
with trading.TradingEnvironment():
start_date = datetime.datetime(
year=2006,
month=1,
day=3,
hour=0,
minute=0,
tzinfo=pytz.utc)
end_date = datetime.datetime(
year=2006,
month=1,
day=5,
hour=0,
minute=0,
tzinfo=pytz.utc)
sim_params = SimulationParameters(
period_start=start_date,
period_end=end_date,
emission_rate='daily',
data_frequency='minute')
algo = BuyAndHoldAlgorithm(
identifiers=[1],
sim_params=sim_params)
first_date = datetime.datetime(2006, 1, 3, tzinfo=pytz.utc)
first_open, first_close = \
trading.environment.get_open_and_close(first_date)
second_date = datetime.datetime(2006, 1, 4, tzinfo=pytz.utc)
second_open, second_close = \
trading.environment.get_open_and_close(second_date)
third_date = datetime.datetime(2006, 1, 5, tzinfo=pytz.utc)
third_open, third_close = \
trading.environment.get_open_and_close(third_date)
benchmark_data = [
Event({
'returns': 0.1,
'dt': first_close,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
Event({
'returns': 0.2,
'dt': second_close,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
Event({
'returns': 0.4,
'dt': third_close,
'source_id': 'test-benchmark-source',
'type': DATASOURCE_TYPE.BENCHMARK
}),
]
trade_bar_data = [
Event({
'open_price': 10,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': first_open,
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 10,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': first_open + datetime.timedelta(minutes=10),
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 15,
'close_price': 20,
'price': 20,
'volume': 2000,
'sid': 1,
'dt': second_open,
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 15,
'close_price': 20,
'price': 20,
'volume': 2000,
'sid': 1,
'dt': second_open + datetime.timedelta(minutes=10),
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 20,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': third_open,
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
Event({
'open_price': 20,
'close_price': 15,
'price': 15,
'volume': 1000,
'sid': 1,
'dt': third_open + datetime.timedelta(minutes=10),
'source_id': 'test-trade-source',
'type': DATASOURCE_TYPE.TRADE
}),
]
algo.benchmark_return_source = benchmark_data
algo.set_sources(list([trade_bar_data]))
gen = algo._create_generator(sim_params)
crm = algo.perf_tracker.cumulative_risk_metrics
dt_loc = crm.cont_index.get_loc(algo.datetime)
first_msg = next(gen)
self.assertIsNotNone(first_msg,
"There should be a message emitted.")
# Protects against bug where the positions appeared to be
# a day late, because benchmarks were triggering
# calculations before the events for the day were
# processed.
self.assertEqual(1, len(algo.portfolio.positions), "There should "
"be one position after the first day.")
self.assertEquals(
0,
crm.algorithm_volatility[dt_loc],
"On the first day algorithm volatility does not exist.")
second_msg = next(gen)
self.assertIsNotNone(second_msg, "There should be a message "
"emitted.")
self.assertEqual(1, len(algo.portfolio.positions),
"Number of positions should stay the same.")
# TODO: Hand derive. Current value is just a canary to
# detect changes.
np.testing.assert_almost_equal(
0.050022510129558301,
crm.algorithm_returns[-1],
decimal=6)
third_msg = next(gen)
self.assertEqual(1, len(algo.portfolio.positions),
"Number of positions should stay the same.")
self.assertIsNotNone(third_msg, "There should be a message "
"emitted.")
# TODO: Hand derive. Current value is just a canary to
# detect changes.
np.testing.assert_almost_equal(
-0.047639464532418657,
crm.algorithm_returns[-1],
decimal=6)
| apache-2.0 |
x111ong/odoo | addons/account/wizard/account_report_common_partner.py | 385 | 1999 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 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/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_common_partner_report(osv.osv_memory):
_name = 'account.common.partner.report'
_description = 'Account Common Partner Report'
_inherit = "account.common.report"
_columns = {
'result_selection': fields.selection([('customer','Receivable Accounts'),
('supplier','Payable Accounts'),
('customer_supplier','Receivable and Payable Accounts')],
"Partner's", required=True),
}
_defaults = {
'result_selection': 'customer',
}
def pre_print_report(self, cr, uid, ids, data, context=None):
if context is None:
context = {}
data['form'].update(self.read(cr, uid, ids, ['result_selection'], context=context)[0])
return data
#vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
wakatime/wakatime | wakatime/packages/py27/pygments/lexers/resource.py | 4 | 2926 | # -*- coding: utf-8 -*-
"""
pygments.lexers.resource
~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for resource definition files.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, words
from pygments.token import Comment, String, Number, Operator, Text, \
Keyword, Name
__all__ = ['ResourceLexer']
class ResourceLexer(RegexLexer):
"""Lexer for `ICU Resource bundles
<http://userguide.icu-project.org/locale/resources>`_.
.. versionadded:: 2.0
"""
name = 'ResourceBundle'
aliases = ['resource', 'resourcebundle']
filenames = []
_types = (':table', ':array', ':string', ':bin', ':import', ':intvector',
':int', ':alias')
flags = re.MULTILINE | re.IGNORECASE
tokens = {
'root': [
(r'//.*?$', Comment),
(r'"', String, 'string'),
(r'-?\d+', Number.Integer),
(r'[,{}]', Operator),
(r'([^\s{:]+)(\s*)(%s?)' % '|'.join(_types),
bygroups(Name, Text, Keyword)),
(r'\s+', Text),
(words(_types), Keyword),
],
'string': [
(r'(\\x[0-9a-f]{2}|\\u[0-9a-f]{4}|\\U00[0-9a-f]{6}|'
r'\\[0-7]{1,3}|\\c.|\\[abtnvfre\'"?\\]|\\\{|[^"{\\])+', String),
(r'\{', String.Escape, 'msgname'),
(r'"', String, '#pop')
],
'msgname': [
(r'([^{},]+)(\s*)', bygroups(Name, String.Escape), ('#pop', 'message'))
],
'message': [
(r'\{', String.Escape, 'msgname'),
(r'\}', String.Escape, '#pop'),
(r'(,)(\s*)([a-z]+)(\s*\})',
bygroups(Operator, String.Escape, Keyword, String.Escape), '#pop'),
(r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)(offset)(\s*)(:)(\s*)(-?\d+)(\s*)',
bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,
String.Escape, Operator.Word, String.Escape, Operator,
String.Escape, Number.Integer, String.Escape), 'choice'),
(r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)',
bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,
String.Escape), 'choice'),
(r'\s+', String.Escape)
],
'choice': [
(r'(=|<|>|<=|>=|!=)(-?\d+)(\s*\{)',
bygroups(Operator, Number.Integer, String.Escape), 'message'),
(r'([a-z]+)(\s*\{)', bygroups(Keyword.Type, String.Escape), 'str'),
(r'\}', String.Escape, ('#pop', '#pop')),
(r'\s+', String.Escape)
],
'str': [
(r'\}', String.Escape, '#pop'),
(r'\{', String.Escape, 'msgname'),
(r'[^{}]+', String)
]
}
def analyse_text(text):
if text.startswith('root:table'):
return 1.0
| bsd-3-clause |
bakkou-badri/dataminingproject | env/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/__init__.py | 745 | 1295 | ######################## BEGIN LICENSE BLOCK ########################
# 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 St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
__version__ = "2.2.1"
from sys import version_info
def detect(aBuf):
if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
(version_info >= (3, 0) and not isinstance(aBuf, bytes))):
raise ValueError('Expected a bytes object, not a unicode object')
from . import universaldetector
u = universaldetector.UniversalDetector()
u.reset()
u.feed(aBuf)
u.close()
return u.result
| gpl-2.0 |
dennybaa/mistral | mistral/tests/unit/engine/test_default_engine.py | 1 | 14261 | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import uuid
import mock
from oslo_config import cfg
from oslo_log import log as logging
from oslo_messaging.rpc import client as rpc_client
from mistral.db.v2 import api as db_api
from mistral.db.v2.sqlalchemy import models
from mistral.engine import default_engine as d_eng
from mistral import exceptions as exc
from mistral.services import workbooks as wb_service
from mistral.tests import base
from mistral.tests.unit.engine import base as eng_test_base
from mistral.workflow import states
from mistral.workflow import utils as wf_utils
LOG = logging.getLogger(__name__)
# Use the set_default method to set value otherwise in certain test cases
# the change in value is not permanent.
cfg.CONF.set_default('auth_enable', False, group='pecan')
WORKBOOK = """
---
version: '2.0'
name: wb
workflows:
wf:
type: reverse
input:
- param1: value1
- param2
tasks:
task1:
action: std.echo output=<% $.param1 %>
publish:
var: <% $.task1 %>
task2:
action: std.echo output=<% $.param2 %>
requires: [task1]
"""
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
ENVIRONMENT = {
'id': str(uuid.uuid4()),
'name': 'test',
'description': 'my test settings',
'variables': {
'key1': 'abc',
'key2': 123
},
'scope': 'private',
'created_at': str(datetime.datetime.utcnow()),
'updated_at': str(datetime.datetime.utcnow())
}
ENVIRONMENT_DB = models.Environment(
id=ENVIRONMENT['id'],
name=ENVIRONMENT['name'],
description=ENVIRONMENT['description'],
variables=ENVIRONMENT['variables'],
scope=ENVIRONMENT['scope'],
created_at=datetime.datetime.strptime(ENVIRONMENT['created_at'],
DATETIME_FORMAT),
updated_at=datetime.datetime.strptime(ENVIRONMENT['updated_at'],
DATETIME_FORMAT)
)
MOCK_ENVIRONMENT = mock.MagicMock(return_value=ENVIRONMENT_DB)
MOCK_NOT_FOUND = mock.MagicMock(side_effect=exc.NotFoundException())
class DefaultEngineTest(base.DbTestCase):
def setUp(self):
super(DefaultEngineTest, self).setUp()
wb_service.create_workbook_v2(WORKBOOK)
# Note: For purposes of this test we can easily use
# simple magic mocks for engine and executor clients
self.engine = d_eng.DefaultEngine(mock.MagicMock())
def test_start_workflow(self):
wf_input = {'param1': 'Hey', 'param2': 'Hi'}
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf',
wf_input,
'my execution',
task_name='task2'
)
self.assertIsNotNone(wf_ex)
self.assertEqual(states.RUNNING, wf_ex.state)
self.assertEqual('my execution', wf_ex.description)
self._assert_dict_contains_subset(wf_input, wf_ex.context)
self.assertIn('__execution', wf_ex.context)
# Note: We need to reread execution to access related tasks.
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertEqual(1, len(wf_ex.task_executions))
task_ex = wf_ex.task_executions[0]
self.assertEqual('wb.wf', task_ex.workflow_name)
self.assertEqual('task1', task_ex.name)
self.assertEqual(states.RUNNING, task_ex.state)
self.assertIsNotNone(task_ex.spec)
self.assertDictEqual({}, task_ex.runtime_context)
# Data Flow properties.
self._assert_dict_contains_subset(wf_input, task_ex.in_context)
self.assertIn('__execution', task_ex.in_context)
action_execs = db_api.get_action_executions(
task_execution_id=task_ex.id
)
self.assertEqual(1, len(action_execs))
task_action_ex = action_execs[0]
self.assertIsNotNone(task_action_ex)
self.assertDictEqual({'output': 'Hey'}, task_action_ex.input)
def test_start_workflow_with_input_default(self):
wf_input = {'param2': 'value2'}
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf',
wf_input,
task_name='task1'
)
self.assertIsNotNone(wf_ex)
self.assertEqual(states.RUNNING, wf_ex.state)
self._assert_dict_contains_subset(wf_input, wf_ex.context)
self.assertIn('__execution', wf_ex.context)
# Note: We need to reread execution to access related tasks.
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertEqual(1, len(wf_ex.task_executions))
task_ex = wf_ex.task_executions[0]
self.assertEqual('wb.wf', task_ex.workflow_name)
self.assertEqual('task1', task_ex.name)
self.assertEqual(states.RUNNING, task_ex.state)
self.assertIsNotNone(task_ex.spec)
self.assertDictEqual({}, task_ex.runtime_context)
# Data Flow properties.
self._assert_dict_contains_subset(wf_input, task_ex.in_context)
self.assertIn('__execution', task_ex.in_context)
action_execs = db_api.get_action_executions(
task_execution_id=task_ex.id
)
self.assertEqual(1, len(action_execs))
task_action_ex = action_execs[0]
self.assertIsNotNone(task_action_ex)
self.assertDictEqual({'output': 'value1'}, task_action_ex.input)
def test_start_workflow_with_adhoc_env(self):
wf_input = {
'param1': '<% env().key1 %>',
'param2': '<% env().key2 %>'
}
env = ENVIRONMENT['variables']
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf',
wf_input,
env=env,
task_name='task2')
self.assertIsNotNone(wf_ex)
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertDictEqual(wf_ex.params.get('env', {}), env)
@mock.patch.object(db_api, "get_environment", MOCK_ENVIRONMENT)
def test_start_workflow_with_saved_env(self):
wf_input = {
'param1': '<% env().key1 %>',
'param2': '<% env().key2 %>'
}
env = ENVIRONMENT['variables']
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf',
wf_input,
env='test',
task_name='task2')
self.assertIsNotNone(wf_ex)
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertDictEqual(wf_ex.params.get('env', {}), env)
@mock.patch.object(db_api, "get_environment", MOCK_NOT_FOUND)
def test_start_workflow_env_not_found(self):
self.assertRaises(exc.NotFoundException,
self.engine.start_workflow,
'wb.wf',
{'param1': '<% env().key1 %>'},
env='foo',
task_name='task2')
def test_start_workflow_with_env_type_error(self):
self.assertRaises(ValueError,
self.engine.start_workflow,
'wb.wf',
{'param1': '<% env().key1 %>'},
env=True,
task_name='task2')
def test_start_workflow_missing_parameters(self):
self.assertRaises(
exc.InputException,
self.engine.start_workflow,
'wb.wf',
None,
task_name='task2'
)
def test_start_workflow_unexpected_parameters(self):
self.assertRaises(
exc.InputException,
self.engine.start_workflow,
'wb.wf',
{'param1': 'Hey', 'param2': 'Hi', 'unexpected_param': 'val'},
task_name='task2'
)
def test_on_action_complete(self):
wf_input = {'param1': 'Hey', 'param2': 'Hi'}
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf',
wf_input,
task_name='task2'
)
self.assertIsNotNone(wf_ex)
self.assertEqual(states.RUNNING, wf_ex.state)
# Note: We need to reread execution to access related tasks.
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertEqual(1, len(wf_ex.task_executions))
task1_ex = wf_ex.task_executions[0]
self.assertEqual('task1', task1_ex.name)
self.assertEqual(states.RUNNING, task1_ex.state)
self.assertIsNotNone(task1_ex.spec)
self.assertDictEqual({}, task1_ex.runtime_context)
self._assert_dict_contains_subset(wf_input, task1_ex.in_context)
self.assertIn('__execution', task1_ex.in_context)
action_execs = db_api.get_action_executions(
task_execution_id=task1_ex.id
)
self.assertEqual(1, len(action_execs))
task1_action_ex = action_execs[0]
self.assertIsNotNone(task1_action_ex)
self.assertDictEqual({'output': 'Hey'}, task1_action_ex.input)
# Finish action of 'task1'.
task1_action_ex = self.engine.on_action_complete(
task1_action_ex.id,
wf_utils.Result(data='Hey')
)
self.assertIsInstance(task1_action_ex, models.ActionExecution)
self.assertEqual('std.echo', task1_action_ex.name)
self.assertEqual(states.SUCCESS, task1_action_ex.state)
# Data Flow properties.
task1_ex = db_api.get_task_execution(task1_ex.id) # Re-read the state.
self._assert_dict_contains_subset(wf_input, task1_ex.in_context)
self.assertIn('__execution', task1_ex.in_context)
self.assertDictEqual({'var': 'Hey'}, task1_ex.published)
self.assertDictEqual({'output': 'Hey'}, task1_action_ex.input)
self.assertDictEqual({'result': 'Hey'}, task1_action_ex.output)
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertIsNotNone(wf_ex)
self.assertEqual(states.RUNNING, wf_ex.state)
self.assertEqual(2, len(wf_ex.task_executions))
task2_ex = self._assert_single_item(
wf_ex.task_executions,
name='task2'
)
self.assertEqual(states.RUNNING, task2_ex.state)
action_execs = db_api.get_action_executions(
task_execution_id=task2_ex.id
)
self.assertEqual(1, len(action_execs))
task2_action_ex = action_execs[0]
self.assertIsNotNone(task2_action_ex)
self.assertDictEqual({'output': 'Hi'}, task2_action_ex.input)
# Finish 'task2'.
task2_action_ex = self.engine.on_action_complete(
task2_action_ex.id,
wf_utils.Result(data='Hi')
)
wf_ex = db_api.get_workflow_execution(wf_ex.id)
self.assertIsNotNone(wf_ex)
self.assertEqual(states.SUCCESS, wf_ex.state)
self.assertIsInstance(task2_action_ex, models.ActionExecution)
self.assertEqual('std.echo', task2_action_ex.name)
self.assertEqual(states.SUCCESS, task2_action_ex.state)
# Data Flow properties.
self.assertIn('__tasks', task2_ex.in_context)
self.assertIn('__execution', task1_ex.in_context)
self.assertDictEqual({'output': 'Hi'}, task2_action_ex.input)
self.assertDictEqual({}, task2_ex.published)
self.assertDictEqual({'output': 'Hi'}, task2_action_ex.input)
self.assertDictEqual({'result': 'Hi'}, task2_action_ex.output)
self.assertEqual(2, len(wf_ex.task_executions))
self._assert_single_item(wf_ex.task_executions, name='task1')
self._assert_single_item(wf_ex.task_executions, name='task2')
def test_stop_workflow_fail(self):
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf', {'param1': 'Hey', 'param2': 'Hi'}, task_name="task2")
# Re-read execution to access related tasks.
wf_ex = db_api.get_execution(wf_ex.id)
self.engine.stop_workflow(wf_ex.id, 'ERROR', "Stop this!")
# Re-read from DB again
wf_ex = db_api.get_execution(wf_ex.id)
self.assertEqual('ERROR', wf_ex.state)
self.assertEqual("Stop this!", wf_ex.state_info)
def test_stop_workflow_succeed(self):
# Start workflow.
wf_ex = self.engine.start_workflow(
'wb.wf', {'param1': 'Hey', 'param2': 'Hi'}, task_name="task2")
# Re-read execution to access related tasks.
wf_ex = db_api.get_execution(wf_ex.id)
self.engine.stop_workflow(wf_ex.id, 'SUCCESS', "Like this, done")
# Re-read from DB again
wf_ex = db_api.get_execution(wf_ex.id)
self.assertEqual('SUCCESS', wf_ex.state)
self.assertEqual("Like this, done", wf_ex.state_info)
def test_stop_workflow_bad_status(self):
wf_ex = self.engine.start_workflow(
'wb.wf', {'param1': 'Hey', 'param2': 'Hi'}, task_name="task2")
# Re-read execution to access related tasks.
wf_ex = db_api.get_execution(wf_ex.id)
self.assertNotEqual(
'PAUSE',
self.engine.stop_workflow(wf_ex.id, 'PAUSE')
)
def test_resume_workflow(self):
# TODO(akhmerov): Implement.
pass
class DefaultEngineWithTransportTest(eng_test_base.EngineTestCase):
def test_engine_client_remote_error(self):
mocked = mock.Mock()
mocked.call.side_effect = rpc_client.RemoteError(
'InputException',
'Input is wrong'
)
self.engine_client._client = mocked
self.assertRaises(
exc.InputException,
self.engine_client.start_workflow,
'some_wf',
{},
'some_description'
)
| apache-2.0 |
alexus37/AugmentedRealityChess | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/text/wglfontprovider.py | 2 | 1419 | """Win32 (win32ui and WGL)-specific font providers
"""
from OpenGLContext.scenegraph.text import fontprovider, wglfont
class WGLOutlineFonts( fontprovider.FontProvider ):
"""Font provider for WGL outline (polygon) fonts"""
format = "polygon"
def get( self, fontStyle, mode=None ):
"""Get a WGLOutlineFont object for the given fontStyle
Basically this object will be able to generate
character display-lists for use in displaying
the given font, and will also include
information for formatting larger paragraphs
or the like according to the font metrics.
"""
return wglfont.WGLOutlineFont(
fontStyle = fontStyle,
)
fontprovider.FontProvider.registerProvider( WGLOutlineFonts() )
class WGLBitmapFonts( fontprovider.FontProvider ):
"""Font provider for WGL bitmap fonts"""
format = "bitmap"
def get( self, fontStyle, mode=None ):
"""Get a WGLBitmapFont object for the given fontStyle
Basically this object will be able to generate
character display-lists for use in displaying
the given font, and will also include
information for formatting larger paragraphs
or the like according to the font metrics.
"""
return wglfont.WGLBitmapFont(
fontStyle = fontStyle,
)
fontprovider.FontProvider.registerProvider( WGLBitmapFonts() )
| mit |
ntts-clo/ryu | ryu/services/protocols/vrrp/monitor_openflow.py | 56 | 5444 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ryu.controller import handler
from ryu.controller import ofp_event
from ryu.lib import dpid as dpid_lib
from ryu.lib.packet import vrrp
from ryu.ofproto import ether
from ryu.ofproto import inet
from ryu.ofproto import ofproto_v1_2
from ryu.ofproto import ofproto_v1_3
from ryu.services.protocols.vrrp import monitor
from ryu.services.protocols.vrrp import event as vrrp_event
from ryu.services.protocols.vrrp import utils
@monitor.VRRPInterfaceMonitor.register(vrrp_event.VRRPInterfaceOpenFlow)
class VRRPInterfaceMonitorOpenFlow(monitor.VRRPInterfaceMonitor):
# OF1.2
OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION,
ofproto_v1_3.OFP_VERSION] # probably work with OF1.3
_TABLE = 0 # generate packet-in in this table
_PRIORITY = 0x8000 # default priority
def __init__(self, *args, **kwargs):
super(VRRPInterfaceMonitorOpenFlow, self).__init__(*args, **kwargs)
table = kwargs.get('vrrp_imof_table', None)
if table is not None:
self._TABLE = int(table)
priority = kwargs.get('vrrp_imof_priority', None)
if priority is not None:
self._PRIORITY = int(priority)
@handler.set_ev_cls(ofp_event.EventOFPPacketIn, handler.MAIN_DISPATCHER)
def packet_in_handler(self, ev):
self.logger.debug('packet_in_handler')
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
# TODO: subscribe only the designated datapath
dpid = datapath.id
if dpid != self.interface.dpid:
self.logger.debug('packet_in_handler dpid %s %s',
dpid_lib.dpid_to_str(dpid),
dpid_lib.dpid_to_str(self.interface.dpid))
return
in_port = None
for field in msg.match.fields:
if field.header == ofproto.OXM_OF_IN_PORT:
in_port = field.value
break
if in_port != self.interface.port_no:
self.logger.debug('packet_in_handler in_port %s %s',
in_port, self.interface.port_no)
return
self._send_vrrp_packet_received(msg.data)
def _get_dp(self):
return utils.get_dp(self, self.interface.dpid)
@handler.set_ev_handler(vrrp_event.EventVRRPTransmitRequest)
def vrrp_transmit_request_handler(self, ev):
dp = self._get_dp()
if not dp:
return
utils.dp_packet_out(dp, self.interface.port_no, ev.data)
def _ofp_match(self, ofproto_parser):
is_ipv6 = vrrp.is_ipv6(self.config.ip_addresses[0])
kwargs = {}
kwargs['in_port'] = self.interface.port_no
if is_ipv6:
kwargs['eth_dst'] = vrrp.VRRP_IPV6_DST_MAC_ADDRESS
kwargs['eth_src'] = \
vrrp.vrrp_ipv6_src_mac_address(self.config.vrid)
kwargs['eth_type'] = ether.ETH_TYPE_IPV6
kwargs['ipv6_dst'] = vrrp.VRRP_IPV6_DST_ADDRESS
else:
kwargs['eth_dst'] = vrrp.VRRP_IPV4_DST_MAC_ADDRESS
kwargs['eth_src'] = \
vrrp.vrrp_ipv4_src_mac_address(self.config.vrid)
kwargs['eth_type'] = ether.ETH_TYPE_IP
kwargs['ipv4_dst'] = vrrp.VRRP_IPV4_DST_ADDRESS
if self.interface.vlan_id is not None:
kwargs['vlan_vid'] = self.interface.vlan_id
kwargs['ip_proto'] = inet.IPPROTO_VRRP
# OF1.2 doesn't support TTL match.
# It needs to be checked by packet in handler
return ofproto_parser.OFPMatch(**kwargs)
def _initialize(self):
dp = self._get_dp()
if not dp:
return
ofproto = dp.ofproto
ofproto_parser = dp.ofproto_parser
match = self._ofp_match(ofproto_parser)
utils.dp_flow_mod(dp, self._TABLE, ofproto.OFPFC_DELETE_STRICT,
self._PRIORITY, match, [],
out_port=ofproto.OFPP_CONTROLLER)
match = self._ofp_match(ofproto_parser)
actions = [ofproto_parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
instructions = [ofproto_parser.OFPInstructionActions(
ofproto.OFPIT_APPLY_ACTIONS, actions)]
utils.dp_flow_mod(dp, self._TABLE, ofproto.OFPFC_ADD, self._PRIORITY,
match, instructions)
def _shutdown(self):
dp = self._get_dp()
if not dp:
return
ofproto = dp.ofproto
match = self._ofp_match(dp.ofproto_parser)
utils.dp_flow_mod(dp, self._TABLE, ofproto.OFPFC_DELETE_STRICT,
self._PRIORITY, match, [],
out_port=ofproto.OFPP_CONTROLLER)
| apache-2.0 |
CAB-LAB/cablab-core | test/providers/test_precip.py | 2 | 3183 | import os
import unittest
from datetime import datetime
from esdl import CubeConfig
from esdl.providers.precip import PrecipProvider
from test.providers.provider_test_utils import ProviderTestBase
from esdl.util import Config
SOURCE_DIR = Config.instance().get_cube_source_path('CPC_precip')
class PrecipProviderTest(ProviderTestBase):
@unittest.skipIf(not os.path.exists(SOURCE_DIR), 'test data not found: ' + SOURCE_DIR)
def test_source_time_ranges(self):
provider = PrecipProvider(CubeConfig(), dir=SOURCE_DIR)
provider.prepare()
source_time_ranges = provider.source_time_ranges
self.assertEqual(13149, len(source_time_ranges))
self.assert_source_time_ranges(source_time_ranges[0],
datetime(1979, 1, 1, 0, 0, 0, 33),
datetime(1979, 1, 2, 0, 0, 0, 33),
self.get_source_dir_list(SOURCE_DIR) + ['Precip.V1.720.360.1979.nc.gz'],
0)
self.assert_source_time_ranges(source_time_ranges[6],
datetime(1979, 1, 7, 0, 0, 0, 33),
datetime(1979, 1, 8, 0, 0, 0, 33),
self.get_source_dir_list(SOURCE_DIR) + ['Precip.V1.720.360.1979.nc.gz'],
6)
self.assert_source_time_ranges(source_time_ranges[13148],
datetime(2014, 12, 31, 0, 0, 0, 33),
datetime(2015, 1, 1, 0, 0, 0, 33),
self.get_source_dir_list(SOURCE_DIR) + ['Precip.RT.720.360.2014.nc.gz'],
364)
@unittest.skipIf(not os.path.exists(SOURCE_DIR), 'test data not found: ' + SOURCE_DIR)
def test_temporal_coverage(self):
provider = PrecipProvider(CubeConfig(), dir=SOURCE_DIR)
provider.prepare()
self.assertEqual((datetime(1979, 1, 1, 0, 0, 0, 33), datetime(2015, 1, 1, 0, 0, 0, 33)),
provider.temporal_coverage)
@unittest.skipIf(not os.path.exists(SOURCE_DIR), 'test data not found: ' + SOURCE_DIR)
def test_get_images(self):
provider = PrecipProvider(CubeConfig(), dir=SOURCE_DIR)
provider.prepare()
images = provider.compute_variable_images(datetime(1996, 1, 1), datetime(1996, 1, 9))
self.assertIsNotNone(images)
self.assertTrue('precipitation' in images)
image = images['precipitation']
self.assertEqual((720, 1440), image.shape)
@unittest.skipIf(not os.path.exists(SOURCE_DIR), 'test data not found: ' + SOURCE_DIR)
def test_get_high_res_images(self):
provider = PrecipProvider(CubeConfig(grid_width=4320, grid_height=2160, spatial_res=1 / 12), dir=SOURCE_DIR)
provider.prepare()
images = provider.compute_variable_images(datetime(1996, 1, 1), datetime(1996, 1, 9))
self.assertIsNotNone(images)
self.assertTrue('precipitation' in images)
image = images['precipitation']
self.assertEqual((2160, 4320), image.shape)
| gpl-3.0 |
caveman-dick/ansible | test/units/contrib/inventory/test_vmware_inventory.py | 97 | 3635 | import json
import os
import pickle
import unittest
import sys
from nose.plugins.skip import SkipTest
try:
from pyVmomi import vim, vmodl
except ImportError:
raise SkipTest("test_vmware_inventory.py requires the python module 'pyVmomi'")
try:
from vmware_inventory import VMWareInventory
except ImportError:
raise SkipTest("test_vmware_inventory.py requires the python module 'vmware_inventory'")
# contrib's dirstruct doesn't contain __init__.py files
checkout_path = os.path.dirname(__file__)
checkout_path = checkout_path.replace('/test/units/contrib/inventory', '')
inventory_dir = os.path.join(checkout_path, 'contrib', 'inventory')
sys.path.append(os.path.abspath(inventory_dir))
# cleanup so that nose's path is not polluted with other inv scripts
sys.path.remove(os.path.abspath(inventory_dir))
BASICINVENTORY = {
'all': {
'hosts': ['foo', 'bar']
},
'_meta': {
'hostvars': {
'foo': {'hostname': 'foo'},
'bar': {'hostname': 'bar'}
}
}
}
class FakeArgs(object):
debug = False
write_dumpfile = None
load_dumpfile = None
host = False
list = True
class TestVMWareInventory(unittest.TestCase):
def test_host_info_returns_single_host(self):
vmw = VMWareInventory(load=False)
vmw.inventory = BASICINVENTORY
foo = vmw.get_host_info('foo')
bar = vmw.get_host_info('bar')
assert foo == {'hostname': 'foo'}
assert bar == {'hostname': 'bar'}
def test_show_returns_serializable_data(self):
fakeargs = FakeArgs()
vmw = VMWareInventory(load=False)
vmw.args = fakeargs
vmw.inventory = BASICINVENTORY
showdata = vmw.show()
serializable = False
try:
json.loads(showdata)
serializable = True
except:
pass
assert serializable
# import epdb; epdb.st()
def test_show_list_returns_serializable_data(self):
fakeargs = FakeArgs()
vmw = VMWareInventory(load=False)
vmw.args = fakeargs
vmw.args.list = True
vmw.inventory = BASICINVENTORY
showdata = vmw.show()
serializable = False
try:
json.loads(showdata)
serializable = True
except:
pass
assert serializable
# import epdb; epdb.st()
def test_show_list_returns_all_data(self):
fakeargs = FakeArgs()
vmw = VMWareInventory(load=False)
vmw.args = fakeargs
vmw.args.list = True
vmw.inventory = BASICINVENTORY
showdata = vmw.show()
expected = json.dumps(BASICINVENTORY, indent=2)
assert showdata == expected
def test_show_host_returns_serializable_data(self):
fakeargs = FakeArgs()
vmw = VMWareInventory(load=False)
vmw.args = fakeargs
vmw.args.host = 'foo'
vmw.inventory = BASICINVENTORY
showdata = vmw.show()
serializable = False
try:
json.loads(showdata)
serializable = True
except:
pass
assert serializable
# import epdb; epdb.st()
def test_show_host_returns_just_host(self):
fakeargs = FakeArgs()
vmw = VMWareInventory(load=False)
vmw.args = fakeargs
vmw.args.list = False
vmw.args.host = 'foo'
vmw.inventory = BASICINVENTORY
showdata = vmw.show()
expected = BASICINVENTORY['_meta']['hostvars']['foo']
expected = json.dumps(expected, indent=2)
# import epdb; epdb.st()
assert showdata == expected
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.