repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
rwillmer/django
tests/template_backends/test_utils.py
351
1521
from django.core.exceptions import ImproperlyConfigured from django.template import engines from django.test import SimpleTestCase, override_settings class TemplateStringsTests(SimpleTestCase): @override_settings(TEMPLATES=[{ 'BACKEND': 'raise.import.error', }]) def test_backend_import_error(self): """ Failing to import a backend keeps raising the original import error. Regression test for #24265. """ with self.assertRaises(ImportError): engines.all() with self.assertRaises(ImportError): engines.all() @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Incorrect: APP_DIRS and loaders are mutually incompatible. 'APP_DIRS': True, 'OPTIONS': {'loaders': []}, }]) def test_backend_improperly_configured(self): """ Failing to initialize a backend keeps raising the original exception. Regression test for #24265. """ with self.assertRaises(ImproperlyConfigured): engines.all() with self.assertRaises(ImproperlyConfigured): engines.all() @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_backend_names_must_be_unique(self): with self.assertRaises(ImproperlyConfigured): engines.all()
bsd-3-clause
gselva/thumbor
thumbor/filters/redeye.py
14
4771
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from os.path import abspath, dirname, join import cv from thumbor.filters import BaseFilter, filter_method FACE_ORIGIN = 'Face Detection' CASCADE_FILE_PATH = abspath(join(dirname(__file__), 'haarcascade_eye.xml')) MIN_SIZE = (20, 20) HAAR_SCALE = 1.2 MIN_NEIGHBORS = 3 HAAR_FLAGS = 0 RED_THRESHOLD = 2.0 class Filter(BaseFilter): def get_pixels(self, image, w, h, mode): pixels = [] for row in range(h): for col in range(w): pixel = cv.Get2D(image, row, col) pixels.append({ 'x': col, 'y': row, 'r': pixel[mode.index('r')], 'g': pixel[mode.index('g')], 'b': pixel[mode.index('b')] }) return pixels def filter_eyes(self, eyes): intersected_eyes = [] for eye in eyes: #if eye in intersected_eyes: continue (x, y, w, h), other = eye for eye2 in eyes: (x2, y2, w2, h2), other2 = eye2 if x == x2 and w == w2 and y == y2 and h == h2: continue #if eye2 in intersected_eyes: continue if (y2 >= y and y2 + h2 <= y + h) or (y2 + h2 >= y and y2 <= y + h): intersected_eyes.append(eye) #intersected_eyes.append(eye2) return intersected_eyes @filter_method() def red_eye(self): self.load_cascade_file() faces = [face for face in self.context.request.focal_points if face.origin == 'Face Detection'] if faces: engine = self.context.modules.engine mode, data = engine.image_data_as_rgb() mode = mode.lower() sz = engine.size image = cv.CreateImageHeader(sz, cv.IPL_DEPTH_8U, 3) cv.SetData(image, data) for face in faces: face_x = int(face.x - face.width / 2) face_y = int(face.y - face.height / 2) face_roi = ( int(face_x), int(face_y), int(face.width), int(face.height) ) cv.SetImageROI(image, face_roi) eyes = cv.HaarDetectObjects( image, self.cascade, cv.CreateMemStorage(0), HAAR_SCALE, MIN_NEIGHBORS, HAAR_FLAGS, MIN_SIZE) for (x, y, w, h), other in self.filter_eyes(eyes): # Set the image Region of interest to be the eye area [this reduces processing time] cv.SetImageROI(image, (face_x + x, face_y + y, w, h)) if self.context.request.debug: cv.Rectangle( image, (0, 0), (w, h), cv.RGB(255, 255, 255), 2, 8, 0 ) for pixel in self.get_pixels(image, w, h, mode): green_blue_avg = (pixel['g'] + pixel['b']) / 2 if not green_blue_avg: red_intensity = RED_THRESHOLD else: # Calculate the intensity compared to blue and green average red_intensity = pixel['r'] / green_blue_avg # If the red intensity is greater than 2.0, lower the value if red_intensity >= RED_THRESHOLD: new_red_value = (pixel['g'] + pixel['b']) / 2 # Insert the new red value for the pixel to the image cv.Set2D( image, pixel['y'], pixel['x'], cv.RGB(new_red_value, pixel['g'], pixel['b']) ) # Reset the image region of interest back to full image cv.ResetImageROI(image) self.context.modules.engine.set_image_data(image.tostring()) def load_cascade_file(self): if not hasattr(self.__class__, 'cascade'): setattr(self.__class__, 'cascade', cv.Load(CASCADE_FILE_PATH))
mit
a16/gobgp
test/scenario_test/ibgp_router_test.py
2
10745
# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation. # # 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 __future__ import absolute_import from itertools import combinations import sys import time import unittest from fabric.api import local import nose from lib.noseplugin import OptionParser, parser_option from lib import base from lib.base import ( BGP_FSM_IDLE, BGP_FSM_ESTABLISHED, ) from lib.base import wait_for_completion from lib.gobgp import GoBGPContainer from lib.quagga import QuaggaBGPContainer class GoBGPTestBase(unittest.TestCase): @classmethod def setUpClass(cls): gobgp_ctn_image_name = parser_option.gobgp_image base.TEST_PREFIX = parser_option.test_prefix g1 = GoBGPContainer(name='g1', asn=65000, router_id='192.168.0.1', ctn_image_name=gobgp_ctn_image_name, log_level=parser_option.gobgp_log_level) q1 = QuaggaBGPContainer(name='q1', asn=65000, router_id='192.168.0.2') q2 = QuaggaBGPContainer(name='q2', asn=65000, router_id='192.168.0.3') qs = [q1, q2] ctns = [g1, q1, q2] initial_wait_time = max(ctn.run() for ctn in ctns) time.sleep(initial_wait_time) # ibgp peer. loop topology for a, b in combinations(ctns, 2): a.add_peer(b) b.add_peer(a) # advertise a route from q1, q2 for idx, c in enumerate(qs): route = '10.0.{0}.0/24'.format(idx + 1) c.add_route(route) cls.gobgp = g1 cls.quaggas = {'q1': q1, 'q2': q2} # test each neighbor state is turned establish def test_01_neighbor_established(self): for q in self.quaggas.itervalues(): self.gobgp.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=q) def test_02_check_gobgp_global_rib(self): for q in self.quaggas.itervalues(): # paths expected to exist in gobgp's global rib routes = q.routes.keys() timeout = 120 interval = 1 count = 0 while True: # gobgp's global rib state = self.gobgp.get_neighbor_state(q) self.assertEqual(state, BGP_FSM_ESTABLISHED) global_rib = [p['prefix'] for p in self.gobgp.get_global_rib()] for p in global_rib: if p in routes: routes.remove(p) if len(routes) == 0: break time.sleep(interval) count += interval if count >= timeout: raise Exception('timeout') def test_03_check_gobgp_adj_rib_out(self): for q in self.quaggas.itervalues(): paths = self.gobgp.get_adj_rib_out(q) # bgp speaker mustn't forward iBGP routes to iBGP peers self.assertEqual(len(paths), 0) def test_04_originate_path(self): self.gobgp.add_route('10.10.0.0/24') dst = self.gobgp.get_global_rib('10.10.0.0/24') self.assertEqual(len(dst), 1) self.assertEqual(len(dst[0]['paths']), 1) path = dst[0]['paths'][0] self.assertEqual(path['nexthop'], '0.0.0.0') self.assertEqual(len(path['aspath']), 0) def test_05_check_gobgp_adj_rib_out(self): for q in self.quaggas.itervalues(): paths = self.gobgp.get_adj_rib_out(q) self.assertEqual(len(paths), len(self.gobgp.routes)) path = paths[0] self.assertEqual(path['nlri']['prefix'], '10.10.0.0/24') peer_info = self.gobgp.peers[q] local_addr = peer_info['local_addr'].split('/')[0] self.assertEqual(path['nexthop'], local_addr) self.assertEqual(len(path['aspath']), 0) # check routes are properly advertised to all BGP speaker def test_06_check_quagga_global_rib(self): interval = 1 timeout = int(120 / interval) for q in self.quaggas.itervalues(): done = False for _ in range(timeout): if done: break global_rib = q.get_global_rib() # quagga's global_rib must have two routes at least, # a self-generated route and a gobgp-generated route if len(global_rib) < len(q.routes) + len(self.gobgp.routes): time.sleep(interval) continue peer_info = self.gobgp.peers[q] local_addr = peer_info['local_addr'].split('/')[0] for r in self.gobgp.routes: self.assertTrue(r in (p['prefix'] for p in global_rib)) for rr in global_rib: if rr['prefix'] == r: self.assertEqual(rr['nexthop'], local_addr) for r in q.routes.keys(): self.assertTrue(r in (p['prefix'] for p in global_rib)) for rr in global_rib: if rr['prefix'] == r: self.assertEqual(rr['nexthop'], '0.0.0.0') done = True if done: continue # should not reach here raise AssertionError def test_07_add_ebgp_peer(self): q3 = QuaggaBGPContainer(name='q3', asn=65001, router_id='192.168.0.4') self.quaggas['q3'] = q3 initial_wait_time = q3.run() time.sleep(initial_wait_time) self.gobgp.add_peer(q3) q3.add_peer(self.gobgp) q3.add_route('10.0.3.0/24') self.gobgp.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=q3) def test_08_check_global_rib(self): self.test_02_check_gobgp_global_rib() def test_09_check_gobgp_ebgp_adj_rib_out(self): q1 = self.quaggas['q1'] q2 = self.quaggas['q2'] q3 = self.quaggas['q3'] paths = self.gobgp.get_adj_rib_out(q3) total_len = len(q1.routes) + len(q2.routes) + len(self.gobgp.routes) assert len(paths) == total_len for path in paths: peer_info = self.gobgp.peers[q3] local_addr = peer_info['local_addr'].split('/')[0] self.assertEqual(path['nexthop'], local_addr) self.assertEqual(path['aspath'], [self.gobgp.asn]) def test_10_check_gobgp_ibgp_adj_rib_out(self): q1 = self.quaggas['q1'] q3 = self.quaggas['q3'] peer_info = self.gobgp.peers[q3] neigh_addr = peer_info['neigh_addr'].split('/')[0] for prefix in q3.routes.iterkeys(): paths = self.gobgp.get_adj_rib_out(q1, prefix) self.assertEqual(len(paths), 1) path = paths[0] # bgp router mustn't change nexthop of routes from eBGP peers # which are sent to iBGP peers self.assertEqual(path['nexthop'], neigh_addr) # bgp router mustn't change aspath of routes from eBGP peers # which are sent to iBGP peers self.assertEqual(path['aspath'], [q3.asn]) # disable ebgp peer, check ebgp routes are removed def test_11_disable_ebgp_peer(self): q3 = self.quaggas['q3'] self.gobgp.disable_peer(q3) del self.quaggas['q3'] self.gobgp.wait_for(expected_state=BGP_FSM_IDLE, peer=q3) for route in q3.routes.iterkeys(): dst = self.gobgp.get_global_rib(route) self.assertEqual(len(dst), 0) for q in self.quaggas.itervalues(): paths = self.gobgp.get_adj_rib_out(q) # only gobgp's locally generated routes must exists print paths self.assertEqual(len(paths), len(self.gobgp.routes)) def test_12_disable_ibgp_peer(self): q1 = self.quaggas['q1'] self.gobgp.disable_peer(q1) self.gobgp.wait_for(expected_state=BGP_FSM_IDLE, peer=q1) for route in q1.routes.iterkeys(): dst = self.gobgp.get_global_rib(route) self.assertEqual(len(dst), 0) def test_13_enable_ibgp_peer(self): q1 = self.quaggas['q1'] self.gobgp.enable_peer(q1) self.gobgp.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=q1) def test_14_check_gobgp_adj_rib_out(self): for q in self.quaggas.itervalues(): paths = self.gobgp.get_adj_rib_out(q) # only gobgp's locally generated routes must exists self.assertEqual(len(paths), len(self.gobgp.routes)) def test_15_add_ebgp_peer(self): q4 = QuaggaBGPContainer(name='q4', asn=65001, router_id='192.168.0.5') self.quaggas['q4'] = q4 initial_wait_time = q4.run() time.sleep(initial_wait_time) self.gobgp.add_peer(q4) q4.add_peer(self.gobgp) prefix = '10.0.4.0/24' q4.add_route(prefix) self.gobgp.wait_for(expected_state=BGP_FSM_ESTABLISHED, peer=q4) q1 = self.quaggas['q1'] q2 = self.quaggas['q2'] for q in [q1, q2]: def _f(): return prefix in [p['nlri']['prefix'] for p in self.gobgp.get_adj_rib_out(q)] wait_for_completion(_f) def f(): return len(q2.get_global_rib(prefix)) == 1 wait_for_completion(f) def test_16_add_best_path_from_ibgp(self): q1 = self.quaggas['q1'] q2 = self.quaggas['q2'] prefix = '10.0.4.0/24' q1.add_route(prefix) def f1(): l = self.gobgp.get_global_rib(prefix) return len(l) == 1 and len(l[0]['paths']) == 2 wait_for_completion(f1) def f2(): return prefix not in [p['nlri']['prefix'] for p in self.gobgp.get_adj_rib_out(q2)] wait_for_completion(f2) def f3(): l = q2.get_global_rib(prefix) # route from ibgp so aspath should be empty return len(l) == 1 and len(l[0]['aspath']) == 0 wait_for_completion(f3) if __name__ == '__main__': output = local("which docker 2>&1 > /dev/null ; echo $?", capture=True) if int(output) is not 0: print "docker not found" sys.exit(1) nose.main(argv=sys.argv, addplugins=[OptionParser()], defaultTest=sys.argv[0])
apache-2.0
hlmnrmr/superdesk-core
superdesk/io/feed_parsers/afp_newsml_1_2.py
7
1201
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from superdesk.io.feed_parsers.newsml_1_2 import NewsMLOneFeedParser from superdesk.io.registry import register_feed_parser from superdesk.utc import utcnow from pytz import utc class AFPNewsMLOneFeedParser(NewsMLOneFeedParser): """AFP specific NewsML parser. Feed Parser which can parse the AFP feed basically it is in NewsML 1.2 format, but the firstcreated and versioncreated times are localised. """ NAME = 'afpnewsml12' label = 'AFP News ML 1.2 Parser' def parse(self, xml, provider=None): item = super().parse(xml, provider) item['firstcreated'] = utc.localize(item['firstcreated']) if item.get('firstcreated') else utcnow() item['versioncreated'] = utc.localize(item['versioncreated']) if item.get('versioncreated') else utcnow() return item register_feed_parser(AFPNewsMLOneFeedParser.NAME, AFPNewsMLOneFeedParser())
agpl-3.0
zsiciarz/django
django/db/models/fields/reverse_related.py
11
9882
""" "Rel objects" for related fields. "Rel objects" (for lack of a better name) carry information about the relation modeled by a related field and provide some utility functions. They're stored in the ``remote_field`` attribute of the field. They also act as reverse fields for the purposes of the Meta API because they're the closest concept currently available. """ from django.core import exceptions from django.utils.encoding import force_text from django.utils.functional import cached_property from . import BLANK_CHOICE_DASH class ForeignObjectRel: """ Used by ForeignObject to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ # Field flags auto_created = True concrete = False editable = False is_relation = True # Reverse relations are always nullable (Django can't enforce that a # foreign key on the related model points to this model). null = True def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None): self.field = field self.model = to self.related_name = related_name self.related_query_name = related_query_name self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to self.parent_link = parent_link self.on_delete = on_delete self.symmetrical = False self.multiple = True # Some of the following cached_properties can't be initialized in # __init__ as the field doesn't have its model yet. Calling these methods # before field.contribute_to_class() has been called will result in # AttributeError @cached_property def hidden(self): return self.is_hidden() @cached_property def name(self): return self.field.related_query_name() @property def remote_field(self): return self.field @property def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.get_path_info()[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError("Can't use target_field for multicolumn relations.") return target_fields[0] @cached_property def related_model(self): if not self.field.model: raise AttributeError( "This property can't be accessed before self.field.contribute_to_class has been called.") return self.field.model @cached_property def many_to_many(self): return self.field.many_to_many @cached_property def many_to_one(self): return self.field.one_to_many @cached_property def one_to_many(self): return self.field.many_to_one @cached_property def one_to_one(self): return self.field.one_to_one def get_lookup(self, lookup_name): return self.field.get_lookup(lookup_name) def get_internal_type(self): return self.field.get_internal_type() @property def db_type(self): return self.field.db_type def __repr__(self): return '<%s: %s.%s>' % ( type(self).__name__, self.related_model._meta.app_label, self.related_model._meta.model_name, ) def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): """ Return choices with a default blank choices included, for use as <select> choices for this field. Analog of django.db.models.fields.Field.get_choices(), provided initially for utilization by RelatedFieldListFilter. """ return (blank_choice if include_blank else []) + [ (x._get_pk_val(), force_text(x)) for x in self.related_model._default_manager.all() ] def is_hidden(self): """Should the related object be hidden?""" return bool(self.related_name) and self.related_name[-1] == '+' def get_joining_columns(self): return self.field.get_reverse_joining_columns() def get_extra_restriction(self, where_class, alias, related_alias): return self.field.get_extra_restriction(where_class, related_alias, alias) def set_field_name(self): """ Set the related field's name, this is not available until later stages of app loading, so set_field_name is called from set_attributes_from_rel() """ # By default foreign object doesn't relate to any remote field (for # example custom multicolumn joins currently have no remote field). self.field_name = None def get_accessor_name(self, model=None): # This method encapsulates the logic that decides what name to give an # accessor descriptor that retrieves related many-to-one or # many-to-many objects. It uses the lower-cased object_name + "_set", # but this can be overridden with the "related_name" option. # Due to backwards compatibility ModelForms need to be able to provide # an alternate model. See BaseInlineFormSet.get_default_prefix(). opts = model._meta if model else self.related_model._meta model = model or self.related_model if self.multiple: # If this is a symmetrical m2m relation on self, there is no reverse accessor. if self.symmetrical and model == self.model: return None if self.related_name: return self.related_name return opts.model_name + ('_set' if self.multiple else '') def get_cache_name(self): return "_%s_cache" % self.get_accessor_name() def get_path_info(self): return self.field.get_reverse_path_info() class ManyToOneRel(ForeignObjectRel): """ Used by the ForeignKey field to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. Note: Because we somewhat abuse the Rel objects by using them as reverse fields we get the funny situation where ``ManyToOneRel.many_to_one == False`` and ``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual ManyToOneRel class is a private API and there is work underway to turn reverse relations into actual fields. """ def __init__(self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None): super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) self.field_name = field_name def __getstate__(self): state = self.__dict__.copy() state.pop('related_model', None) return state def get_related_field(self): """ Return the Field in the 'to' object to which this relationship is tied. """ field = self.model._meta.get_field(self.field_name) if not field.concrete: raise exceptions.FieldDoesNotExist("No related field named '%s'" % self.field_name) return field def set_field_name(self): self.field_name = self.field_name or self.model._meta.pk.name class OneToOneRel(ManyToOneRel): """ Used by OneToOneField to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ def __init__(self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None): super().__init__( field, to, field_name, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) self.multiple = False class ManyToManyRel(ForeignObjectRel): """ Used by ManyToManyField to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=True, through=None, through_fields=None, db_constraint=True): super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, ) if through and not db_constraint: raise ValueError("Can't supply a through model and db_constraint=False") self.through = through if through_fields and not through: raise ValueError("Cannot specify through_fields without a through model") self.through_fields = through_fields self.symmetrical = symmetrical self.db_constraint = db_constraint def get_related_field(self): """ Return the field in the 'to' object to which this relationship is tied. Provided for symmetry with ManyToOneRel. """ opts = self.through._meta if self.through_fields: field = opts.get_field(self.through_fields[0]) else: for field in opts.fields: rel = getattr(field, 'remote_field', None) if rel and rel.model == self.model: break return field.foreign_related_fields[0]
bsd-3-clause
syaiful6/django
django/db/models/sql/constants.py
633
1039
""" Constants specific to the SQL storage portion of the ORM. """ import re # Valid query types (a set is used for speedy lookups). These are (currently) # considered SQL-specific; other storage systems may choose to use different # lookup types. QUERY_TERMS = { 'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in', 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year', 'month', 'day', 'week_day', 'hour', 'minute', 'second', 'isnull', 'search', 'regex', 'iregex', } # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 # Namedtuples for sql.* internal use. # How many results to expect from a cursor.execute call MULTI = 'multi' SINGLE = 'single' CURSOR = 'cursor' NO_RESULTS = 'no results' ORDER_PATTERN = re.compile(r'\?|[-+]?[.\w]+$') ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } # SQL join types. INNER = 'INNER JOIN' LOUTER = 'LEFT OUTER JOIN'
bsd-3-clause
40223208/CDB-Final-
static/Brython3.1.1-20150328-091302/Lib/site-packages/pygame/sprite.py
603
55779
## pygame - Python Game Library ## Copyright (C) 2000-2003, 2007 Pete Shinners ## (C) 2004 Joe Wreschnig ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Library General Public ## License as published by the Free Software Foundation; either ## version 2 of the License, or (at your option) any later version. ## ## 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 ## Library General Public License for more details. ## ## You should have received a copy of the GNU Library General Public ## License along with this library; if not, write to the Free ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## ## Pete Shinners ## pete@shinners.org """pygame module with basic game object classes This module contains several simple classes to be used within games. There are the main Sprite class and several Group classes that contain Sprites. The use of these classes is entirely optional when using Pygame. The classes are fairly lightweight and only provide a starting place for the code that is common to most games. The Sprite class is intended to be used as a base class for the different types of objects in the game. There is also a base Group class that simply stores sprites. A game could create new types of Group classes that operate on specially customized Sprite instances they contain. The basic Sprite class can draw the Sprites it contains to a Surface. The Group.draw() method requires that each Sprite have a Surface.image attribute and a Surface.rect. The Group.clear() method requires these same attributes and can be used to erase all the Sprites with background. There are also more advanced Groups: pygame.sprite.RenderUpdates() and pygame.sprite.OrderedUpdates(). Lastly, this module contains several collision functions. These help find sprites inside multiple groups that have intersecting bounding rectangles. To find the collisions, the Sprites are required to have a Surface.rect attribute assigned. The groups are designed for high efficiency in removing and adding Sprites to them. They also allow cheap testing to see if a Sprite already exists in a Group. A given Sprite can exist in any number of groups. A game could use some groups to control object rendering, and a completely separate set of groups to control interaction or player movement. Instead of adding type attributes or bools to a derived Sprite class, consider keeping the Sprites inside organized Groups. This will allow for easier lookup later in the game. Sprites and Groups manage their relationships with the add() and remove() methods. These methods can accept a single or multiple group arguments for membership. The default initializers for these classes also take a single group or list of groups as argments for initial membership. It is safe to repeatedly add and remove the same Sprite from a Group. While it is possible to design sprite and group classes that don't derive from the Sprite and AbstractGroup classes below, it is strongly recommended that you extend those when you create a new Sprite or Group class. Sprites are not thread safe, so lock them yourself if using threads. """ ##todo ## a group that holds only the 'n' most recent elements. ## sort of like the GroupSingle class, but holding more ## than one sprite ## ## drawing groups that can 'automatically' store the area ## underneath so they can "clear" without needing a background ## function. obviously a little slower than normal, but nice ## to use in many situations. (also remember it must "clear" ## in the reverse order that it draws :]) ## ## the drawing groups should also be able to take a background ## function, instead of just a background surface. the function ## would take a surface and a rectangle on that surface to erase. ## ## perhaps more types of collision functions? the current two ## should handle just about every need, but perhaps more optimized ## specific ones that aren't quite so general but fit into common ## specialized cases. import pygame from pygame.rect import Rect from pygame.time import get_ticks from operator import truth # Python 3 does not have the callable function, but an equivalent can be made # with the hasattr function. #if 'callable' not in dir(__builtins__): callable = lambda obj: hasattr(obj, '__call__') # Don't depend on pygame.mask if it's not there... try: from pygame.mask import from_surface except: pass class Sprite(object): """simple base class for visible game objects pygame.sprite.Sprite(*groups): return Sprite The base class for visible game objects. Derived classes will want to override the Sprite.update() method and assign Sprite.image and Sprite.rect attributes. The initializer can accept any number of Group instances that the Sprite will become a member of. When subclassing the Sprite class, be sure to call the base initializer before adding the Sprite to Groups. """ def __init__(self, *groups): self.__g = {} # The groups the sprite is in if groups: self.add(*groups) def add(self, *groups): """add the sprite to groups Sprite.add(*groups): return None Any number of Group instances can be passed as arguments. The Sprite will be added to the Groups it is not already a member of. """ has = self.__g.__contains__ for group in groups: if hasattr(group, '_spritegroup'): if not has(group): group.add_internal(self) self.add_internal(group) else: self.add(*group) def remove(self, *groups): """remove the sprite from groups Sprite.remove(*groups): return None Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of. """ has = self.__g.__contains__ for group in groups: if hasattr(group, '_spritegroup'): if has(group): group.remove_internal(self) self.remove_internal(group) else: self.remove(*group) def add_internal(self, group): self.__g[group] = 0 def remove_internal(self, group): del self.__g[group] def update(self, *args): """method to control sprite behavior Sprite.update(*args): The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update() with whatever arguments you give it. There is no need to use this method if not using the convenience method by the same name in the Group class. """ pass def kill(self): """remove the Sprite from all Groups Sprite.kill(): return None The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups. """ for c in self.__g: c.remove_internal(self) self.__g.clear() def groups(self): """list of Groups that contain this Sprite Sprite.groups(): return group_list Returns a list of all the Groups that contain this Sprite. """ return list(self.__g) def alive(self): """does the sprite belong to any groups Sprite.alive(): return bool Returns True when the Sprite belongs to one or more Groups. """ return truth(self.__g) def __repr__(self): return "<%s sprite(in %d groups)>" % (self.__class__.__name__, len(self.__g)) class DirtySprite(Sprite): """a more featureful subclass of Sprite with more attributes pygame.sprite.DirtySprite(*groups): return DirtySprite Extra DirtySprite attributes with their default values: dirty = 1 If set to 1, it is repainted and then set to 0 again. If set to 2, it is always dirty (repainted each frame; flag is not reset). If set to 0, it is not dirty and therefore not repainted again. blendmode = 0 It's the special_flags argument of Surface.blit; see the blendmodes in the Surface.blit documentation source_rect = None This is the source rect to use. Remember that it is relative to the top left corner (0, 0) of self.image. visible = 1 Normally this is 1. If set to 0, it will not be repainted. (If you change visible to 1, you must set dirty to 1 for it to be erased from the screen.) _layer = 0 A READ ONLY value, it is read when adding it to the LayeredUpdates group. For details see documentation of sprite.LayeredUpdates. """ def __init__(self, *groups): self.dirty = 1 self.blendmode = 0 # pygame 1.8, referred to as special_flags in # the documentation of Surface.blit self._visible = 1 self._layer = 0 # READ ONLY by LayeredUpdates or LayeredDirty self.source_rect = None Sprite.__init__(self, *groups) def _set_visible(self, val): """set the visible value (0 or 1) and makes the sprite dirty""" self._visible = val if self.dirty < 2: self.dirty = 1 def _get_visible(self): """return the visible value of that sprite""" return self._visible visible = property(lambda self: self._get_visible(), lambda self, value: self._set_visible(value), doc="you can make this sprite disappear without " "removing it from the group,\n" "assign 0 for invisible and 1 for visible") def __repr__(self): return "<%s DirtySprite(in %d groups)>" % \ (self.__class__.__name__, len(self.groups())) class AbstractGroup(object): """base class for containers of sprites AbstractGroup does everything needed to behave as a normal group. You can easily subclass a new group class from this or the other groups below if you want to add more features. Any AbstractGroup-derived sprite groups act like sequences and support iteration, len, and so on. """ # dummy val to identify sprite groups, and avoid infinite recursion _spritegroup = True def __init__(self): self.spritedict = {} self.lostsprites = [] def sprites(self): """get a list of sprites in the group Group.sprite(): return list Returns an object that can be looped over with a 'for' loop. (For now, it is always a list, but this could change in a future version of pygame.) Alternatively, you can get the same information by iterating directly over the sprite group, e.g. 'for sprite in group'. """ return list(self.spritedict) def add_internal(self, sprite): self.spritedict[sprite] = 0 def remove_internal(self, sprite): r = self.spritedict[sprite] if r: self.lostsprites.append(r) del self.spritedict[sprite] def has_internal(self, sprite): return sprite in self.spritedict def copy(self): """copy a group with all the same sprites Group.copy(): return Group Returns a copy of the group that is an instance of the same class and has the same sprites in it. """ return self.__class__(self.sprites()) def __iter__(self): return iter(self.sprites()) def __contains__(self, sprite): return self.has(sprite) def add(self, *sprites): """add sprite(s) to group Group.add(sprite, list, group, ...): return None Adds a sprite or sequence of sprites to a group. """ for sprite in sprites: # It's possible that some sprite is also an iterator. # If this is the case, we should add the sprite itself, # and not the iterator object. if isinstance(sprite, Sprite): if not self.has_internal(sprite): self.add_internal(sprite) sprite.add_internal(self) else: try: # See if sprite is an iterator, like a list or sprite # group. self.add(*sprite) except (TypeError, AttributeError): # Not iterable. This is probably a sprite that is not an # instance of the Sprite class or is not an instance of a # subclass of the Sprite class. Alternately, it could be an # old-style sprite group. if hasattr(sprite, '_spritegroup'): for spr in sprite.sprites(): if not self.has_internal(spr): self.add_internal(spr) spr.add_internal(self) elif not self.has_internal(sprite): self.add_internal(sprite) sprite.add_internal(self) def remove(self, *sprites): """remove sprite(s) from group Group.remove(sprite, list, or group, ...): return None Removes a sprite or sequence of sprites from a group. """ # This function behaves essentially the same as Group.add. It first # tries to handle each argument as an instance of the Sprite class. If # that failes, then it tries to handle the argument as an iterable # object. If that failes, then it tries to handle the argument as an # old-style sprite group. Lastly, if that fails, it assumes that the # normal Sprite methods should be used. for sprite in sprites: if isinstance(sprite, Sprite): if self.has_internal(sprite): self.remove_internal(sprite) sprite.remove_internal(self) else: try: self.remove(*sprite) except (TypeError, AttributeError): if hasattr(sprite, '_spritegroup'): for spr in sprite.sprites(): if self.has_internal(spr): self.remove_internal(spr) spr.remove_internal(self) elif self.has_internal(sprite): self.remove_internal(sprite) sprite.remove_internal(self) def has(self, *sprites): """ask if group has a sprite or sprites Group.has(sprite or group, ...): return bool Returns True if the given sprite or sprites are contained in the group. Alternatively, you can get the same information using the 'in' operator, e.g. 'sprite in group', 'subgroup in group'. """ return_value = False for sprite in sprites: if isinstance(sprite, Sprite): # Check for Sprite instance's membership in this group if self.has_internal(sprite): return_value = True else: return False else: try: if self.has(*sprite): return_value = True else: return False except (TypeError, AttributeError): if hasattr(sprite, '_spritegroup'): for spr in sprite.sprites(): if self.has_internal(spr): return_value = True else: return False else: if self.has_internal(sprite): return_value = True else: return False return return_value def update(self, *args): """call the update method of every member sprite Group.update(*args): return None Calls the update method of every member sprite. All arguments that were passed to this method are passed to the Sprite update function. """ for s in self.sprites(): s.update(*args) def draw(self, surface): """draw all sprites onto the surface Group.draw(surface): return None Draws all of the member sprites onto the given surface. """ #from javascript import console sprites = self.sprites() surface_blit = surface.blit for spr in sprites: #console.log(spr.image, spr.rect) #console.log(spr.image._canvas.width, spr.image._canvas.height) self.spritedict[spr] = surface_blit(spr.image, spr.rect) self.lostsprites = [] def clear(self, surface, bgd): """erase the previous position of all sprites Group.clear(surface, bgd): return None Clears the area under every drawn sprite in the group. The bgd argument should be Surface which is the same dimensions as the screen surface. The bgd could also be a function which accepts the given surface and the area to be cleared as arguments. """ if callable(bgd): for r in self.lostsprites: bgd(surface, r) for r in self.spritedict.values(): if r: bgd(surface, r) else: surface_blit = surface.blit for r in self.lostsprites: surface_blit(bgd, r, r) for r in self.spritedict.values(): if r: surface_blit(bgd, r, r) def empty(self): """remove all sprites Group.empty(): return None Removes all the sprites from the group. """ for s in self.sprites(): self.remove_internal(s) s.remove_internal(self) def __nonzero__(self): return truth(self.sprites()) def __len__(self): """return number of sprites in group Group.len(group): return int Returns the number of sprites contained in the group. """ return len(self.sprites()) def __repr__(self): return "<%s(%d sprites)>" % (self.__class__.__name__, len(self)) class Group(AbstractGroup): """container class for many Sprites pygame.sprite.Group(*sprites): return Group A simple container for Sprite objects. This class can be subclassed to create containers with more specific behaviors. The constructor takes any number of Sprite arguments to add to the Group. The group supports the following standard Python operations: in test if a Sprite is contained len the number of Sprites contained bool test if any Sprites are contained iter iterate through all the Sprites The Sprites in the Group are not ordered, so the Sprites are drawn and iterated over in no particular order. """ def __init__(self, *sprites): AbstractGroup.__init__(self) self.add(*sprites) RenderPlain = Group RenderClear = Group class RenderUpdates(Group): """Group class that tracks dirty updates pygame.sprite.RenderUpdates(*sprites): return RenderUpdates This class is derived from pygame.sprite.Group(). It has an enhanced draw method that tracks the changed areas of the screen. """ def draw(self, surface): spritedict = self.spritedict surface_blit = surface.blit dirty = self.lostsprites self.lostsprites = [] dirty_append = dirty.append for s in self.sprites(): r = spritedict[s] newrect = surface_blit(s.image, s.rect) if r: if newrect.colliderect(r): dirty_append(newrect.union(r)) else: dirty_append(newrect) dirty_append(r) else: dirty_append(newrect) spritedict[s] = newrect return dirty class OrderedUpdates(RenderUpdates): """RenderUpdates class that draws Sprites in order of addition pygame.sprite.OrderedUpdates(*spites): return OrderedUpdates This class derives from pygame.sprite.RenderUpdates(). It maintains the order in which the Sprites were added to the Group for rendering. This makes adding and removing Sprites from the Group a little slower than regular Groups. """ def __init__(self, *sprites): self._spritelist = [] RenderUpdates.__init__(self, *sprites) def sprites(self): return list(self._spritelist) def add_internal(self, sprite): RenderUpdates.add_internal(self, sprite) self._spritelist.append(sprite) def remove_internal(self, sprite): RenderUpdates.remove_internal(self, sprite) self._spritelist.remove(sprite) class LayeredUpdates(AbstractGroup): """LayeredUpdates Group handles layers, which are drawn like OrderedUpdates pygame.sprite.LayeredUpdates(*spites, **kwargs): return LayeredUpdates This group is fully compatible with pygame.sprite.Sprite. New in pygame 1.8.0 """ _init_rect = Rect(0, 0, 0, 0) def __init__(self, *sprites, **kwargs): """initialize an instance of LayeredUpdates with the given attributes You can set the default layer through kwargs using 'default_layer' and an integer for the layer. The default layer is 0. If the sprite you add has an attribute _layer, then that layer will be used. If **kwarg contains 'layer', then the passed sprites will be added to that layer (overriding the sprite._layer attribute). If neither the sprite nor **kwarg has a 'layer', then the default layer is used to add the sprites. """ self._spritelayers = {} self._spritelist = [] AbstractGroup.__init__(self) self._default_layer = kwargs.get('default_layer', 0) self.add(*sprites, **kwargs) def add_internal(self, sprite, layer=None): """Do not use this method directly. It is used by the group to add a sprite internally. """ self.spritedict[sprite] = self._init_rect if layer is None: try: layer = sprite._layer except AttributeError: layer = sprite._layer = self._default_layer elif hasattr(sprite, '_layer'): sprite._layer = layer sprites = self._spritelist # speedup sprites_layers = self._spritelayers sprites_layers[sprite] = layer # add the sprite at the right position # bisect algorithmus leng = len(sprites) low = mid = 0 high = leng - 1 while low <= high: mid = low + (high - low) // 2 if sprites_layers[sprites[mid]] <= layer: low = mid + 1 else: high = mid - 1 # linear search to find final position while mid < leng and sprites_layers[sprites[mid]] <= layer: mid += 1 sprites.insert(mid, sprite) def add(self, *sprites, **kwargs): """add a sprite or sequence of sprites to a group LayeredUpdates.add(*sprites, **kwargs): return None If the sprite you add has an attribute _layer, then that layer will be used. If **kwarg contains 'layer', then the passed sprites will be added to that layer (overriding the sprite._layer attribute). If neither the sprite nor **kwarg has a 'layer', then the default layer is used to add the sprites. """ if not sprites: return if 'layer' in kwargs: layer = kwargs['layer'] else: layer = None for sprite in sprites: # It's possible that some sprite is also an iterator. # If this is the case, we should add the sprite itself, # and not the iterator object. if isinstance(sprite, Sprite): if not self.has_internal(sprite): self.add_internal(sprite, layer) sprite.add_internal(self) else: try: # See if sprite is an iterator, like a list or sprite # group. self.add(*sprite, **kwargs) except (TypeError, AttributeError): # Not iterable. This is probably a sprite that is not an # instance of the Sprite class or is not an instance of a # subclass of the Sprite class. Alternately, it could be an # old-style sprite group. if hasattr(sprite, '_spritegroup'): for spr in sprite.sprites(): if not self.has_internal(spr): self.add_internal(spr, layer) spr.add_internal(self) elif not self.has_internal(sprite): self.add_internal(sprite, layer) sprite.add_internal(self) def remove_internal(self, sprite): """Do not use this method directly. The group uses it to add a sprite. """ self._spritelist.remove(sprite) # these dirty rects are suboptimal for one frame r = self.spritedict[sprite] if r is not self._init_rect: self.lostsprites.append(r) # dirty rect if hasattr(sprite, 'rect'): self.lostsprites.append(sprite.rect) # dirty rect del self.spritedict[sprite] del self._spritelayers[sprite] def sprites(self): """return a ordered list of sprites (first back, last top). LayeredUpdates.sprites(): return sprites """ return list(self._spritelist) def draw(self, surface): """draw all sprites in the right order onto the passed surface LayeredUpdates.draw(surface): return Rect_list """ spritedict = self.spritedict surface_blit = surface.blit dirty = self.lostsprites self.lostsprites = [] dirty_append = dirty.append init_rect = self._init_rect for spr in self.sprites(): rec = spritedict[spr] newrect = surface_blit(spr.image, spr.rect) if rec is init_rect: dirty_append(newrect) else: if newrect.colliderect(rec): dirty_append(newrect.union(rec)) else: dirty_append(newrect) dirty_append(rec) spritedict[spr] = newrect return dirty def get_sprites_at(self, pos): """return a list with all sprites at that position LayeredUpdates.get_sprites_at(pos): return colliding_sprites Bottom sprites are listed first; the top ones are listed last. """ _sprites = self._spritelist rect = Rect(pos, (0, 0)) colliding_idx = rect.collidelistall(_sprites) colliding = [_sprites[i] for i in colliding_idx] return colliding def get_sprite(self, idx): """return the sprite at the index idx from the groups sprites LayeredUpdates.get_sprite(idx): return sprite Raises IndexOutOfBounds if the idx is not within range. """ return self._spritelist[idx] def remove_sprites_of_layer(self, layer_nr): """remove all sprites from a layer and return them as a list LayeredUpdates.remove_sprites_of_layer(layer_nr): return sprites """ sprites = self.get_sprites_from_layer(layer_nr) self.remove(*sprites) return sprites #---# layer methods def layers(self): """return a list of unique defined layers defined. LayeredUpdates.layers(): return layers """ return sorted(set(self._spritelayers.values())) def change_layer(self, sprite, new_layer): """change the layer of the sprite LayeredUpdates.change_layer(sprite, new_layer): return None The sprite must have been added to the renderer already. This is not checked. """ sprites = self._spritelist # speedup sprites_layers = self._spritelayers # speedup sprites.remove(sprite) sprites_layers.pop(sprite) # add the sprite at the right position # bisect algorithmus leng = len(sprites) low = mid = 0 high = leng - 1 while low <= high: mid = low + (high - low) // 2 if sprites_layers[sprites[mid]] <= new_layer: low = mid + 1 else: high = mid - 1 # linear search to find final position while mid < leng and sprites_layers[sprites[mid]] <= new_layer: mid += 1 sprites.insert(mid, sprite) if hasattr(sprite, 'layer'): sprite.layer = new_layer # add layer info sprites_layers[sprite] = new_layer def get_layer_of_sprite(self, sprite): """return the layer that sprite is currently in If the sprite is not found, then it will return the default layer. """ return self._spritelayers.get(sprite, self._default_layer) def get_top_layer(self): """return the top layer LayeredUpdates.get_top_layer(): return layer """ return self._spritelayers[self._spritelist[-1]] def get_bottom_layer(self): """return the bottom layer LayeredUpdates.get_bottom_layer(): return layer """ return self._spritelayers[self._spritelist[0]] def move_to_front(self, sprite): """bring the sprite to front layer LayeredUpdates.move_to_front(sprite): return None Brings the sprite to front by changing the sprite layer to the top-most layer. The sprite is added at the end of the list of sprites in that top-most layer. """ self.change_layer(sprite, self.get_top_layer()) def move_to_back(self, sprite): """move the sprite to the bottom layer LayeredUpdates.move_to_back(sprite): return None Moves the sprite to the bottom layer by moving it to a new layer below the current bottom layer. """ self.change_layer(sprite, self.get_bottom_layer() - 1) def get_top_sprite(self): """return the topmost sprite LayeredUpdates.get_top_sprite(): return Sprite """ return self._spritelist[-1] def get_sprites_from_layer(self, layer): """return all sprites from a layer ordered as they where added LayeredUpdates.get_sprites_from_layer(layer): return sprites Returns all sprites from a layer. The sprites are ordered in the sequence that they where added. (The sprites are not removed from the layer. """ sprites = [] sprites_append = sprites.append sprite_layers = self._spritelayers for spr in self._spritelist: if sprite_layers[spr] == layer: sprites_append(spr) elif sprite_layers[spr] > layer:# break after because no other will # follow with same layer break return sprites def switch_layer(self, layer1_nr, layer2_nr): """switch the sprites from layer1_nr to layer2_nr LayeredUpdates.switch_layer(layer1_nr, layer2_nr): return None The layers number must exist. This method does not check for the existence of the given layers. """ sprites1 = self.remove_sprites_of_layer(layer1_nr) for spr in self.get_sprites_from_layer(layer2_nr): self.change_layer(spr, layer1_nr) self.add(layer=layer2_nr, *sprites1) class LayeredDirty(LayeredUpdates): """LayeredDirty Group is for DirtySprites; subclasses LayeredUpdates pygame.sprite.LayeredDirty(*spites, **kwargs): return LayeredDirty This group requires pygame.sprite.DirtySprite or any sprite that has the following attributes: image, rect, dirty, visible, blendmode (see doc of DirtySprite). It uses the dirty flag technique and is therefore faster than pygame.sprite.RenderUpdates if you have many static sprites. It also switches automatically between dirty rect updating and full screen drawing, so you do no have to worry which would be faster. As with the pygame.sprite.Group, you can specify some additional attributes through kwargs: _use_update: True/False (default is False) _default_layer: default layer where the sprites without a layer are added _time_threshold: treshold time for switching between dirty rect mode and fullscreen mode; defaults to updating at 80 frames per second, which is equal to 1000.0 / 80.0 New in pygame 1.8.0 """ def __init__(self, *sprites, **kwargs): """initialize group. pygame.sprite.LayeredDirty(*spites, **kwargs): return LayeredDirty You can specify some additional attributes through kwargs: _use_update: True/False (default is False) _default_layer: default layer where the sprites without a layer are added _time_threshold: treshold time for switching between dirty rect mode and fullscreen mode; defaults to updating at 80 frames per second, which is equal to 1000.0 / 80.0 """ LayeredUpdates.__init__(self, *sprites, **kwargs) self._clip = None self._use_update = False self._time_threshold = 1000.0 / 80.0 # 1000.0 / fps self._bgd = None for key, val in kwargs.items(): if key in ['_use_update', '_time_threshold', '_default_layer']: if hasattr(self, key): setattr(self, key, val) def add_internal(self, sprite, layer=None): """Do not use this method directly. It is used by the group to add a sprite internally. """ # check if all needed attributes are set if not hasattr(sprite, 'dirty'): raise AttributeError() if not hasattr(sprite, 'visible'): raise AttributeError() if not hasattr(sprite, 'blendmode'): raise AttributeError() if not isinstance(sprite, DirtySprite): raise TypeError() if sprite.dirty == 0: # set it dirty if it is not sprite.dirty = 1 LayeredUpdates.add_internal(self, sprite, layer) def draw(self, surface, bgd=None): """draw all sprites in the right order onto the given surface LayeredDirty.draw(surface, bgd=None): return Rect_list You can pass the background too. If a self.bgd is already set to some value that is not None, then the bgd argument has no effect. """ # speedups _orig_clip = surface.get_clip() _clip = self._clip if _clip is None: _clip = _orig_clip _surf = surface _sprites = self._spritelist _old_rect = self.spritedict _update = self.lostsprites _update_append = _update.append _ret = None _surf_blit = _surf.blit _rect = Rect if bgd is not None: self._bgd = bgd _bgd = self._bgd init_rect = self._init_rect _surf.set_clip(_clip) # ------- # 0. decide whether to render with update or flip start_time = get_ticks() if self._use_update: # dirty rects mode # 1. find dirty area on screen and put the rects into _update # still not happy with that part for spr in _sprites: if 0 < spr.dirty: # chose the right rect if spr.source_rect: _union_rect = _rect(spr.rect.topleft, spr.source_rect.size) else: _union_rect = _rect(spr.rect) _union_rect_collidelist = _union_rect.collidelist _union_rect_union_ip = _union_rect.union_ip i = _union_rect_collidelist(_update) while -1 < i: _union_rect_union_ip(_update[i]) del _update[i] i = _union_rect_collidelist(_update) _update_append(_union_rect.clip(_clip)) if _old_rect[spr] is not init_rect: _union_rect = _rect(_old_rect[spr]) _union_rect_collidelist = _union_rect.collidelist _union_rect_union_ip = _union_rect.union_ip i = _union_rect_collidelist(_update) while -1 < i: _union_rect_union_ip(_update[i]) del _update[i] i = _union_rect_collidelist(_update) _update_append(_union_rect.clip(_clip)) # can it be done better? because that is an O(n**2) algorithm in # worst case # clear using background if _bgd is not None: for rec in _update: _surf_blit(_bgd, rec, rec) # 2. draw for spr in _sprites: if 1 > spr.dirty: if spr._visible: # sprite not dirty; blit only the intersecting part _spr_rect = spr.rect if spr.source_rect is not None: _spr_rect = Rect(spr.rect.topleft, spr.source_rect.size) _spr_rect_clip = _spr_rect.clip for idx in _spr_rect.collidelistall(_update): # clip clip = _spr_rect_clip(_update[idx]) _surf_blit(spr.image, clip, (clip[0] - _spr_rect[0], clip[1] - _spr_rect[1], clip[2], clip[3]), spr.blendmode) else: # dirty sprite if spr._visible: _old_rect[spr] = _surf_blit(spr.image, spr.rect, spr.source_rect, spr.blendmode) if spr.dirty == 1: spr.dirty = 0 _ret = list(_update) else: # flip, full screen mode if _bgd is not None: _surf_blit(_bgd, (0, 0)) for spr in _sprites: if spr._visible: _old_rect[spr] = _surf_blit(spr.image, spr.rect, spr.source_rect, spr.blendmode) _ret = [_rect(_clip)] # return only the part of the screen changed # timing for switching modes # How may a good threshold be found? It depends on the hardware. end_time = get_ticks() if end_time-start_time > self._time_threshold: self._use_update = False else: self._use_update = True ## # debug ## print " check: using dirty rects:", self._use_update # emtpy dirty rects list _update[:] = [] # ------- # restore original clip _surf.set_clip(_orig_clip) return _ret def clear(self, surface, bgd): """use to set background Group.clear(surface, bgd): return None """ self._bgd = bgd def repaint_rect(self, screen_rect): """repaint the given area LayeredDirty.repaint_rect(screen_rect): return None screen_rect is in screen coordinates. """ if self._clip: self.lostsprites.append(screen_rect.clip(self._clip)) else: self.lostsprites.append(Rect(screen_rect)) def set_clip(self, screen_rect=None): """clip the area where to draw; pass None (default) to reset the clip LayeredDirty.set_clip(screen_rect=None): return None """ if screen_rect is None: self._clip = pygame.display.get_surface().get_rect() else: self._clip = screen_rect self._use_update = False def get_clip(self): """get the area where drawing will occur LayeredDirty.get_clip(): return Rect """ return self._clip def change_layer(self, sprite, new_layer): """change the layer of the sprite LayeredUpdates.change_layer(sprite, new_layer): return None The sprite must have been added to the renderer already. This is not checked. """ LayeredUpdates.change_layer(self, sprite, new_layer) if sprite.dirty == 0: sprite.dirty = 1 def set_timing_treshold(self, time_ms): """set the treshold in milliseconds set_timing_treshold(time_ms): return None Defaults to 1000.0 / 80.0. This means that the screen will be painted using the flip method rather than the update method if the update method is taking so long to update the screen that the frame rate falls below 80 frames per second. """ self._time_threshold = time_ms class GroupSingle(AbstractGroup): """A group container that holds a single most recent item. This class works just like a regular group, but it only keeps a single sprite in the group. Whatever sprite has been added to the group last will be the only sprite in the group. You can access its one sprite as the .sprite attribute. Assigning to this attribute will properly remove the old sprite and then add the new one. """ def __init__(self, sprite=None): AbstractGroup.__init__(self) self.__sprite = None if sprite is not None: self.add(sprite) def copy(self): return GroupSingle(self.__sprite) def sprites(self): if self.__sprite is not None: return [self.__sprite] else: return [] def add_internal(self, sprite): if self.__sprite is not None: self.__sprite.remove_internal(self) self.remove_internal(self.__sprite) self.__sprite = sprite def __nonzero__(self): return self.__sprite is not None def _get_sprite(self): return self.__sprite def _set_sprite(self, sprite): self.add_internal(sprite) sprite.add_internal(self) return sprite sprite = property(_get_sprite, _set_sprite, None, "The sprite contained in this group") def remove_internal(self, sprite): if sprite is self.__sprite: self.__sprite = None if sprite in self.spritedict: AbstractGroup.remove_internal(self, sprite) def has_internal(self, sprite): return self.__sprite is sprite # Optimizations... def __contains__(self, sprite): return self.__sprite is sprite # Some different collision detection functions that could be used. def collide_rect(left, right): """collision detection between two sprites, using rects. pygame.sprite.collide_rect(left, right): return bool Tests for collision between two sprites. Uses the pygame.Rect colliderect function to calculate the collision. It is intended to be passed as a collided callback function to the *collide functions. Sprites must have "rect" attributes. New in pygame 1.8.0 """ return left.rect.colliderect(right.rect) class collide_rect_ratio: """A callable class that checks for collisions using scaled rects The class checks for collisions between two sprites using a scaled version of the sprites' rects. Is created with a ratio; the instance is then intended to be passed as a collided callback function to the *collide functions. New in pygame 1.8.1 """ def __init__(self, ratio): """create a new collide_rect_ratio callable Ratio is expected to be a floating point value used to scale the underlying sprite rect before checking for collisions. """ self.ratio = ratio def __call__(self, left, right): """detect collision between two sprites using scaled rects pygame.sprite.collide_rect_ratio(ratio)(left, right): return bool Tests for collision between two sprites. Uses the pygame.Rect colliderect function to calculate the collision after scaling the rects by the stored ratio. Sprites must have "rect" attributes. """ ratio = self.ratio leftrect = left.rect width = leftrect.width height = leftrect.height leftrect = leftrect.inflate(width * ratio - width, height * ratio - height) rightrect = right.rect width = rightrect.width height = rightrect.height rightrect = rightrect.inflate(width * ratio - width, height * ratio - height) return leftrect.colliderect(rightrect) def collide_circle(left, right): """detect collision between two sprites using circles pygame.sprite.collide_circle(left, right): return bool Tests for collision between two sprites by testing whether two circles centered on the sprites overlap. If the sprites have a "radius" attribute, then that radius is used to create the circle; otherwise, a circle is created that is big enough to completely enclose the sprite's rect as given by the "rect" attribute. This function is intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute. New in pygame 1.8.0 """ xdistance = left.rect.centerx - right.rect.centerx ydistance = left.rect.centery - right.rect.centery distancesquared = xdistance ** 2 + ydistance ** 2 if hasattr(left, 'radius'): leftradius = left.radius else: leftrect = left.rect # approximating the radius of a square by using half of the diagonal, # might give false positives (especially if its a long small rect) leftradius = 0.5 * ((leftrect.width ** 2 + leftrect.height ** 2) ** 0.5) # store the radius on the sprite for next time setattr(left, 'radius', leftradius) if hasattr(right, 'radius'): rightradius = right.radius else: rightrect = right.rect # approximating the radius of a square by using half of the diagonal # might give false positives (especially if its a long small rect) rightradius = 0.5 * ((rightrect.width ** 2 + rightrect.height ** 2) ** 0.5) # store the radius on the sprite for next time setattr(right, 'radius', rightradius) return distancesquared <= (leftradius + rightradius) ** 2 class collide_circle_ratio(object): """detect collision between two sprites using scaled circles This callable class checks for collisions between two sprites using a scaled version of a sprite's radius. It is created with a ratio as the argument to the constructor. The instance is then intended to be passed as a collided callback function to the *collide functions. New in pygame 1.8.1 """ def __init__(self, ratio): """creates a new collide_circle_ratio callable instance The given ratio is expected to be a floating point value used to scale the underlying sprite radius before checking for collisions. When the ratio is ratio=1.0, then it behaves exactly like the collide_circle method. """ self.ratio = ratio def __call__(self, left, right): """detect collision between two sprites using scaled circles pygame.sprite.collide_circle_radio(ratio)(left, right): return bool Tests for collision between two sprites by testing whether two circles centered on the sprites overlap after scaling the circle's radius by the stored ratio. If the sprites have a "radius" attribute, that is used to create the circle; otherwise, a circle is created that is big enough to completely enclose the sprite's rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute. """ ratio = self.ratio xdistance = left.rect.centerx - right.rect.centerx ydistance = left.rect.centery - right.rect.centery distancesquared = xdistance ** 2 + ydistance ** 2 if hasattr(left, "radius"): leftradius = left.radius * ratio else: leftrect = left.rect leftradius = ratio * 0.5 * ((leftrect.width ** 2 + leftrect.height ** 2) ** 0.5) # store the radius on the sprite for next time setattr(left, 'radius', leftradius) if hasattr(right, "radius"): rightradius = right.radius * ratio else: rightrect = right.rect rightradius = ratio * 0.5 * ((rightrect.width ** 2 + rightrect.height ** 2) ** 0.5) # store the radius on the sprite for next time setattr(right, 'radius', rightradius) return distancesquared <= (leftradius + rightradius) ** 2 def collide_mask(left, right): """collision detection between two sprites, using masks. pygame.sprite.collide_mask(SpriteLeft, SpriteRight): bool Tests for collision between two sprites by testing if their bitmasks overlap. If the sprites have a "mask" attribute, that is used as the mask; otherwise, a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "mask" attribute. New in pygame 1.8.0 """ xoffset = right.rect[0] - left.rect[0] yoffset = right.rect[1] - left.rect[1] try: leftmask = left.mask except AttributeError: leftmask = from_surface(left.image) try: rightmask = right.mask except AttributeError: rightmask = from_surface(right.image) return leftmask.overlap(rightmask, (xoffset, yoffset)) def spritecollide(sprite, group, dokill, collided=None): """find Sprites in a Group that intersect another Sprite pygame.sprite.spritecollide(sprite, group, dokill, collided=None): return Sprite_list Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite. The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group. The collided argument is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision. """ if dokill: crashed = [] append = crashed.append if collided: for s in group.sprites(): if collided(sprite, s): s.kill() append(s) else: spritecollide = sprite.rect.colliderect for s in group.sprites(): if spritecollide(s.rect): s.kill() append(s) return crashed elif collided: return [s for s in group if collided(sprite, s)] else: spritecollide = sprite.rect.colliderect return [s for s in group if spritecollide(s.rect)] def groupcollide(groupa, groupb, dokilla, dokillb, collided=None): """detect collision between a group and another group pygame.sprite.groupcollide(groupa, groupb, dokilla, dokillb): return dict Given two groups, this will find the intersections between all sprites in each group. It returns a dictionary of all sprites in the first group that collide. The value for each item in the dictionary is a list of the sprites in the second group it collides with. The two dokill arguments control if the sprites from either group will be automatically removed from all groups. Collided is a callback function used to calculate if two sprites are colliding. it should take two sprites as values, and return a bool value indicating if they are colliding. If collided is not passed, all sprites must have a "rect" value, which is a rectangle of the sprite area that will be used to calculate the collision. """ crashed = {} SC = spritecollide if dokilla: for s in groupa.sprites(): c = SC(s, groupb, dokillb, collided) if c: crashed[s] = c s.kill() else: for s in groupa: c = SC(s, groupb, dokillb, collided) if c: crashed[s] = c return crashed def spritecollideany(sprite, group, collided=None): """finds any sprites in a group that collide with the given sprite pygame.sprite.spritecollideany(sprite, group): return sprite Given a sprite and a group of sprites, this will return return any single sprite that collides with with the given sprite. If there are no collisions, then this returns None. If you don't need all the features of the spritecollide function, this function will be a bit quicker. Collided is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision. """ if collided: for s in group: if collided(sprite, s): return s else: # Special case old behaviour for speed. spritecollide = sprite.rect.colliderect for s in group: if spritecollide(s.rect): return s return None
gpl-3.0
ziyan/spider
evaluate/diffbot.py
1
1341
#!/usr/bin/env python import os import sys lib_path = os.path.realpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'lib')) if lib_path not in sys.path: sys.path[0:0] = [lib_path] import utils import os import argparse import urllib, urllib2 import simplejson as json def main(args): path = utils.get_data_path(args.site[0]) urls = utils.load_urls(path) # extract data from each url data = [] for id, url in enumerate(urls): url = url.strip() if not url: continue print '[diffbot] #%03d: %s' % (id, url) response = urllib2.urlopen('http://www.diffbot.com/api/article?' + urllib.urlencode({ 'url': url, 'token': '4bc6e407da88dd8723c70a5297cdf7fb', 'timeout': '60000', })) data.append(json.loads(response.read())) with open(os.path.join(path, 'diffbot.json'), 'w') as f: f.write(json.dumps(data, indent=2, ensure_ascii=False).encode('utf8')) def parse_args(): """ Parse command line arguments """ parser = argparse.ArgumentParser(description='Extract site pages.') parser.add_argument('site', metavar='site', type=str, nargs=1, help='site id, for example: theverge, npr, nytimes') return parser.parse_args() if __name__ == '__main__': main(parse_args())
mit
jenalgit/django
tests/view_tests/urls.py
82
3317
# -*- coding: utf-8 -*- from functools import partial from os import path from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.utils._os import upath from django.utils.translation import ugettext_lazy as _ from django.views import defaults, i18n, static from . import views base_dir = path.dirname(path.abspath(upath(__file__))) media_dir = path.join(base_dir, 'media') locale_dir = path.join(base_dir, 'locale') js_info_dict = { 'domain': 'djangojs', 'packages': ('view_tests',), } js_info_dict_english_translation = { 'domain': 'djangojs', 'packages': ('view_tests.app0',), } js_info_dict_multi_packages1 = { 'domain': 'djangojs', 'packages': ('view_tests.app1', 'view_tests.app2'), } js_info_dict_multi_packages2 = { 'domain': 'djangojs', 'packages': ('view_tests.app3', 'view_tests.app4'), } js_info_dict_admin = { 'domain': 'djangojs', 'packages': ('django.contrib.admin', 'view_tests'), } js_info_dict_app1 = { 'domain': 'djangojs', 'packages': ('view_tests.app1',), } js_info_dict_app2 = { 'domain': 'djangojs', 'packages': ('view_tests.app2',), } js_info_dict_app5 = { 'domain': 'djangojs', 'packages': ('view_tests.app5',), } urlpatterns = [ url(r'^$', views.index_page), # Default views url(r'^non_existing_url/', partial(defaults.page_not_found, exception=None)), url(r'^server_error/', defaults.server_error), # a view that raises an exception for the debug view url(r'raises/$', views.raises), url(r'raises400/$', views.raises400), url(r'raises403/$', views.raises403), url(r'raises404/$', views.raises404), url(r'raises500/$', views.raises500), url(r'technical404/$', views.technical404, name="my404"), url(r'classbased404/$', views.Http404View.as_view()), # i18n views url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/$', i18n.javascript_catalog, js_info_dict), url(r'^jsi18n/app1/$', i18n.javascript_catalog, js_info_dict_app1), url(r'^jsi18n/app2/$', i18n.javascript_catalog, js_info_dict_app2), url(r'^jsi18n/app5/$', i18n.javascript_catalog, js_info_dict_app5), url(r'^jsi18n_english_translation/$', i18n.javascript_catalog, js_info_dict_english_translation), url(r'^jsi18n_multi_packages1/$', i18n.javascript_catalog, js_info_dict_multi_packages1), url(r'^jsi18n_multi_packages2/$', i18n.javascript_catalog, js_info_dict_multi_packages2), url(r'^jsi18n_admin/$', i18n.javascript_catalog, js_info_dict_admin), url(r'^jsi18n_template/$', views.jsi18n), url(r'^jsi18n_multi_catalogs/$', views.jsi18n_multi_catalogs), # Static views url(r'^site_media/(?P<path>.*)$', static.serve, {'document_root': media_dir}), ] urlpatterns += i18n_patterns( url(_(r'^translated/$'), views.index_page, name='i18n_prefixed'), ) urlpatterns += [ url(r'view_exception/(?P<n>[0-9]+)/$', views.view_exception, name='view_exception'), url(r'template_exception/(?P<n>[0-9]+)/$', views.template_exception, name='template_exception'), url(r'^raises_template_does_not_exist/(?P<path>.+)$', views.raises_template_does_not_exist, name='raises_template_does_not_exist'), url(r'^render_no_template/$', views.render_no_template, name='render_no_template'), ]
bsd-3-clause
seanli9jan/tensorflow
tensorflow/python/ops/array_grad.py
4
29874
# Copyright 2015 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. # ============================================================================== """Gradients for operators defined in array_ops.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python import pywrap_tensorflow from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import sparse_ops @ops.RegisterGradient("Pack") def _PackGrad(op, grad): """Gradient for pack op.""" return array_ops.unstack(grad, num=op.get_attr("N"), axis=op.get_attr("axis")) @ops.RegisterGradient("Unpack") def _UnpackGrad(op, *grads): """Gradient for unpack op.""" return array_ops.stack(grads, axis=op.get_attr("axis")) def _ConcatGradHelper(op, grad, start_value_index, end_value_index, dim_index): """Gradient for concat op. Args: op: An operation. grad: `Tensor` or `IndexedSlices` representing the gradients with respect to each output of the op. start_value_index: An integer index of the first value in the op.inputs. end_value_index: An integer index of the last value in the op.inputs. dim_index: An interger index of concat_dim or axis parameter in op.inputs. Returns: Tensors representing the partial gradients with respect to each input of the op. Raises: ValueError: if concat_dim/axis is not statically known. """ def _CreateDenseMaskAndBegin(sizes, concat_dim): """Create variables for iteratively slicing a dense gradients tensor.""" # Since shape is 1-D, shape_of_shape = [rank-of-inputs] shape_of_shape = array_ops.shape(sizes[0]) # Make a vector of length equal to the input's dimensions, # with 0's everywhere and 1 in the concat dim position. # Note: Can't use sparse_to_dense since it isn't GPU-capable (for now) mask = array_ops.concat([ array_ops.fill(array_ops.expand_dims(concat_dim, 0), 0), [1], array_ops.fill(shape_of_shape - concat_dim - 1, 0) ], 0) begin = array_ops.fill(shape_of_shape, 0) return mask, begin def _ExtractInputShapes(inputs): """Extract the shapes of a set of input tensors.""" if context.executing_eagerly(): return array_ops.shape_n(inputs) sizes = [] fully_known = True for x in inputs: input_shape = array_ops.shape(x) if not isinstance(input_shape, ops.Tensor) or input_shape.op.type != "Const": fully_known = False break sizes.append(input_shape) if fully_known: return sizes else: return array_ops.shape_n(inputs) # Degenerate concatenation, just return grad. if len(op.inputs) == 2: return grad + [None] if end_value_index <= dim_index else [None] + grad concat_dim = op.inputs[dim_index] input_values = op.inputs[start_value_index:end_value_index] out_grads = [] if isinstance(grad, ops.Tensor): if context.executing_eagerly(): # Using mod here for convenience since concat_dim is already verified # in concat implementation to be within the allowed [-rank, rank) range. non_neg_concat_dim = ( concat_dim._numpy().item(0) % input_values[0]._rank()) # pylint: disable=protected-access # All inputs are guaranteed to be EagerTensors in eager mode sizes = pywrap_tensorflow.TFE_Py_TensorShapeSlice(input_values, non_neg_concat_dim) out_grads = array_ops.split(grad, sizes, non_neg_concat_dim) else: if constant_op.is_constant(concat_dim): # If concat_dim is a constant defined in a different context, # then we duplicate it in the current context to avoid passing it # through an Enter node. # This is a small optimization in general, but it is required when # compiling with XLA, as XLA needs the concat input to be folded into a # constant. grad_context = control_flow_util.GetOutputContext(grad.op) dim_context = control_flow_util.GetOutputContext(concat_dim.op) if dim_context != grad_context: value = tensor_util.constant_value(concat_dim) concat_dim = constant_op.constant(value=value, dtype=concat_dim.dtype) # Using mod here for convenience since concat_dim is already verified # in concat implementation to be within the allowed [-rank, rank) range. non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0]) # Get the inputs' tensor shapes sizes = _ExtractInputShapes(input_values) # The magic number of 16 was found through benchmarking a range of sizes # on CPUs and a Maxwell TitanX. A speedup was seen in a large majority of # cases when switching implementations at N=16, but it is possible that # there will be a small number of performance regressions. if len(sizes) > 16: # extract the size of each input along the concat dimension sizes = array_ops.squeeze( array_ops.slice( array_ops.stack(sizes, axis=1), [non_neg_concat_dim, 0], [1, -1])) out_grads = array_ops.split(grad, sizes, non_neg_concat_dim) else: offset = gen_array_ops.concat_offset(non_neg_concat_dim, sizes) for (begin, size) in zip(offset, sizes): out_grads.append(array_ops.slice(grad, begin, size)) elif isinstance(grad, ops.IndexedSlices): # Using mod here for convenience since concat_dim is already verified # in concat implementation to be within the allowed [-rank, rank) range. non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0]) concat_dim_static = tensor_util.constant_value(concat_dim) if concat_dim_static is None: raise ValueError("Can only compute IndexedSlices gradient with " "statically-known concat_dim") if concat_dim_static < 0: rank = tensor_util.constant_value(array_ops.rank(input_values[0])) if rank is None: raise ValueError("Can only compute IndexedSlices gradient with " "negative concat_dim when first value rank is " "statically-known.") concat_dim_static %= rank # Get the inputs' tensor shapes sizes = [array_ops.shape(x) for x in input_values] if concat_dim_static > 0: # IndexedSlices, non_neg_concat_dim > 0. Each input gets IndexedSlices # gradients with all the indices, but with grad.values sliced accordingly. # This is like the Tensor case, except shape(grad.values)[0] is not equal # to shape(sizes[i])[0], since only a subset of the dim-0 values are # stored. mask, begin = _CreateDenseMaskAndBegin(sizes, non_neg_concat_dim) for size in sizes: new_values = array_ops.slice( grad.values, begin, array_ops.concat([[-1], array_ops.slice(size, [1], [-1])], 0)) out_grads.append(ops.IndexedSlices(new_values, grad.indices, size)) # Lint complains begin = begin + ... begin = math_ops.add(begin, size * mask) else: # IndexedSlices, concat_dim == 0. Each input gets IndexedSlices gradients # only for the relevant indices. start = constant_op.constant(0, dtype=grad.indices.dtype) for size in sizes: size_concat_dim = array_ops.gather(size, non_neg_concat_dim) if size_concat_dim.dtype != grad.indices.dtype: size_concat_dim = math_ops.cast( size_concat_dim, dtype=grad.indices.dtype) end = start + size_concat_dim # Compute the 1-D Tensor of indices relevant for this input. indices_to_select = array_ops.squeeze( array_ops.where( math_ops.logical_and(grad.indices >= start, grad.indices < end)), axis=[1]) new_indices = array_ops.gather(grad.indices, indices_to_select) - start new_values = array_ops.gather(grad.values, indices_to_select) out_grads.append(ops.IndexedSlices(new_values, new_indices, size)) start = end else: raise TypeError("Expected Tensor or IndexedSlices, got %s" % type(grad)) return (out_grads + [None] if end_value_index <= dim_index else [None] + out_grads) @ops.RegisterGradient("Concat") def _ConcatGrad(op, grad): return _ConcatGradHelper( op, grad, start_value_index=1, end_value_index=len(op.inputs), dim_index=0) @ops.RegisterGradient("ConcatV2") def _ConcatGradV2(op, grad): return _ConcatGradHelper( op, grad, start_value_index=0, end_value_index=-1, dim_index=-1) ops.NotDifferentiable("ConcatOffset") @ops.RegisterGradient("Slice") def _SliceGrad(op, grad): """Gradient for Slice op.""" # Create an Nx2 padding where the first column represents how many # zeros are to be prepended for each dimension, and the second # column indicates how many zeros are appended. # # The number of zeros to append is the shape of the input # elementwise-subtracted by both the begin vector and sizes vector. # # Some more reshaping is needed to assemble this tensor with the # right dimensions. input_vec = op.inputs[0] begin_vec = op.inputs[1] input_rank = array_ops.rank(input_vec) slice_size = array_ops.shape(op.outputs[0]) shape = array_ops.stack([input_rank, 1]) before_pad = array_ops.reshape(begin_vec, shape) after_pad = array_ops.reshape( array_ops.shape(input_vec) - slice_size - begin_vec, shape) paddings = array_ops.concat([before_pad, after_pad], 1) return array_ops.pad(grad, paddings), None, None @ops.RegisterGradient("StridedSlice") def _StridedSliceGrad(op, grad): """Gradient for StridedSlice op.""" begin = op.inputs[1] end = op.inputs[2] strides = op.inputs[3] # StridedSliceGrad requires `x`, `begin`, `end` and `strides` to be of the # same dtype so we build a shape of the same type as other args. # Note that the choice of `begin` for specifying `out_type` is arbitrary. # We could choose any of {begin|end|strides}.dtype since they are required to # be the same. x = array_ops.shape(op.inputs[0], out_type=begin.dtype) return array_ops.strided_slice_grad( x, begin, end, strides, grad, begin_mask=op.get_attr("begin_mask"), end_mask=op.get_attr("end_mask"), ellipsis_mask=op.get_attr("ellipsis_mask"), new_axis_mask=op.get_attr("new_axis_mask"), shrink_axis_mask=op.get_attr("shrink_axis_mask")), None, None, None @ops.RegisterGradient("StridedSliceGrad") def _StridedSliceGradGrad(op, grad): """Gradient for StridedSliceGrad op.""" begin = op.inputs[1] end = op.inputs[2] strides = op.inputs[3] return None, None, None, None, array_ops.strided_slice( grad, begin, end, strides, begin_mask=op.get_attr("begin_mask"), end_mask=op.get_attr("end_mask"), ellipsis_mask=op.get_attr("ellipsis_mask"), new_axis_mask=op.get_attr("new_axis_mask"), shrink_axis_mask=op.get_attr("shrink_axis_mask")) @ops.RegisterGradient("Split") def _SplitGrad(op, *grads): return None, array_ops.concat(list(grads), op.inputs[0]) @ops.RegisterGradient("SplitV") def _SplitVGrad(op, *grads): returnval = array_ops.concat(list(grads), op.inputs[2]) returnval = [returnval] + [ None, ] * ( len(op.inputs) - 1) return returnval ops.NotDifferentiable("Const") @ops.RegisterGradient("Diag") def _DiagGrad(_, grad): return array_ops.diag_part(grad) @ops.RegisterGradient("DiagPart") def _DiagPartGrad(_, grad): return array_ops.diag(grad) @ops.RegisterGradient("MatrixDiag") def _MatrixDiagGrad(_, grad): return array_ops.matrix_diag_part(grad) @ops.RegisterGradient("MatrixDiagPart") def _MatrixDiagPartGrad(op, grad): matrix_shape = op.inputs[0].get_shape()[-2:] if matrix_shape.is_fully_defined() and matrix_shape[0] == matrix_shape[1]: return array_ops.matrix_diag(grad) else: return array_ops.matrix_set_diag(array_ops.zeros_like(op.inputs[0]), grad) @ops.RegisterGradient("MatrixSetDiag") def _MatrixSetDiagGrad(op, grad): """Gradient for MatrixSetDiag.""" input_shape = op.inputs[0].get_shape().merge_with(grad.get_shape()) diag_shape = op.inputs[1].get_shape() batch_shape = input_shape[:-2].merge_with(diag_shape[:-1]) matrix_shape = input_shape[-2:] if batch_shape.is_fully_defined() and matrix_shape.is_fully_defined(): diag_shape = batch_shape.as_list() + [min(matrix_shape.as_list())] else: with ops.colocate_with(grad): grad_shape = array_ops.shape(grad) grad_rank = array_ops.rank(grad) batch_shape = array_ops.slice(grad_shape, [0], [grad_rank - 2]) matrix_shape = array_ops.slice(grad_shape, [grad_rank - 2], [2]) min_dim = math_ops.reduce_min(matrix_shape) diag_shape = array_ops.concat([batch_shape, [min_dim]], 0) grad_input = array_ops.matrix_set_diag(grad, array_ops.zeros( diag_shape, dtype=grad.dtype)) grad_diag = array_ops.matrix_diag_part(grad) return (grad_input, grad_diag) @ops.RegisterGradient("MatrixBandPart") def _MatrixBandPartGrad(op, grad): num_lower = op.inputs[1] num_upper = op.inputs[2] return (array_ops.matrix_band_part(grad, num_lower, num_upper), None, None) # Edit Distance has no gradient (but can be used to eval seq2seq or CTC). ops.NotDifferentiable("EditDistance") @ops.RegisterGradient("Fill") def _FillGrad(_, grad): return None, math_ops.reduce_sum(grad) ops.NotDifferentiable("ZerosLike") ops.NotDifferentiable("OnesLike") @ops.RegisterGradient("PreventGradient") def _PreventGradientGrad(op, _): raise LookupError( "Gradient explicitly disabled. Reason: %s" % op.get_attr("message")) @ops.RegisterGradient("Gather") def _GatherGrad(op, grad): """Gradient for Gather op.""" # params can be large, so colocate the shape calculation with it. # # params can be very large for sparse model, array_ops.shape raises # exception on the Windows platform when any dimension is larger than # int32. params_shape is not used in optimizer apply_sparse gradients, # so it's fine to convert it back to int32 regardless of truncation. params = op.inputs[0] with ops.colocate_with(params): params_shape = array_ops.shape(params, out_type=ops.dtypes.int64) params_shape = math_ops.to_int32(params_shape) # Build appropriately shaped IndexedSlices indices = op.inputs[1] size = array_ops.expand_dims(array_ops.size(indices), 0) values_shape = array_ops.concat([size, params_shape[1:]], 0) values = array_ops.reshape(grad, values_shape) indices = array_ops.reshape(indices, size) return [ops.IndexedSlices(values, indices, params_shape), None] @ops.RegisterGradient("GatherV2") def _GatherV2Grad(op, grad): """Gradient for GatherV2 op.""" # params can be large, so colocate the shape calculation with it. # # params can be very large for sparse model, array_ops.shape raises # exception on the Windows platform when any dimension is larger than # int32. params_shape is not used in optimizer apply_sparse gradients, # so it's fine to convert it back to int32 regardless of truncation. params = op.inputs[0] with ops.colocate_with(params): params_shape = array_ops.shape(params, out_type=ops.dtypes.int64) params_shape = math_ops.to_int32(params_shape) indices = op.inputs[1] indices_size = array_ops.expand_dims(array_ops.size(indices), 0) axis = op.inputs[2] axis_static = tensor_util.constant_value(axis) # For axis 0 gathers, build an appropriately shaped IndexedSlices. if axis_static == 0: if context.executing_eagerly(): params_tail_shape = params_shape.cpu()[1:] else: params_tail_shape = params_shape[1:] values_shape = array_ops.concat([indices_size, params_tail_shape], 0) values = array_ops.reshape(grad, values_shape) indices = array_ops.reshape(indices, indices_size) return [ops.IndexedSlices(values, indices, params_shape), None, None] outer_shape = params_shape[:axis] outer_dims = array_ops.size(outer_shape) inner_shape = params_shape[axis:][1:] inner_dims = array_ops.size(inner_shape) outer_axes_indices = math_ops.range(outer_dims) inner_axes_indices = math_ops.range(outer_dims + 1, outer_dims + 1 + inner_dims) values_shape = array_ops.concat([outer_shape, indices_size, inner_shape], 0) values = array_ops.reshape(grad, values_shape) indices = array_ops.reshape(indices, indices_size) # We need to sum up every slice `values[..., i, ....]` corresponding to # `params[..., indices[i], ...]`. Since `unsorted_segment_sum` does not # support an axis parameter, we transpose the gather dimension to the front, # then use `unsorted_segment_sum` to build a # [gather_axis, outer_axes, inner_axes] tensor with all the gradients # affecting each index in `gather_axis` summed up. transpose_dims = array_ops.concat( [[outer_dims], outer_axes_indices, inner_axes_indices], 0) values_transpose = array_ops.transpose(values, transpose_dims) num_segments = params_shape[axis] params_grad = math_ops.unsorted_segment_sum(values_transpose, indices, num_segments) # Inverts the above transpose by moving dimension 0 back to its original # position. invert_transpose_dims = array_ops.concat( [outer_axes_indices + 1, [0], inner_axes_indices], 0) params_grad = array_ops.transpose(params_grad, invert_transpose_dims) return [params_grad, None, None] @ops.RegisterGradient("GatherNd") def _GatherNdGrad(op, grad): ref = op.inputs[0] indices = op.inputs[1] ref_shape = array_ops.shape(ref, out_type=indices.dtype) if indices.shape.ndims == 2 and indices.shape.dims[-1].value == 1: ref_grad = ops.IndexedSlices(grad, array_ops.squeeze(indices, axis=-1), ref_shape) else: ref_grad = array_ops.scatter_nd(indices, grad, ref_shape) return [ref_grad, None] @ops.RegisterGradient("CheckNumerics") def _CheckNumericsGrad(_, grad): """Gradient for check_numerics op.""" return array_ops.check_numerics( grad, "Not a number (NaN) or infinity (Inf) values detected in gradient.") @ops.RegisterGradient("PlaceholderWithDefault") @ops.RegisterGradient("Identity") def _IdGrad(_, grad): return grad @ops.RegisterGradient("RefIdentity") def _RefIdGrad(_, grad): return grad @ops.RegisterGradient("IdentityN") def _IdNGrad(_, *grad): return grad ops.NotDifferentiable("StopGradient") @ops.RegisterGradient("Reshape") def _ReshapeGrad(op, grad): return [array_ops.reshape(grad, array_ops.shape(op.inputs[0])), None] ops.NotDifferentiable("InvertPermutation") def _ReshapeToInput(op, grad): """Reshapes the gradient to the shape of the original input.""" return array_ops.reshape(grad, array_ops.shape(op.inputs[0])) @ops.RegisterGradient("ExpandDims") def _ExpandDimsGrad(op, grad): return [_ReshapeToInput(op, grad), None] @ops.RegisterGradient("Squeeze") def _SqueezeGrad(op, grad): return _ReshapeToInput(op, grad) @ops.RegisterGradient("Transpose") def _TransposeGrad(op, grad): """Returns unshuffle(grad).""" p = op.inputs[1] return [array_ops.transpose(grad, array_ops.invert_permutation(p)), None] @ops.RegisterGradient("ConjugateTranspose") def _ConjugateTransposeGrad(op, grad): """Returns conj(unshuffle(grad)).""" p = op.inputs[1] return [ array_ops.transpose( grad, array_ops.invert_permutation(p), conjugate=True), None ] ops.NotDifferentiable("Shape") ops.NotDifferentiable("ShapeN") ops.NotDifferentiable("Rank") ops.NotDifferentiable("Size") @ops.RegisterGradient("Tile") def _TileGrad(op, grad): """Sum reduces grad along the tiled dimensions.""" input_shape = array_ops.shape(op.inputs[0]) # We interleave multiples and input_shape to get split_shape, # reshape grad to split_shape, and reduce along all even # dimensions (the tiled dimensions) to get the result # with shape input_shape. For example # input_shape = [20, 30, 40] # multiples = [2, 3, 4] # split_shape = [2, 20, 3, 30, 4, 40] # axes = [0, 2, 4] split_shape = array_ops.reshape( array_ops.transpose(array_ops.stack([op.inputs[1], input_shape])), [-1]) axes = math_ops.range(0, array_ops.size(split_shape), 2) # Sum reduces grad along the first dimension for IndexedSlices if isinstance(grad, ops.IndexedSlices): grad = math_ops.unsorted_segment_sum( grad.values, math_ops.mod(grad.indices, input_shape[0]), input_shape[0]) split_shape = array_ops.concat([[1], split_shape[1:]], axis=0) input_grad = math_ops.reduce_sum(array_ops.reshape(grad, split_shape), axes) # Fix shape inference if not context.executing_eagerly(): input_grad.set_shape(op.inputs[0].get_shape()) return [input_grad, None] ops.NotDifferentiable("BroadcastGradientArgs") def _PadGrad(op, grad): """Gradient for Pad.""" # Pad introduces values around the original tensor, so the gradient function # slices the original shape out of the gradient.""" x = op.inputs[0] a = op.inputs[1] # [Rank(x), 2] # Takes a slice of a. The 1st column. [Rank(x), 1]. pad_before = array_ops.slice(a, [0, 0], array_ops.stack([array_ops.rank(x), 1])) # Make it a 1-D tensor. begin = array_ops.reshape(pad_before, [-1]) sizes = array_ops.shape(x) x_grad = array_ops.slice(grad, begin, sizes) if len(op.inputs) == 3: return x_grad, None, None else: return x_grad, None ops.RegisterGradient("Pad")(_PadGrad) ops.RegisterGradient("PadV2")(_PadGrad) # ReverseSequence is just a permutation. The gradient permutes back. @ops.RegisterGradient("ReverseSequence") def _ReverseSequenceGrad(op, grad): seq_lengths = op.inputs[1] return [ array_ops.reverse_sequence( grad, batch_axis=op.get_attr("batch_dim"), seq_axis=op.get_attr("seq_dim"), seq_lengths=seq_lengths), None ] @ops.RegisterGradient("Reverse") def _ReverseGrad(op, grad): reverse_dims = op.inputs[1] return gen_array_ops.reverse(grad, reverse_dims), None @ops.RegisterGradient("ReverseV2") def _ReverseV2Grad(op, grad): axis = op.inputs[1] return array_ops.reverse_v2(grad, axis), None @ops.RegisterGradient("SpaceToBatch") def _SpaceToBatchGrad(op, grad): # Its gradient is the opposite op: BatchToSpace. block_size = op.get_attr("block_size") return [ array_ops.batch_to_space(grad, op.inputs[1], block_size=block_size), None ] @ops.RegisterGradient("SpaceToBatchND") def _SpaceToBatchNDGrad(op, grad): # Its gradient is the opposite op: BatchToSpaceND. return [ array_ops.batch_to_space_nd(grad, op.inputs[1], op.inputs[2]), None, None ] @ops.RegisterGradient("BatchToSpace") def _BatchToSpaceGrad(op, grad): # Its gradient is the opposite op: SpaceToBatch. block_size = op.get_attr("block_size") return [ array_ops.space_to_batch(grad, op.inputs[1], block_size=block_size), None ] @ops.RegisterGradient("BatchToSpaceND") def _BatchToSpaceNDGrad(op, grad): # Its gradient is the opposite op: SpaceToBatchND. return [ array_ops.space_to_batch_nd(grad, op.inputs[1], op.inputs[2]), None, None ] @ops.RegisterGradient("SpaceToDepth") def _SpaceToDepthGrad(op, grad): # Its gradient is the opposite op: DepthToSpace. block_size = op.get_attr("block_size") data_format = op.get_attr("data_format") if data_format == "NCHW_VECT_C": raise ValueError("Cannot compute SpaceToDepth gradient with NCHW_VECT_C. " "NCHW_VECT_C requires qint8 data type.") return array_ops.depth_to_space(grad, block_size, data_format=data_format) @ops.RegisterGradient("DepthToSpace") def _DepthToSpaceGrad(op, grad): # Its gradient is the opposite op: SpaceToDepth. block_size = op.get_attr("block_size") data_format = op.get_attr("data_format") if data_format == "NCHW_VECT_C": raise ValueError("Cannot compute DepthToSpace gradient with NCHW_VECT_C. " "NCHW_VECT_C requires qint8 data type.") return array_ops.space_to_depth(grad, block_size, data_format=data_format) ops.NotDifferentiable("OneHot") @ops.RegisterGradient("MirrorPad") def _MirrorPadGrad(op, grad): mode = op.get_attr("mode") return [gen_array_ops.mirror_pad_grad(grad, op.inputs[1], mode=mode), None] @ops.RegisterGradient("MirrorPadGrad") def _MirrorPadGradGrad(op, grad): mode = op.get_attr("mode") return [gen_array_ops.mirror_pad(grad, op.inputs[1], mode=mode), None] @ops.RegisterGradient("QuantizeAndDequantize") def _QuantizeAndDequantizeGrad(_, grad): return grad @ops.RegisterGradient("QuantizeAndDequantizeV2") def _QuantizeAndDequantizeV2Grad(_, grad): return [grad, None, None] @ops.RegisterGradient("QuantizeAndDequantizeV3") def _QuantizeAndDequantizeV3Grad(_, grad): # Only propagate the gradient for the unquantized input. return [grad, None, None, None] @ops.RegisterGradient("ExtractImagePatches") def _ExtractImagePatchesGrad(op, grad): batch_size, rows_in, cols_in, channels = [ dim.value for dim in op.inputs[0].shape.dims ] input_bhwc = array_ops.shape(op.inputs[0]) batch_size = input_bhwc[0] channels = input_bhwc[3] # Create indices matrix for input tensor. # Note that 0 is preserved for padding location, # so indices for input start from 1 to 1 + rows_in * cols_in. input_indices_num = 1 + rows_in * cols_in input_idx = array_ops.reshape(math_ops.range(1, input_indices_num, dtype=ops.dtypes.int64), (1, rows_in, cols_in, 1)) input_idx_patched = gen_array_ops.extract_image_patches( input_idx, op.get_attr("ksizes"), op.get_attr("strides"), op.get_attr("rates"), op.get_attr("padding")) # Create indices matrix for output tensor. _, rows_out, cols_out, _ = [dim.value for dim in op.outputs[0].shape.dims] _, ksize_r, ksize_c, _ = op.get_attr("ksizes") # Indices for output start from 0. output_indices_num = rows_out * cols_out * ksize_r * ksize_c output_idx = array_ops.reshape(math_ops.range(output_indices_num, dtype=ops.dtypes.int64), (1, rows_out, cols_out, ksize_r * ksize_c)) # Construct mapping table for indices: (input -> output). idx_matrix = array_ops.concat( [array_ops.expand_dims(input_idx_patched, axis=-1), array_ops.expand_dims(output_idx, axis=-1)], axis=-1) idx_map = array_ops.reshape(idx_matrix, (-1, 2)) sp_shape = (input_indices_num, output_indices_num) sp_mat_full = sparse_tensor.SparseTensor( idx_map, array_ops.ones([output_indices_num], dtype=grad.dtype), sp_shape) # Remove all padding locations [0, :]. sp_mat = sparse_ops.sparse_slice(sp_mat_full, (1, 0), (input_indices_num - 1, output_indices_num)) grad_expanded = array_ops.transpose( array_ops.reshape( grad, (batch_size, rows_out, cols_out, ksize_r, ksize_c, channels)), (1, 2, 3, 4, 0, 5)) grad_flat = array_ops.reshape(grad_expanded, (-1, batch_size * channels)) jac = sparse_ops.sparse_tensor_dense_matmul(sp_mat, grad_flat) grad_out = array_ops.reshape(jac, (rows_in, cols_in, batch_size, channels)) grad_out = array_ops.transpose(grad_out, (2, 0, 1, 3)) return [grad_out] @ops.RegisterGradient("ScatterNd") def _ScatterNdGrad(op, grad): indices = op.inputs[0] updates_grad = array_ops.gather_nd(grad, indices) return [None, updates_grad, None] @ops.RegisterGradient("ScatterNdNonAliasingAdd") def _ScatterNdNonAliasingAddGrad(op, grad): indices = op.inputs[1] updates_grad = array_ops.gather_nd(grad, indices) return [grad, None, updates_grad] @ops.RegisterGradient("BroadcastTo") def _BroadcastToGrad(op, grad): input_value = op.inputs[0] broadcast_shape = op.inputs[1] # Assign ids for each position in input_value. input_value_shape = array_ops.shape(input_value) input_value_size = array_ops.size(input_value) ids = array_ops.reshape(math_ops.range(input_value_size), input_value_shape) broadcast_ids = array_ops.broadcast_to(ids, broadcast_shape) # Group by ids and sum its gradients. grad_flatten = array_ops.reshape(grad, [-1]) broadcast_ids_flatten = array_ops.reshape(broadcast_ids, [-1]) updates_grad_flatten = math_ops.unsorted_segment_sum(grad_flatten, broadcast_ids_flatten, input_value_size) updates_grad = array_ops.reshape(updates_grad_flatten, input_value_shape) return [updates_grad, None]
apache-2.0
leechor/vnpy
vn.ctp/pyscript/generate_struct.py
27
1387
# encoding: UTF-8 __author__ = 'CHENXY' from ctp_data_type import * def main(): """主函数""" fcpp = open('ThostFtdcUserApiStruct.h', 'r') fpy = open('ctp_struct.py', 'w') fpy.write('# encoding: UTF-8\n') fpy.write('\n') fpy.write('structDict = {}\n') fpy.write('\n') for line in fcpp: # 结构体申明注释 if '///' in line and '\t' not in line: py_line = '#' + line[3:] # 结构体变量注释 elif '\t///' in line: py_line = '#' + line[4:] # 结构体申明 elif 'struct' in line: content = line.split(' ') name = content[1].replace('\n','') py_line = '%s = {}\n' % name # 结构体变量 elif '\t' in line and '///' not in line: content = line.split('\t') typedef = content[1] type_ = typedefDict[typedef] variable = content[2].replace(';\n', "") py_line = '%s["%s"] = "%s"\n' % (name, variable, type_) # 结构体结束 elif '}' in line: py_line = "structDict['%s'] = %s\n\n" % (name, name) # 结构体开始 elif '{' in line: py_line = '' # 其他 else: py_line = '\n' fpy.write(py_line.decode('gbk').encode('utf-8')) if __name__ == '__main__': main()
mit
eric-haibin-lin/mxnet
python/mxnet/executor_manager.py
4
17594
# 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. # coding: utf-8 # pylint: disable=invalid-name, protected-access, too-many-locals, too-many-arguments, too-many-statements """Executor manager.""" import logging import numpy as np from .base import mx_real_t from . import ndarray as nd from .context import cpu from .io import DataDesc def _split_input_slice(batch_size, work_load_list): """Get input slice from the input shape. Parameters ---------- batch_size : int The number of samples in a mini-batch. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as `ctx`. Returns ------- slices : list of slice The split slices to get a specific slice. Raises ------ ValueError In case of too many splits, leading to some empty slices. """ total_work_load = sum(work_load_list) batch_num_list = [round(work_load * batch_size / total_work_load) for work_load in work_load_list] batch_num_sum = sum(batch_num_list) if batch_num_sum < batch_size: batch_num_list[-1] += batch_size - batch_num_sum slices = [] end = 0 for batch_num in batch_num_list: begin = int(min((end, batch_size))) end = int(min((begin + batch_num, batch_size))) if begin >= end: raise ValueError('Too many slices. Some splits are empty.') slices.append(slice(begin, end)) return slices def _check_arguments(symbol): """Check the argument names of symbol. This function checks the duplication of arguments in Symbol. The check is done for feedforward net for now. Parameters ---------- symbol : Symbol The network configuration. """ arg_set = set() arg_names = symbol.list_arguments() for name in arg_names: if name in arg_set: raise ValueError(('Find duplicated argument name \"%s\", ' + 'please make the weight name non-duplicated(using name arguments), ' + 'arguments are %s') % (name, str(arg_names))) arg_set.add(name) aux_set = set() aux_names = symbol.list_auxiliary_states() for name in aux_names: if name in aux_set: raise ValueError( ('Find duplicated auxiliary param name \"%s\", ' + 'please make the weight name non-duplicated(using name arguments), ' + 'arguments are %s, auxiliary params are %s' ) % (name, str(arg_names), str(aux_names))) aux_set.add(name) def _load_general(data, targets): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets in zip(data, targets): if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) else: assert d_targets[-1][0].stop == d_src.shape[0], \ "Batch size miss match. Expected %d, got %d"%( \ d_targets[-1][0].stop, d_src.shape[0]) for slice_idx, d_dst in d_targets: d_src[slice_idx].copyto(d_dst) def _load_data(batch, targets): """Load data into sliced arrays.""" _load_general(batch.data, targets) def _load_label(batch, targets): """Load label into sliced arrays.""" _load_general(batch.label, targets) # pylint: disable=too-many-branches def _bind_exec(sym, ctx, input_shapes, param_names, need_grad=False, base_exec=None, shared_data_arrays=None, input_types=None, logger=logging): """bind executor for bucketing, potentially sharing data with an existing executor.""" arg_shape, _, aux_shape = sym.infer_shape(**input_shapes) assert(arg_shape is not None) if input_types is None: input_types = {k: mx_real_t for k in input_shapes.keys()} arg_types, _, aux_types = sym.infer_type(**input_types) assert(arg_types is not None) arg_arrays = [] grad_arrays = {} if need_grad is not False else None arg_names = sym.list_arguments() if need_grad is False: need_grad = set() elif need_grad is True: need_grad = set(arg_names) - set(input_shapes.keys()) elif isinstance(need_grad, set): pass else: raise AssertionError("need_grad must be boolean or set.") grad_req = {name:('write' if name in need_grad else 'null') for name in arg_names} # create or borrow arguments and gradients for i, name in enumerate(arg_names): if not name in param_names: # data or label if shared_data_arrays is not None and \ name in shared_data_arrays: arg_arr = shared_data_arrays[name] if np.prod(arg_arr.shape) >= np.prod(arg_shape[i]): # good, we can share this memory assert(arg_types[i] == arg_arr.dtype) arg_arr = arg_arr.reshape(arg_shape[i]) else: logger.warning(('bucketing: data "%s" has a shape %s' % (name, arg_shape[i])) + (', which is larger than already allocated ') + ('shape %s' % (arg_arr.shape,)) + ('. Need to re-allocate. Consider putting ') + ('default_bucket_key to be the bucket taking the largest ') + ('input for better memory sharing.')) arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) # replace existing shared array because the new one is bigger shared_data_arrays[name] = arg_arr else: arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) if shared_data_arrays is not None: shared_data_arrays[name] = arg_arr arg_arrays.append(arg_arr) else: # model parameter if base_exec is None: arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) if name in need_grad: grad_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) grad_arrays[name] = grad_arr else: arg_arr = base_exec.arg_dict[name] assert arg_arr.shape == arg_shape[i] assert arg_arr.dtype == arg_types[i] if name in need_grad: grad_arrays[name] = base_exec.grad_dict[name] arg_arrays.append(arg_arr) # create or borrow aux variables if base_exec is None: aux_arrays = [nd.zeros(s, ctx, dtype=t) for s, t in zip(aux_shape, aux_types)] else: for i, a in enumerate(base_exec.aux_arrays): assert aux_shape[i] == a.shape assert aux_types[i] == a.dtype aux_arrays = [a for a in base_exec.aux_arrays] executor = sym.bind(ctx=ctx, args=arg_arrays, args_grad=grad_arrays, aux_states=aux_arrays, grad_req=grad_req, shared_exec=base_exec) return executor class DataParallelExecutorGroup(object): """A group of executors living on different devices, for data parallelization. Parameters ---------- sym: Symbol The network configuration. arg_names: list of str Equals `sym.list_arguments()` param_names: list of str List of names of all trainable parameters. ctx: list of Context List of devices for training (data parallelization). slices: list of int Describes how the data parallelization splits data into different devices. train_data: DataIter (or DataBatch) The dataset for training. It could be any object with `provide_data` and `provide_label` properties. Loading of actual data is not necessarily needed at this stage. shared_grop: DataParallelExecutorGroup An existing executor group, if to share parameters with it. """ def __init__(self, sym, arg_names, param_names, ctx, slices, train_data, shared_group=None): # make sure the architecture is valid _check_arguments(sym) if shared_group is None: self.shared_data_arrays = [{} for _ in ctx] else: self.shared_data_arrays = shared_group.shared_data_arrays self.data_names = [x[0] for x in train_data.provide_data] self.label_names = [x[0] for x in train_data.provide_label] self.aux_names = sym.list_auxiliary_states() self.param_idx = [i for i in range(len(arg_names)) if arg_names[i] in param_names] self.param_names = [arg_names[i] for i in self.param_idx] self.train_execs = [] for i, ctxi in enumerate(ctx): data_shapes = {} data_types = {} for x in train_data.provide_data + train_data.provide_label: data_shapes[x[0]] = tuple([slices[i].stop - slices[i].start] + list(x[1][1:])) if isinstance(x, DataDesc): data_types[x.name] = x.dtype else: data_types[x[0]] = mx_real_t shared_exec = None if shared_group is None else shared_group.train_execs[i] train_exec = _bind_exec(sym, ctxi, data_shapes, self.param_names, need_grad=True, base_exec=shared_exec, shared_data_arrays=self.shared_data_arrays[i], input_types=data_types) self.train_execs.append(train_exec) # data structure self.data_arrays = [[(slices[i], e.arg_dict[name]) for i, e in enumerate(self.train_execs)] for name in self.data_names] self.label_arrays = [[(slices[i], e.arg_dict[name]) for i, e in enumerate(self.train_execs)] for name in self.label_names] self.param_arrays = [[e.arg_arrays[i] for e in self.train_execs] for i in self.param_idx] self.grad_arrays = [[e.grad_arrays[i] for e in self.train_execs] for i in self.param_idx] self.aux_arrays = [[e.aux_arrays[i] for e in self.train_execs] for i in range(len(self.aux_names))] self.slices = slices def load_data_batch(self, data_batch): """Load data and labels into arrays.""" _load_data(data_batch, self.data_arrays) _load_label(data_batch, self.label_arrays) def forward(self, is_train=False): """Perform a forward pass on each executor.""" for texec in self.train_execs: texec.forward(is_train=is_train) def backward(self): """Perform a backward pass on each executor.""" for texec in self.train_execs: texec.backward() def update_metric(self, metric, labels, pre_sliced=False): """Update evaluation metric with label and current outputs.""" for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)): if not pre_sliced: labels_slice = [label[islice] for label in labels] else: labels_slice = labels[current_exec] metric.update(labels_slice, texec.outputs) class DataParallelExecutorManager(object): """ Helper class to manage multiple executors for data parallelism. Parameters ---------- symbol : Symbol Output symbol. ctx : list of Context Devices to run on. param_names: list of str Name of all trainable parameters of the network. arg_names: list of str Name of all arguments of the network. aux_names: list of str Name of all auxiliary states of the network. train_data : DataIter Training data iterator. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as ctx. logger : logging logger When not specified, default logger will be used. sym_gen : A function that generate new Symbols depending on different input shapes. Used only for bucketing. """ def __init__(self, symbol, ctx, train_data, arg_names, param_names, aux_names, work_load_list=None, logger=None, sym_gen=None): if logger is None: logger = logging # preparation num_device = len(ctx) logger.info('Start training with %s', str(ctx)) if work_load_list is None: work_load_list = [1] * num_device assert isinstance(work_load_list, list) and len(work_load_list) == num_device, \ "Invalid settings for work load. " slices = _split_input_slice(train_data.batch_size, work_load_list) self.slices = slices self.arg_names = arg_names self.param_names = param_names self.aux_names = aux_names self.ctx = ctx self.execgrp = DataParallelExecutorGroup(symbol, self.arg_names, self.param_names, self.ctx, self.slices, train_data) self.symbol = symbol self.sym_gen = sym_gen self.curr_execgrp = None # this is set when data is loaded if self.sym_gen is not None: self.execgrp_bucket = {train_data.default_bucket_key: self.execgrp} def install_monitor(self, monitor): """Install monitor on all executors.""" if self.sym_gen is not None: raise NotImplementedError("Monitoring is not implemented for bucketing") for train_exec in self.execgrp.train_execs: monitor.install(train_exec) def set_params(self, arg_params, aux_params): """Set parameter and aux values. Parameters ---------- arg_params : list of NDArray Source parameter arrays aux_params : list of NDArray Source aux arrays. """ for texec in self.execgrp.train_execs: texec.copy_params_from(arg_params, aux_params) def copy_to(self, arg_params, aux_params): """ Copy data from each executor to ```arg_params`` and ``aux_params``. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the NDArrays in arg_params and aux_params. """ for name, block in zip(self.param_names, self.param_arrays): weight = sum(w.copyto(cpu()) for w in block) / len(block) weight.astype(arg_params[name].dtype).copyto(arg_params[name]) for name, block in zip(self.aux_names, self.aux_arrays): weight = sum(w.copyto(cpu()) for w in block) / len(block) weight.astype(aux_params[name].dtype).copyto(aux_params[name]) @property def param_arrays(self): """Shared parameter arrays.""" # param arrays should be shared by all executor groups return self.execgrp.param_arrays @property def grad_arrays(self): """Shared gradient arrays.""" # grad arrays should be shared by all executor groups return self.execgrp.grad_arrays @property def aux_arrays(self): """Shared aux states.""" # aux arrays are also shared by all executor groups return self.execgrp.aux_arrays def load_data_batch(self, data_batch): """Load data and labels into arrays.""" if self.sym_gen is not None: key = data_batch.bucket_key if key not in self.execgrp_bucket: # create new bucket entry symbol = self.sym_gen(key) execgrp = DataParallelExecutorGroup(symbol, self.arg_names, self.param_names, self.ctx, self.slices, data_batch, shared_group=self.execgrp) self.execgrp_bucket[key] = execgrp self.curr_execgrp = self.execgrp_bucket[key] else: self.curr_execgrp = self.execgrp self.curr_execgrp.load_data_batch(data_batch) def forward(self, is_train=False): """Run forward on the current executor.""" self.curr_execgrp.forward(is_train=is_train) def backward(self): """Run backward on the current executor.""" self.curr_execgrp.backward() def update_metric(self, metric, labels, pre_sliced=False): """Update metric with the current executor.""" self.curr_execgrp.update_metric(metric, labels, pre_sliced)
apache-2.0
mortada/tensorflow
tensorflow/contrib/keras/python/keras/applications/inception_v3_test.py
52
1591
# 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. # ============================================================================== """Tests for Inception V3 application.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python import keras from tensorflow.python.platform import test class InceptionV3Test(test.TestCase): def test_with_top(self): model = keras.applications.InceptionV3(weights=None) self.assertEqual(model.output_shape, (None, 1000)) def test_no_top(self): model = keras.applications.InceptionV3(weights=None, include_top=False) self.assertEqual(model.output_shape, (None, None, None, 2048)) def test_with_pooling(self): model = keras.applications.InceptionV3(weights=None, include_top=False, pooling='avg') self.assertEqual(model.output_shape, (None, 2048)) if __name__ == '__main__': test.main()
apache-2.0
galaxy001/libtorrent
python_BTL_BitTorrent-5.3-GPL/BTL/ebrpc.py
5
3425
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ### ebrpc ## query = ebencode({'y':'q', 'q':'<method>', 'a':[<params>]) ## response = ebencode({'y':'r', 'r':<return value>}} ## fault = ebencode({'y':'e','c':'<fault code>', 's':'<fault string>' from xmlrpclib import Error, Fault from types import TupleType from BTL.ebencode import ebencode, ebdecode def dump_fault(code, msg): return ebencode({'y':'e', 'c':code, 's':msg}) def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False): if methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if methodname: out = ebencode({'y':'q', 'q':methodname, 'a':params}) elif isinstance(params, Fault): out = ebencode({'y':'e', 'c':params.faultCode, 's':params.faultString}) elif methodresponse: out = ebencode({'y':'r', 'r':params[0]}) else: raise Error("") return out def loads(data): d = ebdecode(data) if d['y'] == 'e': raise Fault(d['c'], d['s']) # the server raised a fault elif d['y'] == 'r': # why is this return value so weird? # because it's the way that loads works in xmlrpclib return (d['r'],), None elif d['y'] == 'q': return d['a'], d['q'] raise ValueError class DFault(Exception): """Indicates an Datagram EBRPC fault package.""" # If you return a DFault with tid=None from within a function called via # twispread's TEBRPC.callRemote then TEBRPC will insert the tid for the call. def __init__(self, faultCode, faultString, tid=None): self.faultCode = faultCode self.faultString = faultString self.tid = tid self.args = (faultCode, faultString) def __repr__(self): return ( "<Fault %s: %s>" % (self.faultCode, repr(self.faultString)) ) ### datagram interface ### has transaction ID as third return valuebt ### slightly different API, returns a tid as third argument in query/response def dumpd(params, methodname=None, methodresponse=None, encoding=None, allow_none=False, tid=None): assert tid is not None, "need a transaction identifier" if methodname: out = ebencode({'y':'q', 't':tid, 'q':methodname, 'a':params}) elif isinstance(params, DFault): out = ebencode({'y':'e', 't':tid, 'c':params.faultCode, 's':params.faultString}) elif methodresponse: out = ebencode({'y':'r', 't':tid, 'r':params}) else: raise Error("") return out def loadd(data): d = ebdecode(data) if d['y'] == 'e': raise DFault(d['c'], d['s'], d['t']) elif d['y'] == 'r': return d['r'], None, d['t'] elif d['y'] == 'q': return d['a'], d['q'], d['t'] raise ValueError
mit
srjoglekar246/sympy
sympy/plotting/pygletplot/plot_window.py
3
4573
from pyglet.gl import * from managed_window import ManagedWindow from plot_camera import PlotCamera from plot_controller import PlotController from time import clock class PlotWindow(ManagedWindow): def __init__(self, plot, **kwargs): """ Named Arguments =============== antialiasing = True True OR False ortho = False True OR False invert_mouse_zoom = False True OR False """ self.plot = plot self.camera = None self._calculating = False self.antialiasing = kwargs.pop('antialiasing', True) self.ortho = kwargs.pop('ortho', False) self.invert_mouse_zoom = kwargs.pop('invert_mouse_zoom', False) self.linewidth = kwargs.pop('linewidth', 1.5) self.title = kwargs.setdefault('caption', "SymPy Plot") self.last_caption_update = 0 self.caption_update_interval = 0.2 self.drawing_first_object = True super(PlotWindow, self).__init__(**kwargs) def setup(self): self.camera = PlotCamera(self, ortho=self.ortho) self.controller = PlotController(self, invert_mouse_zoom=self.invert_mouse_zoom) self.push_handlers(self.controller) glClearColor(1.0, 1.0, 1.0, 0.0) #glClearColor(0.95, 0.95, 0.95, 0.0) glClearDepth(1.0) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glEnable(GL_LINE_SMOOTH) glShadeModel(GL_SMOOTH) glLineWidth(self.linewidth) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if self.antialiasing: glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) #glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE) #glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE) self.camera.setup_projection() def on_resize(self, w, h): super(PlotWindow, self).on_resize(w, h) if self.camera is not None: self.camera.setup_projection() def update(self, dt): self.controller.update(dt) def draw(self): self.plot._render_lock.acquire() self.camera.apply_transformation() calc_verts_pos, calc_verts_len = 0, 0 calc_cverts_pos, calc_cverts_len = 0, 0 should_update_caption = (clock()-self.last_caption_update > self.caption_update_interval) if len(self.plot._functions.values()) == 0: self.drawing_first_object = True for r in self.plot._functions.itervalues(): if self.drawing_first_object: self.camera.set_rot_preset(r.default_rot_preset) self.drawing_first_object = False glPushMatrix() r._draw() glPopMatrix() # might as well do this while we are # iterating and have the lock rather # than locking and iterating twice # per frame: if should_update_caption: try: if r.calculating_verts: calc_verts_pos += r.calculating_verts_pos calc_verts_len += r.calculating_verts_len if r.calculating_cverts: calc_cverts_pos += r.calculating_cverts_pos calc_cverts_len += r.calculating_cverts_len except ValueError: pass for r in self.plot._pobjects: glPushMatrix() r._draw() glPopMatrix() if should_update_caption: self.update_caption(calc_verts_pos, calc_verts_len, calc_cverts_pos, calc_cverts_len) self.last_caption_update = clock() if self.plot._screenshot: self.plot._screenshot._execute_saving() self.plot._render_lock.release() def update_caption(self, calc_verts_pos, calc_verts_len, calc_cverts_pos, calc_cverts_len): caption = self.title if calc_verts_len or calc_cverts_len: caption += " (calculating" if calc_verts_len > 0: p = (calc_verts_pos / calc_verts_len) * 100 caption += " vertices %i%%" % (p) if calc_cverts_len > 0: p = (calc_cverts_pos / calc_cverts_len) * 100 caption += " colors %i%%" % (p) caption += ")" if self.caption != caption: self.set_caption(caption)
bsd-3-clause
yousafsyed/casperjs
bin/Lib/wsgiref/headers.py
145
6682
"""Manage HTTP Response Headers Much of this module is red-handedly pilfered from email.message in the stdlib, so portions are Copyright (C) 2001,2002 Python Software Foundation, and were written by Barry Warsaw. """ # Regular expression that matches `special' characters in parameters, the # existence of which force quoting of the parameter value. import re tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: if quote or tspecials.search(value): value = value.replace('\\', '\\\\').replace('"', r'\"') return '%s="%s"' % (param, value) else: return '%s=%s' % (param, value) else: return param class Headers: """Manage a collection of HTTP response headers""" def __init__(self,headers): if type(headers) is not list: raise TypeError("Headers must be a list of name/value tuples") self._headers = headers if __debug__: for k, v in headers: self._convert_string_type(k) self._convert_string_type(v) def _convert_string_type(self, value): """Convert/check value type.""" if type(value) is str: return value raise AssertionError("Header names/values must be" " of type str (got {0})".format(repr(value))) def __len__(self): """Return the total number of headers, including duplicates.""" return len(self._headers) def __setitem__(self, name, val): """Set the value of a header.""" del self[name] self._headers.append( (self._convert_string_type(name), self._convert_string_type(val))) def __delitem__(self,name): """Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing. """ name = self._convert_string_type(name.lower()) self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] def __getitem__(self,name): """Get the first header value for 'name' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name. """ return self.get(name) def __contains__(self, name): """Return true if the message contains the header.""" return self.get(name) is not None def get_all(self, name): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list. """ name = self._convert_string_type(name.lower()) return [kv[1] for kv in self._headers if kv[0].lower()==name] def get(self,name,default=None): """Get the first header value for 'name', or return 'default'""" name = self._convert_string_type(name.lower()) for k,v in self._headers: if k.lower()==name: return v return default def keys(self): """Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [k for k, v in self._headers] def values(self): """Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [v for k, v in self._headers] def items(self): """Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return self._headers[:] def __repr__(self): return "Headers(%r)" % self._headers def __str__(self): """str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.""" return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) def __bytes__(self): return str(self).encode('iso-8859-1') def setdefault(self,name,value): """Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.""" result = self.get(name) if result is None: self._headers.append((self._convert_string_type(name), self._convert_string_type(value))) return value else: return result def add_header(self, _name, _value, **_params): """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None. """ parts = [] if _value is not None: _value = self._convert_string_type(_value) parts.append(_value) for k, v in _params.items(): k = self._convert_string_type(k) if v is None: parts.append(k.replace('_', '-')) else: v = self._convert_string_type(v) parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((self._convert_string_type(_name), "; ".join(parts)))
mit
ycsoft/FatCat-Server
LIBS/boost_1_58_0/tools/litre/litre.py
10
1967
from docutils import writers from docutils import nodes class LitreTranslator(nodes.GenericNodeVisitor): def __init__(self, document, config): nodes.GenericNodeVisitor.__init__(self,document) self._config = config def default_visit(self, node): pass # print '**visiting:', repr(node) def default_departure(self, node): pass # print '**departing:', repr(node) def visit_raw(self, node): if node.has_key('format'): key = node['format'].lower() if key == 'litre': # This is probably very evil ;-) #if node.has_key('source'): # node.file = node.attributes['source'] self._handle_code(node, node.astext()) raise nodes.SkipNode def visit_comment(self, node): code = node.astext() if code[0] == '@': self._handle_code(node, code[1:].strip()) def _handle_code(self, node, code): start_line = node.line or 0 start_line -= code.count('\n') + 2 # docutils bug workaround? try: self._execute(compile( start_line*'\n' + code, str(node.source), 'exec')) except: print '\n------- begin offending Python source -------' print code print '------- end offending Python source -------' raise def _execute(self, code): """Override this to set up local variable context for code before invoking it """ eval(code) class Writer(writers.Writer): translator = LitreTranslator _config = None def translate(self): visitor = self.translator(self.document, self._config) self.document.walkabout(visitor) self.output = visitor.astext()
mit
bitcity/django-allauth
allauth/socialaccount/providers/orcid/views.py
50
1222
import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import OrcidProvider class OrcidOAuth2Adapter(OAuth2Adapter): provider_id = OrcidProvider.id # http://support.orcid.org/knowledgebase/articles/335483-the-public- # client-orcid-api authorize_url = 'https://orcid.org/oauth/authorize' access_token_url = 'https://pub.orcid.org/oauth/token' profile_url = 'https://pub.orcid.org/v1.1/%s/orcid-profile' def complete_login(self, request, app, token, **kwargs): resp = requests.get(self.profile_url % kwargs['response']['orcid'], params={'access_token': token.token}, headers={'accept': 'application/orcid+json'}) extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(OrcidOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(OrcidOAuth2Adapter)
mit
sv-dev1/odoo
addons/l10n_ma/l10n_ma.py
336
1952
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class l10n_ma_report(osv.osv): _name = 'l10n.ma.report' _description = 'Report for l10n_ma_kzc' _columns = { 'code': fields.char('Code', size=64), 'name': fields.char('Name'), 'line_ids': fields.one2many('l10n.ma.line', 'report_id', 'Lines', copy=True), } _sql_constraints = [ ('code_uniq', 'unique (code)','The code report must be unique !') ] class l10n_ma_line(osv.osv): _name = 'l10n.ma.line' _description = 'Report Lines for l10n_ma' _columns = { 'code': fields.char('Variable Name', size=64), 'definition': fields.char('Definition'), 'name': fields.char('Name'), 'report_id': fields.many2one('l10n.ma.report', 'Report'), } _sql_constraints = [ ('code_uniq', 'unique (code)', 'The variable name must be unique !') ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
brianlsharp/MissionPlanner
Lib/site-packages/numpy/lib/tests/test_io.py
53
49601
import numpy as np import numpy.ma as ma from numpy.ma.testutils import * from numpy.testing import assert_warns import sys import gzip import os import threading from tempfile import mkstemp, NamedTemporaryFile import time from datetime import datetime from numpy.lib._iotools import ConverterError, ConverterLockError, \ ConversionWarning from numpy.compat import asbytes, asbytes_nested, bytes if sys.version_info[0] >= 3: from io import BytesIO def StringIO(s=""): return BytesIO(asbytes(s)) else: from StringIO import StringIO BytesIO = StringIO MAJVER, MINVER = sys.version_info[:2] def strptime(s, fmt=None): """This function is available in the datetime module only from Python >= 2.5. """ if sys.version_info[0] >= 3: return datetime(*time.strptime(s.decode('latin1'), fmt)[:3]) else: return datetime(*time.strptime(s, fmt)[:3]) class RoundtripTest(object): def roundtrip(self, save_func, *args, **kwargs): """ save_func : callable Function used to save arrays to file. file_on_disk : bool If true, store the file on disk, instead of in a string buffer. save_kwds : dict Parameters passed to `save_func`. load_kwds : dict Parameters passed to `numpy.load`. args : tuple of arrays Arrays stored to file. """ save_kwds = kwargs.get('save_kwds', {}) load_kwds = kwargs.get('load_kwds', {}) file_on_disk = kwargs.get('file_on_disk', False) if file_on_disk: # Do not delete the file on windows, because we can't # reopen an already opened file on that platform, so we # need to close the file and reopen it, implying no # automatic deletion. if sys.platform == 'win32' and MAJVER >= 2 and MINVER >= 6: target_file = NamedTemporaryFile(delete=False) else: target_file = NamedTemporaryFile() load_file = target_file.name else: target_file = StringIO() load_file = target_file arr = args save_func(target_file, *arr, **save_kwds) target_file.flush() target_file.seek(0) if sys.platform == 'win32' and not isinstance(target_file, BytesIO): target_file.close() arr_reloaded = np.load(load_file, **load_kwds) self.arr = arr self.arr_reloaded = arr_reloaded def test_array(self): a = np.array([[1, 2], [3, 4]], float) self.roundtrip(a) a = np.array([[1, 2], [3, 4]], int) self.roundtrip(a) a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle) self.roundtrip(a) a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble) self.roundtrip(a) def test_1D(self): a = np.array([1, 2, 3, 4], int) self.roundtrip(a) @np.testing.dec.knownfailureif(sys.platform == 'win32', "Fail on Win32") def test_mmap(self): a = np.array([[1, 2.5], [4, 7.3]]) self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'}) def test_record(self): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) self.roundtrip(a) class TestSaveLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): RoundtripTest.roundtrip(self, np.save, *args, **kwargs) assert_equal(self.arr[0], self.arr_reloaded) class TestSavezLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): RoundtripTest.roundtrip(self, np.savez, *args, **kwargs) for n, arr in enumerate(self.arr): assert_equal(arr, self.arr_reloaded['arr_%d' % n]) def test_multiple_arrays(self): a = np.array([[1, 2], [3, 4]], float) b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex) self.roundtrip(a, b) def test_named_arrays(self): a = np.array([[1, 2], [3, 4]], float) b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex) c = StringIO() np.savez(c, file_a=a, file_b=b) c.seek(0) l = np.load(c) assert_equal(a, l['file_a']) assert_equal(b, l['file_b']) def test_savez_filename_clashes(self): if hasattr(sys, 'gettotalrefcount'): # skip this test when Python was compiled using # the --with-pydebug option return # Test that issue #852 is fixed # and savez functions in multithreaded environment def writer(error_list): fd, tmp = mkstemp(suffix='.npz') os.close(fd) try: arr = np.random.randn(500, 500) try: np.savez(tmp, arr=arr) except OSError, err: error_list.append(err) finally: os.remove(tmp) errors = [] threads = [threading.Thread(target=writer, args=(errors,)) for j in xrange(3)] for t in threads: t.start() for t in threads: t.join() if errors: raise AssertionError(errors) class TestSaveTxt(TestCase): def test_array(self): a = np.array([[1, 2], [3, 4]], float) fmt = "%.18e" c = StringIO() np.savetxt(c, a, fmt=fmt) c.seek(0) assert_equal(c.readlines(), asbytes_nested( [(fmt + ' ' + fmt + '\n') % (1, 2), (fmt + ' ' + fmt + '\n') % (3, 4)])) a = np.array([[1, 2], [3, 4]], int) c = StringIO() np.savetxt(c, a, fmt='%d') c.seek(0) assert_equal(c.readlines(), asbytes_nested(['1 2\n', '3 4\n'])) def test_1D(self): a = np.array([1, 2, 3, 4], int) c = StringIO() np.savetxt(c, a, fmt='%d') c.seek(0) lines = c.readlines() assert_equal(lines, asbytes_nested(['1\n', '2\n', '3\n', '4\n'])) def test_record(self): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) c = StringIO() np.savetxt(c, a, fmt='%d') c.seek(0) assert_equal(c.readlines(), asbytes_nested(['1 2\n', '3 4\n'])) def test_delimiter(self): a = np.array([[1., 2.], [3., 4.]]) c = StringIO() np.savetxt(c, a, delimiter=asbytes(','), fmt='%d') c.seek(0) assert_equal(c.readlines(), asbytes_nested(['1,2\n', '3,4\n'])) def test_format(self): a = np.array([(1, 2), (3, 4)]) c = StringIO() # Sequence of formats np.savetxt(c, a, fmt=['%02d', '%3.1f']) c.seek(0) assert_equal(c.readlines(), asbytes_nested(['01 2.0\n', '03 4.0\n'])) # A single multiformat string c = StringIO() np.savetxt(c, a, fmt='%02d : %3.1f') c.seek(0) lines = c.readlines() assert_equal(lines, asbytes_nested(['01 : 2.0\n', '03 : 4.0\n'])) # Specify delimiter, should be overiden c = StringIO() np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',') c.seek(0) lines = c.readlines() assert_equal(lines, asbytes_nested(['01 : 2.0\n', '03 : 4.0\n'])) def test_file_roundtrip(self): f, name = mkstemp() os.close(f) try: a = np.array([(1, 2), (3, 4)]) np.savetxt(name, a) b = np.loadtxt(name) assert_array_equal(a, b) finally: os.unlink(name) class TestLoadTxt(TestCase): def test_record(self): c = StringIO() c.write(asbytes('1 2\n3 4')) c.seek(0) x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)]) a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) assert_array_equal(x, a) d = StringIO() d.write(asbytes('M 64.0 75.0\nF 25.0 60.0')) d.seek(0) mydescriptor = {'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')} b = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=mydescriptor) y = np.loadtxt(d, dtype=mydescriptor) assert_array_equal(y, b) def test_array(self): c = StringIO() c.write(asbytes('1 2\n3 4')) c.seek(0) x = np.loadtxt(c, dtype=int) a = np.array([[1, 2], [3, 4]], int) assert_array_equal(x, a) c.seek(0) x = np.loadtxt(c, dtype=float) a = np.array([[1, 2], [3, 4]], float) assert_array_equal(x, a) def test_1D(self): c = StringIO() c.write(asbytes('1\n2\n3\n4\n')) c.seek(0) x = np.loadtxt(c, dtype=int) a = np.array([1, 2, 3, 4], int) assert_array_equal(x, a) c = StringIO() c.write(asbytes('1,2,3,4\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',') a = np.array([1, 2, 3, 4], int) assert_array_equal(x, a) def test_missing(self): c = StringIO() c.write(asbytes('1,2,3,,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}) a = np.array([1, 2, 3, -999, 5], int) assert_array_equal(x, a) def test_converters_with_usecols(self): c = StringIO() c.write(asbytes('1,2,3,,5\n6,7,8,9,10\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}, \ usecols=(1, 3,)) a = np.array([[2, -999], [7, 9]], int) assert_array_equal(x, a) def test_comments(self): c = StringIO() c.write(asbytes('# comment\n1,2,3,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ comments='#') a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) def test_skiprows(self): c = StringIO() c.write(asbytes('comment\n1,2,3,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ skiprows=1) a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) c = StringIO() c.write(asbytes('# comment\n1,2,3,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ skiprows=1) a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) def test_usecols(self): a = np.array([[1, 2], [3, 4]], float) c = StringIO() np.savetxt(c, a) c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1,)) assert_array_equal(x, a[:, 1]) a = np.array([[1, 2, 3], [3, 4, 5]], float) c = StringIO() np.savetxt(c, a) c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1, 2)) assert_array_equal(x, a[:, 1:]) # Testing with arrays instead of tuples. c.seek(0) x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2])) assert_array_equal(x, a[:, 1:]) # Checking with dtypes defined converters. data = '''JOE 70.1 25.3 BOB 60.5 27.9 ''' c = StringIO(data) names = ['stid', 'temp'] dtypes = ['S4', 'f8'] arr = np.loadtxt(c, usecols=(0, 2), dtype=zip(names, dtypes)) assert_equal(arr['stid'], asbytes_nested(["JOE", "BOB"])) assert_equal(arr['temp'], [25.3, 27.9]) def test_fancy_dtype(self): c = StringIO() c.write(asbytes('1,2,3.0\n4,5,6.0\n')) c.seek(0) dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) x = np.loadtxt(c, dtype=dt, delimiter=',') a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt) assert_array_equal(x, a) def test_shaped_dtype(self): c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 3))]) x = np.loadtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], dtype=dt) assert_array_equal(x, a) def test_empty_file(self): c = StringIO() assert_raises(IOError, np.loadtxt, c) def test_unused_converter(self): c = StringIO() c.writelines([asbytes('1 21\n'), asbytes('3 42\n')]) c.seek(0) data = np.loadtxt(c, usecols=(1,), converters={0: lambda s: int(s, 16)}) assert_array_equal(data, [21, 42]) c.seek(0) data = np.loadtxt(c, usecols=(1,), converters={1: lambda s: int(s, 16)}) assert_array_equal(data, [33, 66]) def test_dtype_with_object(self): "Test using an explicit dtype with an object" from datetime import date import time data = """ 1; 2001-01-01 2; 2002-01-31 """ ndtype = [('idx', int), ('code', np.object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.loadtxt(StringIO(data), delimiter=";", dtype=ndtype, converters=converters) control = np.array([(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))], dtype=ndtype) assert_equal(test, control) def test_universal_newline(self): f, name = mkstemp() os.write(f, asbytes('1 21\r3 42\r')) os.close(f) try: data = np.loadtxt(name) assert_array_equal(data, [[1, 21], [3, 42]]) finally: os.unlink(name) class Testfromregex(TestCase): def test_record(self): c = StringIO() c.write(asbytes('1.312 foo\n1.534 bar\n4.444 qux')) c.seek(0) dt = [('num', np.float64), ('val', 'S3')] x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt) a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')], dtype=dt) assert_array_equal(x, a) def test_record_2(self): c = StringIO() c.write(asbytes('1312 foo\n1534 bar\n4444 qux')) c.seek(0) dt = [('num', np.int32), ('val', 'S3')] x = np.fromregex(c, r"(\d+)\s+(...)", dt) a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')], dtype=dt) assert_array_equal(x, a) def test_record_3(self): c = StringIO() c.write(asbytes('1312 foo\n1534 bar\n4444 qux')) c.seek(0) dt = [('num', np.float64)] x = np.fromregex(c, r"(\d+)\s+...", dt) a = np.array([(1312,), (1534,), (4444,)], dtype=dt) assert_array_equal(x, a) #####-------------------------------------------------------------------------- class TestFromTxt(TestCase): # def test_record(self): "Test w/ explicit dtype" data = StringIO(asbytes('1 2\n3 4')) # data.seek(0) test = np.ndfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)]) control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) assert_equal(test, control) # data = StringIO('M 64.0 75.0\nF 25.0 60.0') # data.seek(0) descriptor = {'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')} control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=descriptor) test = np.ndfromtxt(data, dtype=descriptor) assert_equal(test, control) def test_array(self): "Test outputing a standard ndarray" data = StringIO('1 2\n3 4') control = np.array([[1, 2], [3, 4]], dtype=int) test = np.ndfromtxt(data, dtype=int) assert_array_equal(test, control) # data.seek(0) control = np.array([[1, 2], [3, 4]], dtype=float) test = np.loadtxt(data, dtype=float) assert_array_equal(test, control) def test_1D(self): "Test squeezing to 1D" control = np.array([1, 2, 3, 4], int) # data = StringIO('1\n2\n3\n4\n') test = np.ndfromtxt(data, dtype=int) assert_array_equal(test, control) # data = StringIO('1,2,3,4\n') test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(',')) assert_array_equal(test, control) def test_comments(self): "Test the stripping of comments" control = np.array([1, 2, 3, 5], int) # Comment on its own line data = StringIO('# comment\n1,2,3,5\n') test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(','), comments=asbytes('#')) assert_equal(test, control) # Comment at the end of a line data = StringIO('1,2,3,5# comment\n') test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(','), comments=asbytes('#')) assert_equal(test, control) def test_skiprows(self): "Test row skipping" control = np.array([1, 2, 3, 5], int) kwargs = dict(dtype=int, delimiter=asbytes(',')) # data = StringIO('comment\n1,2,3,5\n') test = np.ndfromtxt(data, skip_header=1, **kwargs) assert_equal(test, control) # data = StringIO('# comment\n1,2,3,5\n') test = np.loadtxt(data, skiprows=1, **kwargs) assert_equal(test, control) def test_skip_footer(self): data = ["# %i" % i for i in range(1, 6)] data.append("A, B, C") data.extend(["%i,%3.1f,%03s" % (i, i, i) for i in range(51)]) data[-1] = "99,99" kwargs = dict(delimiter=",", names=True, skip_header=5, skip_footer=10) test = np.genfromtxt(StringIO(asbytes("\n".join(data))), **kwargs) ctrl = np.array([("%f" % i, "%f" % i, "%f" % i) for i in range(41)], dtype=[(_, float) for _ in "ABC"]) assert_equal(test, ctrl) def test_skip_footer_with_invalid(self): import warnings basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' warnings.filterwarnings("ignore") # Footer too small to get rid of all invalid values assert_raises(ValueError, np.genfromtxt, StringIO(basestr), skip_footer=1) # except ValueError: # pass a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) # a = np.genfromtxt(StringIO(basestr), skip_footer=3) assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])) # basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n' a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False) assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]])) a = np.genfromtxt(StringIO(basestr), skip_footer=3, invalid_raise=False) assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]])) warnings.resetwarnings() def test_header(self): "Test retrieving a header" data = StringIO('gender age weight\nM 64.0 75.0\nF 25.0 60.0') test = np.ndfromtxt(data, dtype=None, names=True) control = {'gender': np.array(asbytes_nested(['M', 'F'])), 'age': np.array([64.0, 25.0]), 'weight': np.array([75.0, 60.0])} assert_equal(test['gender'], control['gender']) assert_equal(test['age'], control['age']) assert_equal(test['weight'], control['weight']) def test_auto_dtype(self): "Test the automatic definition of the output dtype" data = StringIO('A 64 75.0 3+4j True\nBCD 25 60.0 5+6j False') test = np.ndfromtxt(data, dtype=None) control = [np.array(asbytes_nested(['A', 'BCD'])), np.array([64, 25]), np.array([75.0, 60.0]), np.array([3 + 4j, 5 + 6j]), np.array([True, False]), ] assert_equal(test.dtype.names, ['f0', 'f1', 'f2', 'f3', 'f4']) for (i, ctrl) in enumerate(control): assert_equal(test['f%i' % i], ctrl) def test_auto_dtype_uniform(self): "Tests whether the output dtype can be uniformized" data = StringIO('1 2 3 4\n5 6 7 8\n') test = np.ndfromtxt(data, dtype=None) control = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) assert_equal(test, control) def test_fancy_dtype(self): "Check that a nested dtype isn't MIA" data = StringIO('1,2,3.0\n4,5,6.0\n') fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) test = np.ndfromtxt(data, dtype=fancydtype, delimiter=',') control = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype) assert_equal(test, control) def test_names_overwrite(self): "Test overwriting the names of the dtype" descriptor = {'names': ('g', 'a', 'w'), 'formats': ('S1', 'i4', 'f4')} data = StringIO('M 64.0 75.0\nF 25.0 60.0') names = ('gender', 'age', 'weight') test = np.ndfromtxt(data, dtype=descriptor, names=names) descriptor['names'] = names control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=descriptor) assert_equal(test, control) def test_commented_header(self): "Check that names can be retrieved even if the line is commented out." data = StringIO(""" #gender age weight M 21 72.100000 F 35 58.330000 M 33 21.99 """) # The # is part of the first name and should be deleted automatically. test = np.genfromtxt(data, names=True, dtype=None) ctrl = np.array([('M', 21, 72.1), ('F', 35, 58.33), ('M', 33, 21.99)], dtype=[('gender', '|S1'), ('age', int), ('weight', float)]) assert_equal(test, ctrl) # Ditto, but we should get rid of the first element data = StringIO(""" # gender age weight M 21 72.100000 F 35 58.330000 M 33 21.99 """) test = np.genfromtxt(data, names=True, dtype=None) assert_equal(test, ctrl) def test_autonames_and_usecols(self): "Tests names and usecols" data = StringIO('A B C D\n aaaa 121 45 9.1') test = np.ndfromtxt(data, usecols=('A', 'C', 'D'), names=True, dtype=None) control = np.array(('aaaa', 45, 9.1), dtype=[('A', '|S4'), ('C', int), ('D', float)]) assert_equal(test, control) def test_converters_with_usecols(self): "Test the combination user-defined converters and usecol" data = StringIO('1,2,3,,5\n6,7,8,9,10\n') test = np.ndfromtxt(data, dtype=int, delimiter=',', converters={3:lambda s: int(s or - 999)}, usecols=(1, 3,)) control = np.array([[2, -999], [7, 9]], int) assert_equal(test, control) def test_converters_with_usecols_and_names(self): "Tests names and usecols" data = StringIO('A B C D\n aaaa 121 45 9.1') test = np.ndfromtxt(data, usecols=('A', 'C', 'D'), names=True, dtype=None, converters={'C':lambda s: 2 * int(s)}) control = np.array(('aaaa', 90, 9.1), dtype=[('A', '|S4'), ('C', int), ('D', float)]) assert_equal(test, control) def test_converters_cornercases(self): "Test the conversion to datetime." converter = {'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')} data = StringIO('2009-02-03 12:00:00Z, 72214.0') test = np.ndfromtxt(data, delimiter=',', dtype=None, names=['date', 'stid'], converters=converter) control = np.array((datetime(2009, 02, 03), 72214.), dtype=[('date', np.object_), ('stid', float)]) assert_equal(test, control) def test_unused_converter(self): "Test whether unused converters are forgotten" data = StringIO("1 21\n 3 42\n") test = np.ndfromtxt(data, usecols=(1,), converters={0: lambda s: int(s, 16)}) assert_equal(test, [21, 42]) # data.seek(0) test = np.ndfromtxt(data, usecols=(1,), converters={1: lambda s: int(s, 16)}) assert_equal(test, [33, 66]) def test_invalid_converter(self): strip_rand = lambda x : float((asbytes('r') in x.lower() and x.split()[-1]) or (not asbytes('r') in x.lower() and x.strip() or 0.0)) strip_per = lambda x : float((asbytes('%') in x.lower() and x.split()[0]) or (not asbytes('%') in x.lower() and x.strip() or 0.0)) s = StringIO("D01N01,10/1/2003 ,1 %,R 75,400,600\r\n" \ "L24U05,12/5/2003, 2 %,1,300, 150.5\r\n" "D02N03,10/10/2004,R 1,,7,145.55") kwargs = dict(converters={2 : strip_per, 3 : strip_rand}, delimiter=",", dtype=None) assert_raises(ConverterError, np.genfromtxt, s, **kwargs) def test_tricky_converter_bug1666(self): "Test some corner case" s = StringIO('q1,2\nq3,4') cnv = lambda s:float(s[1:]) test = np.genfromtxt(s, delimiter=',', converters={0:cnv}) control = np.array([[1., 2.], [3., 4.]]) assert_equal(test, control) def test_dtype_with_converters(self): dstr = "2009; 23; 46" test = np.ndfromtxt(StringIO(dstr,), delimiter=";", dtype=float, converters={0:bytes}) control = np.array([('2009', 23., 46)], dtype=[('f0', '|S4'), ('f1', float), ('f2', float)]) assert_equal(test, control) test = np.ndfromtxt(StringIO(dstr,), delimiter=";", dtype=float, converters={0:float}) control = np.array([2009., 23., 46],) assert_equal(test, control) def test_dtype_with_object(self): "Test using an explicit dtype with an object" from datetime import date import time data = asbytes(""" 1; 2001-01-01 2; 2002-01-31 """) ndtype = [('idx', int), ('code', np.object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.genfromtxt(StringIO(data), delimiter=";", dtype=ndtype, converters=converters) control = np.array([(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))], dtype=ndtype) assert_equal(test, control) # ndtype = [('nest', [('idx', int), ('code', np.object)])] try: test = np.genfromtxt(StringIO(data), delimiter=";", dtype=ndtype, converters=converters) except NotImplementedError: pass else: errmsg = "Nested dtype involving objects should be supported." raise AssertionError(errmsg) def test_userconverters_with_explicit_dtype(self): "Test user_converters w/ explicit (standard) dtype" data = StringIO('skip,skip,2001-01-01,1.0,skip') test = np.genfromtxt(data, delimiter=",", names=None, dtype=float, usecols=(2, 3), converters={2: bytes}) control = np.array([('2001-01-01', 1.)], dtype=[('', '|S10'), ('', float)]) assert_equal(test, control) def test_spacedelimiter(self): "Test space delimiter" data = StringIO("1 2 3 4 5\n6 7 8 9 10") test = np.ndfromtxt(data) control = np.array([[ 1., 2., 3., 4., 5.], [ 6., 7., 8., 9., 10.]]) assert_equal(test, control) def test_integer_delimiter(self): "Test using an integer for delimiter" data = " 1 2 3\n 4 5 67\n890123 4" test = np.genfromtxt(StringIO(data), delimiter=3) control = np.array([[1, 2, 3], [4, 5, 67], [890, 123, 4]]) assert_equal(test, control) def test_missing(self): data = StringIO('1,2,3,,5\n') test = np.ndfromtxt(data, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}) control = np.array([1, 2, 3, -999, 5], int) assert_equal(test, control) def test_missing_with_tabs(self): "Test w/ a delimiter tab" txt = "1\t2\t3\n\t2\t\n1\t\t3" test = np.genfromtxt(StringIO(txt), delimiter="\t", usemask=True,) ctrl_d = np.array([(1, 2, 3), (np.nan, 2, np.nan), (1, np.nan, 3)],) ctrl_m = np.array([(0, 0, 0), (1, 0, 1), (0, 1, 0)], dtype=bool) assert_equal(test.data, ctrl_d) assert_equal(test.mask, ctrl_m) def test_usecols(self): "Test the selection of columns" # Select 1 column control = np.array([[1, 2], [3, 4]], float) data = StringIO() np.savetxt(data, control) data.seek(0) test = np.ndfromtxt(data, dtype=float, usecols=(1,)) assert_equal(test, control[:, 1]) # control = np.array([[1, 2, 3], [3, 4, 5]], float) data = StringIO() np.savetxt(data, control) data.seek(0) test = np.ndfromtxt(data, dtype=float, usecols=(1, 2)) assert_equal(test, control[:, 1:]) # Testing with arrays instead of tuples. data.seek(0) test = np.ndfromtxt(data, dtype=float, usecols=np.array([1, 2])) assert_equal(test, control[:, 1:]) def test_usecols_as_css(self): "Test giving usecols with a comma-separated string" data = "1 2 3\n4 5 6" test = np.genfromtxt(StringIO(data), names="a, b, c", usecols="a, c") ctrl = np.array([(1, 3), (4, 6)], dtype=[(_, float) for _ in "ac"]) assert_equal(test, ctrl) def test_usecols_with_structured_dtype(self): "Test usecols with an explicit structured dtype" data = StringIO("""JOE 70.1 25.3\nBOB 60.5 27.9""") names = ['stid', 'temp'] dtypes = ['S4', 'f8'] test = np.ndfromtxt(data, usecols=(0, 2), dtype=zip(names, dtypes)) assert_equal(test['stid'], asbytes_nested(["JOE", "BOB"])) assert_equal(test['temp'], [25.3, 27.9]) def test_usecols_with_integer(self): "Test usecols with an integer" test = np.genfromtxt(StringIO("1 2 3\n4 5 6"), usecols=0) assert_equal(test, np.array([1., 4.])) def test_usecols_with_named_columns(self): "Test usecols with named columns" ctrl = np.array([(1, 3), (4, 6)], dtype=[('a', float), ('c', float)]) data = "1 2 3\n4 5 6" kwargs = dict(names="a, b, c") test = np.genfromtxt(StringIO(data), usecols=(0, -1), **kwargs) assert_equal(test, ctrl) test = np.genfromtxt(StringIO(data), usecols=('a', 'c'), **kwargs) assert_equal(test, ctrl) def test_empty_file(self): "Test that an empty file raises the proper exception" data = StringIO() assert_raises(IOError, np.ndfromtxt, data) def test_fancy_dtype_alt(self): "Check that a nested dtype isn't MIA" data = StringIO('1,2,3.0\n4,5,6.0\n') fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) test = np.mafromtxt(data, dtype=fancydtype, delimiter=',') control = ma.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype) assert_equal(test, control) def test_shaped_dtype(self): c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 3))]) x = np.ndfromtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], dtype=dt) assert_array_equal(x, a) def test_withmissing(self): data = StringIO('A,B\n0,1\n2,N/A') kwargs = dict(delimiter=",", missing_values="N/A", names=True) test = np.mafromtxt(data, dtype=None, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.int), ('B', np.int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # data.seek(0) test = np.mafromtxt(data, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.float), ('B', np.float)]) assert_equal(test, control) assert_equal(test.mask, control.mask) def test_user_missing_values(self): data = "A, B, C\n0, 0., 0j\n1, N/A, 1j\n-9, 2.2, N/A\n3, -99, 3j" basekwargs = dict(dtype=None, delimiter=",", names=True,) mdtype = [('A', int), ('B', float), ('C', complex)] # test = np.mafromtxt(StringIO(data), missing_values="N/A", **basekwargs) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)], dtype=mdtype) assert_equal(test, control) # basekwargs['dtype'] = mdtype test = np.mafromtxt(StringIO(data), missing_values={0:-9, 1:-99, 2:-999j}, **basekwargs) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)], dtype=mdtype) assert_equal(test, control) # test = np.mafromtxt(StringIO(data), missing_values={0:-9, 'B':-99, 'C':-999j}, **basekwargs) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)], dtype=mdtype) assert_equal(test, control) def test_user_filling_values(self): "Test with missing and filling values" ctrl = np.array([(0, 3), (4, -999)], dtype=[('a', int), ('b', int)]) data = "N/A, 2, 3\n4, ,???" kwargs = dict(delimiter=",", dtype=int, names="a,b,c", missing_values={0:"N/A", 'b':" ", 2:"???"}, filling_values={0:0, 'b':0, 2:-999}) test = np.genfromtxt(StringIO(data), **kwargs) ctrl = np.array([(0, 2, 3), (4, 0, -999)], dtype=[(_, int) for _ in "abc"]) assert_equal(test, ctrl) # test = np.genfromtxt(StringIO(data), usecols=(0, -1), **kwargs) ctrl = np.array([(0, 3), (4, -999)], dtype=[(_, int) for _ in "ac"]) assert_equal(test, ctrl) def test_withmissing_float(self): data = StringIO('A,B\n0,1.5\n2,-999.00') test = np.mafromtxt(data, dtype=None, delimiter=',', missing_values='-999.0', names=True,) control = ma.array([(0, 1.5), (2, -1.)], mask=[(False, False), (False, True)], dtype=[('A', np.int), ('B', np.float)]) assert_equal(test, control) assert_equal(test.mask, control.mask) def test_with_masked_column_uniform(self): "Test masked column" data = StringIO('1 2 3\n4 5 6\n') test = np.genfromtxt(data, dtype=None, missing_values='2,5', usemask=True) control = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[0, 1, 0], [0, 1, 0]]) assert_equal(test, control) def test_with_masked_column_various(self): "Test masked column" data = StringIO('True 2 3\nFalse 5 6\n') test = np.genfromtxt(data, dtype=None, missing_values='2,5', usemask=True) control = ma.array([(1, 2, 3), (0, 5, 6)], mask=[(0, 1, 0), (0, 1, 0)], dtype=[('f0', bool), ('f1', bool), ('f2', int)]) assert_equal(test, control) def test_invalid_raise(self): "Test invalid raise" data = ["1, 1, 1, 1, 1"] * 50 for i in range(5): data[10 * i] = "2, 2, 2, 2 2" data.insert(0, "a, b, c, d, e") mdata = StringIO("\n".join(data)) # kwargs = dict(delimiter=",", dtype=None, names=True) # XXX: is there a better way to get the return value of the callable in # assert_warns ? ret = {} def f(_ret={}): _ret['mtest'] = np.ndfromtxt(mdata, invalid_raise=False, **kwargs) assert_warns(ConversionWarning, f, _ret=ret) mtest = ret['mtest'] assert_equal(len(mtest), 45) assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde'])) # mdata.seek(0) assert_raises(ValueError, np.ndfromtxt, mdata, delimiter=",", names=True) def test_invalid_raise_with_usecols(self): "Test invalid_raise with usecols" data = ["1, 1, 1, 1, 1"] * 50 for i in range(5): data[10 * i] = "2, 2, 2, 2 2" data.insert(0, "a, b, c, d, e") mdata = StringIO("\n".join(data)) kwargs = dict(delimiter=",", dtype=None, names=True, invalid_raise=False) # XXX: is there a better way to get the return value of the callable in # assert_warns ? ret = {} def f(_ret={}): _ret['mtest'] = np.ndfromtxt(mdata, usecols=(0, 4), **kwargs) assert_warns(ConversionWarning, f, _ret=ret) mtest = ret['mtest'] assert_equal(len(mtest), 45) assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae'])) # mdata.seek(0) mtest = np.ndfromtxt(mdata, usecols=(0, 1), **kwargs) assert_equal(len(mtest), 50) control = np.ones(50, dtype=[(_, int) for _ in 'ab']) control[[10 * _ for _ in range(5)]] = (2, 2) assert_equal(mtest, control) def test_inconsistent_dtype(self): "Test inconsistent dtype" data = ["1, 1, 1, 1, -1.1"] * 50 mdata = StringIO("\n".join(data)) converters = {4: lambda x:"(%s)" % x} kwargs = dict(delimiter=",", converters=converters, dtype=[(_, int) for _ in 'abcde'],) assert_raises(TypeError, np.genfromtxt, mdata, **kwargs) def test_default_field_format(self): "Test default format" data = "0, 1, 2.3\n4, 5, 6.7" mtest = np.ndfromtxt(StringIO(data), delimiter=",", dtype=None, defaultfmt="f%02i") ctrl = np.array([(0, 1, 2.3), (4, 5, 6.7)], dtype=[("f00", int), ("f01", int), ("f02", float)]) assert_equal(mtest, ctrl) def test_single_dtype_wo_names(self): "Test single dtype w/o names" data = "0, 1, 2.3\n4, 5, 6.7" mtest = np.ndfromtxt(StringIO(data), delimiter=",", dtype=float, defaultfmt="f%02i") ctrl = np.array([[0., 1., 2.3], [4., 5., 6.7]], dtype=float) assert_equal(mtest, ctrl) def test_single_dtype_w_explicit_names(self): "Test single dtype w explicit names" data = "0, 1, 2.3\n4, 5, 6.7" mtest = np.ndfromtxt(StringIO(data), delimiter=",", dtype=float, names="a, b, c") ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)], dtype=[(_, float) for _ in "abc"]) assert_equal(mtest, ctrl) def test_single_dtype_w_implicit_names(self): "Test single dtype w implicit names" data = "a, b, c\n0, 1, 2.3\n4, 5, 6.7" mtest = np.ndfromtxt(StringIO(data), delimiter=",", dtype=float, names=True) ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)], dtype=[(_, float) for _ in "abc"]) assert_equal(mtest, ctrl) def test_easy_structured_dtype(self): "Test easy structured dtype" data = "0, 1, 2.3\n4, 5, 6.7" mtest = np.ndfromtxt(StringIO(data), delimiter=",", dtype=(int, float, float), defaultfmt="f_%02i") ctrl = np.array([(0, 1., 2.3), (4, 5., 6.7)], dtype=[("f_00", int), ("f_01", float), ("f_02", float)]) assert_equal(mtest, ctrl) def test_autostrip(self): "Test autostrip" data = "01/01/2003 , 1.3, abcde" kwargs = dict(delimiter=",", dtype=None) mtest = np.ndfromtxt(StringIO(data), **kwargs) ctrl = np.array([('01/01/2003 ', 1.3, ' abcde')], dtype=[('f0', '|S12'), ('f1', float), ('f2', '|S8')]) assert_equal(mtest, ctrl) mtest = np.ndfromtxt(StringIO(data), autostrip=True, **kwargs) ctrl = np.array([('01/01/2003', 1.3, 'abcde')], dtype=[('f0', '|S10'), ('f1', float), ('f2', '|S5')]) assert_equal(mtest, ctrl) def test_replace_space(self): "Test the 'replace_space' option" txt = "A.A, B (B), C:C\n1, 2, 3.14" # Test default: replace ' ' by '_' and delete non-alphanum chars test = np.genfromtxt(StringIO(txt), delimiter=",", names=True, dtype=None) ctrl_dtype = [("AA", int), ("B_B", int), ("CC", float)] ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype) assert_equal(test, ctrl) # Test: no replace, no delete test = np.genfromtxt(StringIO(txt), delimiter=",", names=True, dtype=None, replace_space='', deletechars='') ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", float)] ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype) assert_equal(test, ctrl) # Test: no delete (spaces are replaced by _) test = np.genfromtxt(StringIO(txt), delimiter=",", names=True, dtype=None, deletechars='') ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", float)] ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype) assert_equal(test, ctrl) def test_incomplete_names(self): "Test w/ incomplete names" data = "A,,C\n0,1,2\n3,4,5" kwargs = dict(delimiter=",", names=True) # w/ dtype=None ctrl = np.array([(0, 1, 2), (3, 4, 5)], dtype=[(_, int) for _ in ('A', 'f0', 'C')]) test = np.ndfromtxt(StringIO(data), dtype=None, **kwargs) assert_equal(test, ctrl) # w/ default dtype ctrl = np.array([(0, 1, 2), (3, 4, 5)], dtype=[(_, float) for _ in ('A', 'f0', 'C')]) test = np.ndfromtxt(StringIO(data), **kwargs) def test_names_auto_completion(self): "Make sure that names are properly completed" data = "1 2 3\n 4 5 6" test = np.genfromtxt(StringIO(data), dtype=(int, float, int), names="a") ctrl = np.array([(1, 2, 3), (4, 5, 6)], dtype=[('a', int), ('f0', float), ('f1', int)]) assert_equal(test, ctrl) def test_names_with_usecols_bug1636(self): "Make sure we pick up the right names w/ usecols" data = "A,B,C,D,E\n0,1,2,3,4\n0,1,2,3,4\n0,1,2,3,4" ctrl_names = ("A", "C", "E") test = np.genfromtxt(StringIO(data), dtype=(int, int, int), delimiter=",", usecols=(0, 2, 4), names=True) assert_equal(test.dtype.names, ctrl_names) # test = np.genfromtxt(StringIO(data), dtype=(int, int, int), delimiter=",", usecols=("A", "C", "E"), names=True) assert_equal(test.dtype.names, ctrl_names) # test = np.genfromtxt(StringIO(data), dtype=int, delimiter=",", usecols=("A", "C", "E"), names=True) assert_equal(test.dtype.names, ctrl_names) def test_fixed_width_names(self): "Test fix-width w/ names" data = " A B C\n 0 1 2.3\n 45 67 9." kwargs = dict(delimiter=(5, 5, 4), names=True, dtype=None) ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)], dtype=[('A', int), ('B', int), ('C', float)]) test = np.ndfromtxt(StringIO(data), **kwargs) assert_equal(test, ctrl) # kwargs = dict(delimiter=5, names=True, dtype=None) ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)], dtype=[('A', int), ('B', int), ('C', float)]) test = np.ndfromtxt(StringIO(data), **kwargs) assert_equal(test, ctrl) def test_filling_values(self): "Test missing values" data = "1, 2, 3\n1, , 5\n0, 6, \n" kwargs = dict(delimiter=",", dtype=None, filling_values= -999) ctrl = np.array([[1, 2, 3], [1, -999, 5], [0, 6, -999]], dtype=int) test = np.ndfromtxt(StringIO(data), **kwargs) assert_equal(test, ctrl) def test_recfromtxt(self): # data = StringIO('A,B\n0,1\n2,3') kwargs = dict(delimiter=",", missing_values="N/A", names=True) test = np.recfromtxt(data, **kwargs) control = np.array([(0, 1), (2, 3)], dtype=[('A', np.int), ('B', np.int)]) self.assertTrue(isinstance(test, np.recarray)) assert_equal(test, control) # data = StringIO('A,B\n0,1\n2,N/A') test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.int), ('B', np.int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(test.A, [0, 2]) def test_recfromcsv(self): # data = StringIO('A,B\n0,1\n2,3') kwargs = dict(missing_values="N/A", names=True, case_sensitive=True) test = np.recfromcsv(data, dtype=None, **kwargs) control = np.array([(0, 1), (2, 3)], dtype=[('A', np.int), ('B', np.int)]) self.assertTrue(isinstance(test, np.recarray)) assert_equal(test, control) # data = StringIO('A,B\n0,1\n2,N/A') test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.int), ('B', np.int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(test.A, [0, 2]) # data = StringIO('A,B\n0,1\n2,3') test = np.recfromcsv(data, missing_values='N/A',) control = np.array([(0, 1), (2, 3)], dtype=[('a', np.int), ('b', np.int)]) self.assertTrue(isinstance(test, np.recarray)) assert_equal(test, control) def test_gzip_load(): if hasattr(sys, 'gettotalrefcount'): # skip this test when Python was compiled using --with-pydebug return a = np.random.random((5, 5)) s = StringIO() f = gzip.GzipFile(fileobj=s, mode="w") np.save(f, a) f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(np.load(f), a) def test_gzip_loadtxt(): if hasattr(sys, 'gettotalrefcount'): # skip this test when Python was compiled using --with-pydebug return # Thanks to another windows brokeness, we can't use # NamedTemporaryFile: a file created from this function cannot be # reopened by another open call. So we first put the gzipped string # of the test reference array, write it to a securely opened file, # which is then read from by the loadtxt function s = StringIO() g = gzip.GzipFile(fileobj=s, mode='w') g.write(asbytes('1 2 3\n')) g.close() s.seek(0) f, name = mkstemp(suffix='.gz') try: os.write(f, s.read()) s.close() assert_array_equal(np.loadtxt(name), [1, 2, 3]) finally: os.close(f) os.unlink(name) def test_gzip_loadtxt_from_string(): s = StringIO() f = gzip.GzipFile(fileobj=s, mode="w") f.write(asbytes('1 2 3\n')) f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(np.loadtxt(f), [1, 2, 3]) def test_npzfile_dict(): s = StringIO() x = np.zeros((3, 3)) y = np.zeros((3, 3)) np.savez(s, x=x, y=y) s.seek(0) z = np.load(s) assert 'x' in z assert 'y' in z assert 'x' in z.keys() assert 'y' in z.keys() for f, a in z.iteritems(): assert f in ['x', 'y'] assert_equal(a.shape, (3, 3)) assert len(z.items()) == 2 for f in z: assert f in ['x', 'y'] assert 'x' in list(z.iterkeys()) if __name__ == "__main__": run_module_suite()
gpl-3.0
quantifiedcode-bot/invenio-base
tests/test_apps/flash_msg/views.py
4
1351
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Test Application for displaying flash messages on base page.""" from flask import Blueprint, flash, render_template from invenio_base.decorators import wash_arguments blueprint = Blueprint('flash_msg', __name__, url_prefix='/flash_msg', template_folder='templates', static_folder='static') @blueprint.route('/') @wash_arguments({"context": (unicode, ""), "message": (unicode, None)}) def index(context, message=None): """Print the given message string as a flash message.""" flash(message, context) return render_template("page.html")
gpl-2.0
luiscape/andaime
tests/unit/test_class_makefile.py
1
1448
''' Unit tests for the Makefile() class. ''' import os from unittest import TestCase from andaime.tasks.makefile import Makefile class MakefileTestCase(TestCase): ''' Unit tests for the Makefile() class. ''' def _remove_makefile(self): ''' Private method for removing a Makefile from a target test path. ''' file_list = os.listdir('tests/output') for file in file_list: if file == 'Makefile': os.remove('tests/output/Makefile') def setUp(self): ''' Method that sets-up the test enviroment. ''' self._remove_makefile() def tearDown(self): ''' Method that clears the test environment. ''' self._remove_makefile() def test_makefile_is_created(self): ''' Makefile() creates a `Makefile` file successfully. ''' Makefile(path='tests/output') files = os.listdir('tests/output') self.assertTrue('Makefile' in files) def test_makefile_raises_error_if_file_exists(self): ''' Makefile()._craete_makefile() raises error if file exists. ''' open('tests/output/Makefile', 'w+') class f: def __init__(self): self.path = 'tests/output' self.contents = 'foo' with self.assertRaises(ValueError): Makefile._create_makefile(f())
mit
nttks/edx-platform
common/lib/sandbox-packages/eia.py
193
4344
""" Standard resistor values. Commonly used for verifying electronic components in circuit classes are standard values, or conversely, for generating realistic component values in parameterized problems. For details, see: http://en.wikipedia.org/wiki/Electronic_color_code """ # pylint: disable=invalid-name # r is standard name for a resistor. We would like to use it as such. import math import numbers E6 = [10, 15, 22, 33, 47, 68] E12 = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82] E24 = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82, 11, 13, 16, 20, 24, 30, 36, 43, 51, 62, 75, 91] E48 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953] E96 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 102, 124, 150, 182, 221, 267, 324, 392, 475, 576, 698, 845, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 107, 130, 158, 191, 232, 280, 340, 412, 499, 604, 732, 887, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 113, 137, 165, 200, 243, 294, 357, 432, 523, 634, 768, 931, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953, 118, 143, 174, 210, 255, 309, 374, 453, 549, 665, 806, 976] E192 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 101, 123, 149, 180, 218, 264, 320, 388, 470, 569, 690, 835, 102, 124, 150, 182, 221, 267, 324, 392, 475, 576, 698, 845, 104, 126, 152, 184, 223, 271, 328, 397, 481, 583, 706, 856, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 106, 129, 156, 189, 229, 277, 336, 407, 493, 597, 723, 876, 107, 130, 158, 191, 232, 280, 340, 412, 499, 604, 732, 887, 109, 132, 160, 193, 234, 284, 344, 417, 505, 612, 741, 898, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 111, 135, 164, 198, 240, 291, 352, 427, 517, 626, 759, 920, 113, 137, 165, 200, 243, 294, 357, 432, 523, 634, 768, 931, 114, 138, 167, 203, 246, 298, 361, 437, 530, 642, 777, 942, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953, 117, 142, 172, 208, 252, 305, 370, 448, 542, 657, 796, 965, 118, 143, 174, 210, 255, 309, 374, 453, 549, 665, 806, 976, 120, 145, 176, 213, 258, 312, 379, 459, 556, 673, 816, 988] def iseia(r, valid_types=(E6, E12, E24)): ''' Check if a component is a valid EIA value. By default, check 5% component values ''' # Step 1: Discount things which are not numbers if not isinstance(r, numbers.Number) or \ r < 0 or \ math.isnan(r) or \ math.isinf(r): return False # Special case: 0 is an okay resistor if r == 0: return True # Step 2: Move into the range [100, 1000) while r < 100: r = r * 10 while r >= 1000: r = r / 10 # Step 3: Discount things which are not integers, and cast to int if abs(r - round(r)) > 0.01: return False r = int(round(r)) # Step 4: Check if we're a valid EIA value for type_list in valid_types: if r in type_list: return True if int(r / 10.) in type_list and (r % 10) == 0: return True return False if __name__ == '__main__': # Test cases. All of these should return True print iseia(100) # 100 ohm resistor is EIA print not iseia(101) # 101 is not print not iseia(100.3) # Floating point close to EIA is not EIA print iseia(100.001) # But within floating point error is print iseia(1e5) # We handle big numbers well print iseia(2200) # We handle middle-of-the-list well # We can handle 1% components correctly; 2.2k is EIA24, but not EIA48. print not iseia(2200, (E48, E96, E192)) print iseia(5490e2, (E48, E96, E192)) print iseia(2200) print not iseia(5490e2) print iseia(1e-5) # We handle little numbers well print not iseia("Hello") # Junk handled okay print not iseia(float('NaN')) print not iseia(-1) print not iseia(iseia) print not iseia(float('Inf')) print iseia(0) # Corner case. 0 is a standard resistor value.
agpl-3.0
wzbozon/scikit-learn
sklearn/cluster/dbscan_.py
92
12380
# -*- coding: utf-8 -*- """ DBSCAN: Density-Based Spatial Clustering of Applications with Noise """ # Author: Robert Layton <robertlayton@gmail.com> # Joel Nothman <joel.nothman@gmail.com> # Lars Buitinck # # License: BSD 3 clause import warnings import numpy as np from scipy import sparse from ..base import BaseEstimator, ClusterMixin from ..metrics import pairwise_distances from ..utils import check_array, check_consistent_length from ..utils.fixes import astype from ..neighbors import NearestNeighbors from ._dbscan_inner import dbscan_inner def dbscan(X, eps=0.5, min_samples=5, metric='minkowski', algorithm='auto', leaf_size=30, p=2, sample_weight=None, random_state=None): """Perform DBSCAN clustering from vector array or distance matrix. Read more in the :ref:`User Guide <dbscan>`. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. eps : float, optional The maximum distance between two samples for them to be considered as in the same neighborhood. min_samples : int, optional The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by metrics.pairwise.pairwise_distances for its metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only "nonzero" elements may be considered neighbors for DBSCAN. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. p : float, optional The power of the Minkowski metric to be used to calculate distance between points. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. random_state: numpy.RandomState, optional Deprecated and ignored as of version 0.16, will be removed in version 0.18. DBSCAN does not use random initialization. Returns ------- core_samples : array [n_core_samples] Indices of core samples. labels : array [n_samples] Cluster labels for each point. Noisy samples are given the label -1. Notes ----- See examples/cluster/plot_dbscan.py for an example. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). Sparse neighborhoods can be precomputed using :func:`NearestNeighbors.radius_neighbors_graph <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with ``mode='distance'``. References ---------- Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ if not eps > 0.0: raise ValueError("eps must be positive.") if random_state is not None: warnings.warn("The parameter random_state is deprecated in 0.16 " "and will be removed in version 0.18. " "DBSCAN is deterministic except for rare border cases.", category=DeprecationWarning) X = check_array(X, accept_sparse='csr') if sample_weight is not None: sample_weight = np.asarray(sample_weight) check_consistent_length(X, sample_weight) # Calculate neighborhood for all samples. This leaves the original point # in, which needs to be considered later (i.e. point i is in the # neighborhood of point i. While True, its useless information) if metric == 'precomputed' and sparse.issparse(X): neighborhoods = np.empty(X.shape[0], dtype=object) X.sum_duplicates() # XXX: modifies X's internals in-place X_mask = X.data <= eps masked_indices = astype(X.indices, np.intp, copy=False)[X_mask] masked_indptr = np.cumsum(X_mask)[X.indptr[1:] - 1] # insert the diagonal: a point is its own neighbor, but 0 distance # means absence from sparse matrix data masked_indices = np.insert(masked_indices, masked_indptr, np.arange(X.shape[0])) masked_indptr = masked_indptr[:-1] + np.arange(1, X.shape[0]) # split into rows neighborhoods[:] = np.split(masked_indices, masked_indptr) else: neighbors_model = NearestNeighbors(radius=eps, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p) neighbors_model.fit(X) # This has worst case O(n^2) memory complexity neighborhoods = neighbors_model.radius_neighbors(X, eps, return_distance=False) if sample_weight is None: n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods]) else: n_neighbors = np.array([np.sum(sample_weight[neighbors]) for neighbors in neighborhoods]) # Initially, all samples are noise. labels = -np.ones(X.shape[0], dtype=np.intp) # A list of all core samples found. core_samples = np.asarray(n_neighbors >= min_samples, dtype=np.uint8) dbscan_inner(core_samples, neighborhoods, labels) return np.where(core_samples)[0], labels class DBSCAN(BaseEstimator, ClusterMixin): """Perform DBSCAN clustering from vector array or distance matrix. DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density. Read more in the :ref:`User Guide <dbscan>`. Parameters ---------- eps : float, optional The maximum distance between two samples for them to be considered as in the same neighborhood. min_samples : int, optional The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by metrics.pairwise.calculate_distance for its metric parameter. If metric is "precomputed", X is assumed to be a distance matrix and must be square. X may be a sparse matrix, in which case only "nonzero" elements may be considered neighbors for DBSCAN. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. random_state: numpy.RandomState, optional Deprecated and ignored as of version 0.16, will be removed in version 0.18. DBSCAN does not use random initialization. Attributes ---------- core_sample_indices_ : array, shape = [n_core_samples] Indices of core samples. components_ : array, shape = [n_core_samples, n_features] Copy of each core sample found by training. labels_ : array, shape = [n_samples] Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1. Notes ----- See examples/cluster/plot_dbscan.py for an example. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). Sparse neighborhoods can be precomputed using :func:`NearestNeighbors.radius_neighbors_graph <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with ``mode='distance'``. References ---------- Ester, M., H. P. Kriegel, J. Sander, and X. Xu, "A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise". In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 """ def __init__(self, eps=0.5, min_samples=5, metric='euclidean', algorithm='auto', leaf_size=30, p=None, random_state=None): self.eps = eps self.min_samples = min_samples self.metric = metric self.algorithm = algorithm self.leaf_size = leaf_size self.p = p self.random_state = random_state def fit(self, X, y=None, sample_weight=None): """Perform DBSCAN clustering from features or distance matrix. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. """ X = check_array(X, accept_sparse='csr') clust = dbscan(X, sample_weight=sample_weight, **self.get_params()) self.core_sample_indices_, self.labels_ = clust if len(self.core_sample_indices_): # fix for scipy sparse indexing issue self.components_ = X[self.core_sample_indices_].copy() else: # no core samples self.components_ = np.empty((0, X.shape[1])) return self def fit_predict(self, X, y=None, sample_weight=None): """Performs clustering on X and returns cluster labels. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between samples if ``metric='precomputed'``. sample_weight : array, shape (n_samples,), optional Weight of each sample, such that a sample with a weight of at least ``min_samples`` is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1. Returns ------- y : ndarray, shape (n_samples,) cluster labels """ self.fit(X, sample_weight=sample_weight) return self.labels_
bsd-3-clause
arbrandes/edx-platform
openedx/core/djangoapps/olx_rest_api/test_views.py
4
4873
""" Test for the OLX REST API app. """ import re from xml.dom import minidom from openedx.core.djangolib.testing.utils import skip_unless_cms from common.djangoapps.student.roles import CourseStaffRole from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import ToyCourseFactory @skip_unless_cms class OlxRestApiTestCase(SharedModuleStoreTestCase): """ Test the views (and consequently all the other code) of the OLX REST API. """ @classmethod def setUpClass(cls): """ Set up a course for use in these tests """ super().setUpClass() with cls.store.default_store(ModuleStoreEnum.Type.split): cls.course = ToyCourseFactory.create(modulestore=cls.store) assert str(cls.course.id).startswith("course-v1:"), "This test is for split mongo course exports only" cls.unit_key = cls.course.id.make_usage_key('vertical', 'vertical_test') def setUp(self): """ Per-test setup """ super().setUp() self.user = UserFactory.create(password='edx') CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id) self.client.login(username=self.user.username, password='edx') # Helper methods: def assertXmlEqual(self, xml_str_a, xml_str_b): """ Assert that the given XML strings are equal, ignoring attribute order and some whitespace variations. """ def clean(xml_str): # Collapse repeated whitespace: xml_str = re.sub(r'(\s)\s+', r'\1', xml_str) xml_bytes = xml_str.encode('utf8') return minidom.parseString(xml_bytes).toprettyxml() assert clean(xml_str_a) == clean(xml_str_b) def get_olx_response_for_block(self, block_id): return self.client.get(f'/api/olx-export/v1/xblock/{block_id}/') # Actual tests: def test_no_permission(self): """ A regular user enrolled in the course (but not part of the authoring team) should not be able to use the API. """ response = self.get_olx_response_for_block(self.unit_key) assert response.status_code == 403 assert response.json()['detail'] ==\ 'You must be a member of the course team in Studio to export OLX using this API.' def test_export(self): """ A staff user should be able to use this API to get the OLX of XBlocks in the course. """ CourseStaffRole(self.course.id).add_users(self.user) response = self.get_olx_response_for_block(self.unit_key) assert response.status_code == 200 assert response.json()['root_block_id'] == str(self.unit_key) blocks = response.json()['blocks'] # Check the OLX of the root block: self.assertXmlEqual( blocks[str(self.unit_key)]['olx'], '<unit>\n' ' <xblock-include definition="video/sample_video"/>\n' ' <xblock-include definition="video/separate_file_video"/>\n' ' <xblock-include definition="video/video_with_end_time"/>\n' ' <xblock-include definition="poll_question/T1_changemind_poll_foo_2"/>\n' '</unit>\n' ) # Check the OLX of a video self.assertXmlEqual( blocks[str(self.course.id.make_usage_key('video', 'sample_video'))]['olx'], '<video youtube="0.75:JMD_ifUUfsU,1.00:OEoXaMPEzfM,1.25:AKqURZnYqpk,1.50:DYpADpL7jAY" ' 'display_name="default" youtube_id_0_75="JMD_ifUUfsU" youtube_id_1_0="OEoXaMPEzfM" ' 'youtube_id_1_25="AKqURZnYqpk" youtube_id_1_5="DYpADpL7jAY"/>\n' ) def test_html_with_static_asset(self): """ Test that HTML gets converted to use CDATA and static assets are handled. """ CourseStaffRole(self.course.id).add_users(self.user) block_id = str(self.course.id.make_usage_key('html', 'just_img')) response = self.get_olx_response_for_block(block_id) assert response.status_code == 200 assert response.json()['root_block_id'] == block_id block_data = response.json()['blocks'][block_id] self.assertXmlEqual( block_data['olx'], ''' <html display_name="Text"><![CDATA[ <img src="/static/foo_bar.jpg" /> ]]></html> ''' ) assert 'static_files' in block_data assert 'foo_bar.jpg' in block_data['static_files'] url = block_data['static_files']['foo_bar.jpg']['url'] assert url == 'http://testserver/asset-v1:edX+toy+2012_Fall+type@asset+block@foo_bar.jpg'
agpl-3.0
buqing2009/MissionPlanner
Lib/site-packages/scipy/linalg/benchmarks/bench_basic.py
57
3834
import sys from numpy.testing import * import numpy.linalg as linalg def random(size): return rand(*size) class TestSolve(TestCase): def bench_random(self): basic_solve = linalg.solve print print ' Solving system of linear equations' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # larger diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) b = random([size]) print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] print '| %6.2f ' % measure('solve(a,b)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_solve(a,b)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) class TestInv(TestCase): def bench_random(self): basic_inv = linalg.inv print print ' Finding matrix inverse' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] print '| %6.2f ' % measure('inv(a)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_inv(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) class TestDet(TestCase): def bench_random(self): basic_det = linalg.det print print ' Finding matrix determinant' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert not a.flags['CONTIGUOUS'] print '| %6.2f ' % measure('det(a)',repeat), sys.stdout.flush() print '| %6.2f ' % measure('basic_det(a)',repeat), sys.stdout.flush() print ' (secs for %s calls)' % (repeat) if __name__ == "__main__": run_module_suite()
gpl-3.0
tootedom/moto
tests/test_autoscaling/test_launch_configurations.py
17
7779
from __future__ import unicode_literals import boto from boto.ec2.autoscale.launchconfig import LaunchConfiguration from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping import sure # noqa from moto import mock_autoscaling from tests.helpers import requires_boto_gte @mock_autoscaling def test_create_launch_configuration(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', instance_type='t1.micro', key_name='the_keys', security_groups=["default", "default2"], user_data=b"This is some user_data", instance_monitoring=True, instance_profile_name='arn:aws:iam::123456789012:instance-profile/testing', spot_price=0.1, ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.name.should.equal('tester') launch_config.image_id.should.equal('ami-abcd1234') launch_config.instance_type.should.equal('t1.micro') launch_config.key_name.should.equal('the_keys') set(launch_config.security_groups).should.equal(set(['default', 'default2'])) launch_config.user_data.should.equal(b"This is some user_data") launch_config.instance_monitoring.enabled.should.equal('true') launch_config.instance_profile_name.should.equal('arn:aws:iam::123456789012:instance-profile/testing') launch_config.spot_price.should.equal(0.1) @requires_boto_gte("2.27.0") @mock_autoscaling def test_create_launch_configuration_with_block_device_mappings(): block_device_mapping = BlockDeviceMapping() ephemeral_drive = BlockDeviceType() ephemeral_drive.ephemeral_name = 'ephemeral0' block_device_mapping['/dev/xvdb'] = ephemeral_drive snapshot_drive = BlockDeviceType() snapshot_drive.snapshot_id = "snap-1234abcd" snapshot_drive.volume_type = "standard" block_device_mapping['/dev/xvdp'] = snapshot_drive ebs_drive = BlockDeviceType() ebs_drive.volume_type = "io1" ebs_drive.size = 100 ebs_drive.iops = 1000 ebs_drive.delete_on_termination = False block_device_mapping['/dev/xvdh'] = ebs_drive conn = boto.connect_autoscale(use_block_device_types=True) config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', instance_type='m1.small', key_name='the_keys', security_groups=["default", "default2"], user_data=b"This is some user_data", instance_monitoring=True, instance_profile_name='arn:aws:iam::123456789012:instance-profile/testing', spot_price=0.1, block_device_mappings=[block_device_mapping] ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.name.should.equal('tester') launch_config.image_id.should.equal('ami-abcd1234') launch_config.instance_type.should.equal('m1.small') launch_config.key_name.should.equal('the_keys') set(launch_config.security_groups).should.equal(set(['default', 'default2'])) launch_config.user_data.should.equal(b"This is some user_data") launch_config.instance_monitoring.enabled.should.equal('true') launch_config.instance_profile_name.should.equal('arn:aws:iam::123456789012:instance-profile/testing') launch_config.spot_price.should.equal(0.1) len(launch_config.block_device_mappings).should.equal(3) returned_mapping = launch_config.block_device_mappings set(returned_mapping.keys()).should.equal(set(['/dev/xvdb', '/dev/xvdp', '/dev/xvdh'])) returned_mapping['/dev/xvdh'].iops.should.equal(1000) returned_mapping['/dev/xvdh'].size.should.equal(100) returned_mapping['/dev/xvdh'].volume_type.should.equal("io1") returned_mapping['/dev/xvdh'].delete_on_termination.should.be.false returned_mapping['/dev/xvdp'].snapshot_id.should.equal("snap-1234abcd") returned_mapping['/dev/xvdp'].volume_type.should.equal("standard") returned_mapping['/dev/xvdb'].ephemeral_name.should.equal('ephemeral0') @requires_boto_gte("2.12") @mock_autoscaling def test_create_launch_configuration_for_2_12(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', ebs_optimized=True, ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.ebs_optimized.should.equal(True) @requires_boto_gte("2.25.0") @mock_autoscaling def test_create_launch_configuration_using_ip_association(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', associate_public_ip_address=True, ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.associate_public_ip_address.should.equal(True) @requires_boto_gte("2.25.0") @mock_autoscaling def test_create_launch_configuration_using_ip_association_should_default_to_false(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.associate_public_ip_address.should.equal(False) @mock_autoscaling def test_create_launch_configuration_defaults(): """ Test with the minimum inputs and check that all of the proper defaults are assigned for the other attributes """ conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', instance_type='m1.small', ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.name.should.equal('tester') launch_config.image_id.should.equal('ami-abcd1234') launch_config.instance_type.should.equal('m1.small') # Defaults launch_config.key_name.should.equal('') list(launch_config.security_groups).should.equal([]) launch_config.user_data.should.equal(b"") launch_config.instance_monitoring.enabled.should.equal('false') launch_config.instance_profile_name.should.equal(None) launch_config.spot_price.should.equal(None) @requires_boto_gte("2.12") @mock_autoscaling def test_create_launch_configuration_defaults_for_2_12(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', ) conn.create_launch_configuration(config) launch_config = conn.get_all_launch_configurations()[0] launch_config.ebs_optimized.should.equal(False) @mock_autoscaling def test_launch_configuration_describe_filter(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', instance_type='m1.small', ) conn.create_launch_configuration(config) config.name = 'tester2' conn.create_launch_configuration(config) config.name = 'tester3' conn.create_launch_configuration(config) conn.get_all_launch_configurations(names=['tester', 'tester2']).should.have.length_of(2) conn.get_all_launch_configurations().should.have.length_of(3) @mock_autoscaling def test_launch_configuration_delete(): conn = boto.connect_autoscale() config = LaunchConfiguration( name='tester', image_id='ami-abcd1234', instance_type='m1.small', ) conn.create_launch_configuration(config) conn.get_all_launch_configurations().should.have.length_of(1) conn.delete_launch_configuration('tester') conn.get_all_launch_configurations().should.have.length_of(0)
apache-2.0
fldc/CouchPotatoServer
libs/requests/packages/urllib3/response.py
478
16459
try: import http.client as httplib except ImportError: import httplib import zlib import io from socket import timeout as SocketTimeout from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ) from .packages.six import string_types as basestring, binary_type, PY3 from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: return self._obj.decompress(data) except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data return self._obj.decompress(data) def _get_decoder(mode): if mode == 'gzip': return GzipDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. """ CONTENT_DECODERS = ['gzip', 'deflate'] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 if body and isinstance(body, (basestring, binary_type)): self._body = body self._pool = pool self._connection = connection if hasattr(body, 'read'): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get('transfer-encoding', '').lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # We certainly don't want to preload content when the response is chunked. if not self.chunked and preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_decoder(self): """ Set-up the _decoder attribute if necessar. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lower() if self._decoder is None and content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ try: if decode_content and self._decoder: data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e) if flush_decoder and decode_content and self._decoder: buf = self._decoder.decompress(binary_type()) data += buf + self._decoder.flush() return data def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False try: try: if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except HTTPException as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) self._fp_bytes_read += len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data finally: if self._original_response and self._original_response.isclosed(): self.release_conn() def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked: for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() @property def closed(self): if self._fp is None: return True elif hasattr(self._fp, 'closed'): return self._fp.closed elif hasattr(self._fp, 'isclosed'): # Python 2 return self._fp.isclosed() else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError("The file-like object this HTTPResponse is wrapped " "around has no file descriptor") def flush(self): if self._fp is not None and hasattr(self._fp, 'flush'): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[:len(temp)] = temp return len(temp) def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b';', 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise httplib.IncompleteRead(line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked("Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") if self._original_response and self._original_response._method.upper() == 'HEAD': # Don't bother reading the body of a HEAD request. # FIXME: Can we do this somehow without accessing private httplib _method? self._original_response.close() return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) yield self._decode(chunk, decode_content=decode_content, flush_decoder=True) # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close() self.release_conn()
gpl-3.0
gojira/tensorflow
tensorflow/contrib/estimator/python/estimator/head_test.py
5
58092
# Copyright 2017 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. # ============================================================================== """Tests for head.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six from tensorflow.contrib.estimator.python.estimator import head as head_lib from tensorflow.core.framework import summary_pb2 from tensorflow.python.estimator import model_fn from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.estimator.canned import prediction_keys from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import string_ops from tensorflow.python.ops import variables from tensorflow.python.ops.losses import losses from tensorflow.python.platform import test from tensorflow.python.saved_model import signature_constants from tensorflow.python.training import monitored_session _DEFAULT_SERVING_KEY = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY def _initialize_variables(test_case, scaffold): scaffold.finalize() test_case.assertIsNone(scaffold.init_feed_dict) test_case.assertIsNone(scaffold.init_fn) scaffold.init_op.run() scaffold.ready_for_local_init_op.eval() scaffold.local_init_op.run() scaffold.ready_op.eval() test_case.assertIsNotNone(scaffold.saver) def _assert_simple_summaries(test_case, expected_summaries, summary_str, tol=1e-6): """Assert summary the specified simple values. Args: test_case: test case. expected_summaries: Dict of expected tags and simple values. summary_str: Serialized `summary_pb2.Summary`. tol: Tolerance for relative and absolute. """ summary = summary_pb2.Summary() summary.ParseFromString(summary_str) test_case.assertAllClose(expected_summaries, { v.tag: v.simple_value for v in summary.value }, rtol=tol, atol=tol) def _assert_no_hooks(test_case, spec): test_case.assertAllEqual([], spec.training_chief_hooks) test_case.assertAllEqual([], spec.training_hooks) def _sigmoid(logits): return 1 / (1 + np.exp(-logits)) def _sigmoid_cross_entropy(labels, logits): """Returns sigmoid cross entropy averaged over classes.""" sigmoid_logits = _sigmoid(logits) unreduced_result = ( -labels * np.log(sigmoid_logits) -(1 - labels) * np.log(1 - sigmoid_logits)) # Mean over classes return np.mean(unreduced_result, axis=-1, keepdims=True) class MultiLabelHead(test.TestCase): def setUp(self): ops.reset_default_graph() def test_n_classes_is_none(self): with self.assertRaisesRegexp( ValueError, r'n_classes must be > 1 for multi-class classification\. Given: None'): head_lib.multi_label_head(n_classes=None) def test_n_classes_is_1(self): with self.assertRaisesRegexp( ValueError, r'n_classes must be > 1 for multi-class classification\. Given: 1'): head_lib.multi_label_head(n_classes=1) def test_threshold_too_small(self): with self.assertRaisesRegexp( ValueError, r'thresholds must be in \(0, 1\) range\. Given: 0\.0'): head_lib.multi_label_head(n_classes=2, thresholds=[0., 0.5]) def test_threshold_too_large(self): with self.assertRaisesRegexp( ValueError, r'thresholds must be in \(0, 1\) range\. Given: 1\.0'): head_lib.multi_label_head(n_classes=2, thresholds=[0.5, 1.0]) def test_label_vocabulary_dict(self): with self.assertRaisesRegexp( ValueError, r'label_vocabulary must be a list or tuple\. ' r'Given type: <(type|class) \'dict\'>'): head_lib.multi_label_head(n_classes=2, label_vocabulary={'foo': 'bar'}) def test_label_vocabulary_wrong_size(self): with self.assertRaisesRegexp( ValueError, r'Length of label_vocabulary must be n_classes \(3\). Given: 2'): head_lib.multi_label_head(n_classes=3, label_vocabulary=['foo', 'bar']) def test_invalid_loss_reduction(self): with self.assertRaisesRegexp( ValueError, r'Invalid loss_reduction: invalid_loss_reduction'): head_lib.multi_label_head( n_classes=3, loss_reduction='invalid_loss_reduction') with self.assertRaisesRegexp( ValueError, r'Invalid loss_reduction: none'): head_lib.multi_label_head( n_classes=3, loss_reduction=losses.Reduction.NONE) def test_loss_fn_arg_labels_missing(self): def _loss_fn(logits): del logits # Unused with self.assertRaisesRegexp( ValueError, r'loss_fn must contain argument: labels\. ' r'Given arguments: \(\'logits\',\)'): head_lib.multi_label_head(n_classes=3, loss_fn=_loss_fn) def test_loss_fn_arg_logits_missing(self): def _loss_fn(labels): del labels # unused with self.assertRaisesRegexp( ValueError, r'loss_fn must contain argument: logits\. ' r'Given arguments: \(\'labels\',\)'): head_lib.multi_label_head(n_classes=3, loss_fn=_loss_fn) def test_loss_fn_arg_features_ok(self): def _loss_fn(labels, logits, features): del labels, logits, features # Unused head_lib.multi_label_head(n_classes=3, loss_fn=_loss_fn) def test_loss_fn_arg_invalid(self): def _loss_fn(labels, logits, name=None): del labels, logits, name # Unused with self.assertRaisesRegexp( ValueError, r'loss_fn has unexpected args: \[\'name\'\]'): head_lib.multi_label_head(n_classes=3, loss_fn=_loss_fn) def test_classes_for_class_based_metrics_invalid(self): with self.assertRaisesRegexp( ValueError, r'All classes_for_class_based_metrics must be in range \[0, 2\]\. ' r'Given: -1'): head_lib.multi_label_head( n_classes=3, classes_for_class_based_metrics=[2, -1]) def test_classes_for_class_based_metrics_string_invalid(self): with self.assertRaisesRegexp( ValueError, r'\'z\' is not in list'): head_lib.multi_label_head( n_classes=3, label_vocabulary=['a', 'b', 'c'], classes_for_class_based_metrics=['c', 'z']) def test_name(self): head = head_lib.multi_label_head(n_classes=4, name='foo') self.assertEqual('foo', head.name) def test_predict(self): n_classes = 4 head = head_lib.multi_label_head(n_classes) self.assertEqual(n_classes, head.logits_dimension) logits = np.array( [[0., 1., 2., -1.], [-1., -2., -3., 1.]], dtype=np.float32) expected_probabilities = _sigmoid(logits) expected_export_classes = [[b'0', b'1', b'2', b'3']] * 2 spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.PREDICT, logits=logits) self.assertItemsEqual( (_DEFAULT_SERVING_KEY, 'predict', 'classification'), spec.export_outputs.keys()) # Assert predictions and export_outputs. with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNone(spec.scaffold.summary_op) predictions = sess.run(spec.predictions) self.assertAllClose(logits, predictions[prediction_keys.PredictionKeys.LOGITS]) self.assertAllClose( expected_probabilities, predictions[prediction_keys.PredictionKeys.PROBABILITIES]) self.assertAllClose( expected_probabilities, sess.run(spec.export_outputs[_DEFAULT_SERVING_KEY].scores)) self.assertAllEqual( expected_export_classes, sess.run(spec.export_outputs[_DEFAULT_SERVING_KEY].classes)) def test_predict_with_label_vocabulary(self): n_classes = 4 head = head_lib.multi_label_head( n_classes, label_vocabulary=['foo', 'bar', 'foobar', 'barfoo']) logits = np.array( [[0., 1., 2., -1.], [-1., -2., -3., 1.]], dtype=np.float32) expected_export_classes = [[b'foo', b'bar', b'foobar', b'barfoo']] * 2 spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.PREDICT, logits=logits) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertAllEqual( expected_export_classes, sess.run(spec.export_outputs[_DEFAULT_SERVING_KEY].classes)) def test_weight_should_not_impact_prediction(self): n_classes = 4 head = head_lib.multi_label_head(n_classes, weight_column='example_weights') self.assertEqual(n_classes, head.logits_dimension) logits = np.array( [[0., 1., 2., -1.], [-1., -2., -3., 1.]], dtype=np.float32) expected_probabilities = _sigmoid(logits) weights_2x1 = [[1.], [2.]] spec = head.create_estimator_spec( features={ 'x': np.array(((42,),), dtype=np.int32), 'example_weights': weights_2x1, }, mode=model_fn.ModeKeys.PREDICT, logits=logits) # Assert predictions and export_outputs. with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNone(spec.scaffold.summary_op) predictions = sess.run(spec.predictions) self.assertAllClose(logits, predictions[prediction_keys.PredictionKeys.LOGITS]) self.assertAllClose( expected_probabilities, predictions[prediction_keys.PredictionKeys.PROBABILITIES]) def test_eval_create_loss(self): """Tests head.create_loss for eval mode.""" n_classes = 2 head = head_lib.multi_label_head(n_classes) logits = np.array([[-1., 1.], [-1.5, 1.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = (labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits))) / 2 expected_training_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels, logits=logits)) actual_training_loss = head.create_loss( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels)[0] with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose(expected_training_loss, actual_training_loss.eval()) def test_eval_create_loss_large_logits(self): """Tests head.create_loss for eval mode and large logits.""" n_classes = 2 head = head_lib.multi_label_head(n_classes) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # For large logits, this is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits expected_training_loss = 0.5 * np.sum( np.array([[(10. + 10.) / 2.], [(15. + 0.) / 2.]], dtype=np.float32)) actual_training_loss = head.create_loss( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels)[0] with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose( expected_training_loss, actual_training_loss.eval(), atol=1e-4) def test_eval_create_loss_labels_wrong_shape(self): """Tests head.create_loss for eval mode when labels has the wrong shape.""" n_classes = 2 head = head_lib.multi_label_head(n_classes) logits = np.array([[-1., 1.], [-1.5, 1.]], dtype=np.float32) labels_placeholder = array_ops.placeholder(dtype=dtypes.int64) actual_training_loss = head.create_loss( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels_placeholder)[0] with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[expected_labels_shape: \] \[2 2\] \[labels_shape: \] \[2 1\]'): actual_training_loss.eval({ labels_placeholder: np.array([[1], [1]], dtype=np.int64) }) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'labels shape must be \[D0, D1, ... DN, 2\]\..*' r'\[Received shape: \] \[2\]'): actual_training_loss.eval({ labels_placeholder: np.array([1, 1], dtype=np.int64) }) def test_eval_create_loss_loss_fn(self): """Tests head.create_loss for eval mode and custom loss_fn.""" loss = np.array([[1.], [2.]], dtype=np.float32) logits_input = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels_input = np.array([[1, 0], [1, 1]], dtype=np.int64) def _loss_fn(labels, logits): check_labels = control_flow_ops.Assert( math_ops.reduce_all(math_ops.equal(labels, labels_input)), data=[labels]) check_logits = control_flow_ops.Assert( math_ops.reduce_all(math_ops.equal(logits, logits_input)), data=[logits]) with ops.control_dependencies([check_labels, check_logits]): return constant_op.constant(loss) head = head_lib.multi_label_head(n_classes=2, loss_fn=_loss_fn) actual_training_loss = head.create_loss( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=logits_input, labels=labels_input)[0] with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose(np.sum(loss) / 2., actual_training_loss.eval()) def test_eval_create_loss_loss_fn_wrong_shape(self): """Tests custom loss_fn that returns Tensor of unexpected shape.""" loss = np.array([1., 2.], dtype=np.float32) def _loss_fn(labels, logits): del labels, logits # Unused return constant_op.constant(loss) head = head_lib.multi_label_head(n_classes=2, loss_fn=_loss_fn) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) actual_training_loss = head.create_loss( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels)[0] with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[loss_fn must return Tensor of shape \[D0, D1, ... DN, 1\]\. \] ' r'\[logits_shape: \] \[2 2\] \[loss_shape: \] \[2\]'): actual_training_loss.eval() def test_eval_labels_none(self): """Tests that error is raised when labels is None.""" head = head_lib.multi_label_head(n_classes=2) with self.assertRaisesRegexp( ValueError, r'You must provide a labels Tensor\. Given: None\.'): head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.EVAL, logits=np.array([[-10., 10.], [-15., 10.]], dtype=np.float32), labels=None) def _test_eval( self, head, logits, labels, expected_loss, expected_metrics, features=None, regularization_losses=None): spec = head.create_estimator_spec( features=features or {}, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels, regularization_losses=regularization_losses) # Assert spec contains expected tensors. self.assertIsNotNone(spec.loss) self.assertItemsEqual(expected_metrics.keys(), spec.eval_metric_ops.keys()) self.assertIsNone(spec.train_op) self.assertIsNone(spec.export_outputs) _assert_no_hooks(self, spec) # Assert predictions, loss, and metrics. tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNone(spec.scaffold.summary_op) value_ops = {k: spec.eval_metric_ops[k][0] for k in spec.eval_metric_ops} update_ops = {k: spec.eval_metric_ops[k][1] for k in spec.eval_metric_ops} loss, metrics = sess.run((spec.loss, update_ops)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) # Check results of both update (in `metrics`) and value ops. self.assertAllClose(expected_metrics, metrics, rtol=tol, atol=tol) self.assertAllClose( expected_metrics, {k: value_ops[k].eval() for k in value_ops}, rtol=tol, atol=tol) def test_eval(self): n_classes = 2 head = head_lib.multi_label_head(n_classes) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_sparse_labels(self): n_classes = 2 head = head_lib.multi_label_head(n_classes) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) # Equivalent to multi_hot = [[1, 0], [1, 1]] labels = sparse_tensor.SparseTensor( values=[0, 0, 1], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) labels_multi_hot = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels_multi_hot, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_with_regularization_losses(self): n_classes = 2 head = head_lib.multi_label_head( n_classes, loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) regularization_losses = [1.5, 0.5] expected_regularization_loss = 2. # unregularized_loss = sum( # labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits))) / batch_size expected_unregularized_loss = np.sum( _sigmoid_cross_entropy(labels=labels, logits=logits)) / 2. expected_regularized_loss = ( expected_unregularized_loss + expected_regularization_loss) keys = metric_keys.MetricKeys expected_metrics = { keys.LOSS_MEAN: expected_unregularized_loss, keys.LOSS_REGULARIZATION: expected_regularization_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_regularized_loss, expected_metrics=expected_metrics, regularization_losses=regularization_losses) def test_eval_with_label_vocabulary(self): n_classes = 2 head = head_lib.multi_label_head( n_classes, label_vocabulary=['class0', 'class1']) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) # Equivalent to multi_hot = [[1, 0], [1, 1]] labels = sparse_tensor.SparseTensor( values=['class0', 'class0', 'class1'], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) labels_multi_hot = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels_multi_hot, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_with_thresholds(self): n_classes = 2 thresholds = [0.25, 0.5, 0.75] head = head_lib.multi_label_head(n_classes, thresholds=thresholds) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, keys.ACCURACY_AT_THRESHOLD % thresholds[0]: 2. / 4., keys.PRECISION_AT_THRESHOLD % thresholds[0]: 2. / 3., keys.RECALL_AT_THRESHOLD % thresholds[0]: 2. / 3., keys.ACCURACY_AT_THRESHOLD % thresholds[1]: 1. / 4., keys.PRECISION_AT_THRESHOLD % thresholds[1]: 1. / 2., keys.RECALL_AT_THRESHOLD % thresholds[1]: 1. / 3., keys.ACCURACY_AT_THRESHOLD % thresholds[2]: 2. / 4., keys.PRECISION_AT_THRESHOLD % thresholds[2]: 1. / 1., keys.RECALL_AT_THRESHOLD % thresholds[2]: 1. / 3., } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_with_classes_for_class_based_metrics(self): head = head_lib.multi_label_head( n_classes=2, classes_for_class_based_metrics=[0, 1]) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, keys.PROBABILITY_MEAN_AT_CLASS % 0: np.sum(_sigmoid(logits[:, 0])) / 2., keys.AUC_AT_CLASS % 0: 0., keys.AUC_PR_AT_CLASS % 0: 1., keys.PROBABILITY_MEAN_AT_CLASS % 1: np.sum(_sigmoid(logits[:, 1])) / 2., keys.AUC_AT_CLASS % 1: 1., keys.AUC_PR_AT_CLASS % 1: 1., } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_with_classes_for_class_based_metrics_string(self): head = head_lib.multi_label_head( n_classes=2, label_vocabulary=['a', 'b'], classes_for_class_based_metrics=['a', 'b']) logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) labels = sparse_tensor.SparseTensor( values=['a', 'a', 'b'], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) labels_onehot = np.array([[1, 0], [1, 1]], dtype=np.int64) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # Sum over examples, divide by batch_size. expected_loss = 0.5 * np.sum( _sigmoid_cross_entropy(labels=labels_onehot, logits=logits)) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over examples. keys.LOSS_MEAN: expected_loss, # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.3333, keys.AUC_PR: 0.7639, keys.PROBABILITY_MEAN_AT_CLASS % 0: np.sum(_sigmoid(logits[:, 0])) / 2., keys.AUC_AT_CLASS % 0: 0., keys.AUC_PR_AT_CLASS % 0: 1., keys.PROBABILITY_MEAN_AT_CLASS % 1: np.sum(_sigmoid(logits[:, 1])) / 2., keys.AUC_AT_CLASS % 1: 1., keys.AUC_PR_AT_CLASS % 1: 1., } self._test_eval( head=head, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) def test_eval_with_weights(self): n_classes = 2 head = head_lib.multi_label_head(n_classes, weight_column='example_weights') logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, weighted sum over examples, divide by batch_size. # loss = ( 1 * (10 + 10) / 2 + 2 * (15 + 0) / 2) / 2 expected_loss = 12.5 spec = head.create_estimator_spec( features={ 'x': np.array([[41], [42]], dtype=np.int32), 'example_weights': np.array([[1.], [2.]], dtype=np.float32), }, mode=model_fn.ModeKeys.EVAL, logits=logits, labels=labels) keys = metric_keys.MetricKeys expected_metrics = { # Average loss over weighted examples (denominator is sum(weights)). keys.LOSS_MEAN: expected_loss * (2. / 3.), # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.2000, keys.AUC_PR: 0.7833, } # Assert spec contains expected tensors. self.assertIsNotNone(spec.loss) self.assertItemsEqual(expected_metrics.keys(), spec.eval_metric_ops.keys()) self.assertIsNone(spec.train_op) self.assertIsNone(spec.export_outputs) _assert_no_hooks(self, spec) # Assert predictions, loss, and metrics. tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNone(spec.scaffold.summary_op) value_ops = {k: spec.eval_metric_ops[k][0] for k in spec.eval_metric_ops} update_ops = {k: spec.eval_metric_ops[k][1] for k in spec.eval_metric_ops} loss, metrics = sess.run((spec.loss, update_ops)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) # Check results of both update (in `metrics`) and value ops. self.assertAllClose(expected_metrics, metrics, rtol=tol, atol=tol) self.assertAllClose( expected_metrics, {k: value_ops[k].eval() for k in value_ops}, rtol=tol, atol=tol) def test_train_create_loss_large_logits(self): """Tests head.create_loss for train mode and large logits.""" n_classes = 2 head = head_lib.multi_label_head(n_classes, weight_column='example_weights') logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) weights = np.array([[1.], [2.]], dtype=np.float32) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # For large logits, this is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits expected_unreduced_loss = [[(10. + 10.) / 2.], [(15. + 0.) / 2.]] expected_weights = [[1.], [2.]] expected_training_loss = (1. * (10. + 10.) / 2. + 2. * (15. + 0.) / 2.) / 2. training_loss, unreduced_loss, actual_weights, _ = head.create_loss( features={ 'x': np.array(((42,),), dtype=np.int32), 'example_weights': weights }, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels) with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose( expected_training_loss, training_loss.eval(), atol=1e-4) self.assertAllClose( expected_unreduced_loss, unreduced_loss.eval(), atol=1e-4) self.assertAllClose(expected_weights, actual_weights.eval()) def test_train_create_loss_loss_reduction(self): """Tests head.create_loss with loss_reduction.""" n_classes = 2 head = head_lib.multi_label_head( n_classes, weight_column='example_weights', loss_reduction=losses.Reduction.SUM_BY_NONZERO_WEIGHTS) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) weights = np.array([[1.], [2.]], dtype=np.float32) # loss = labels * -log(sigmoid(logits)) + # (1 - labels) * -log(1 - sigmoid(logits)) # For large logits, this is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits expected_unreduced_loss = [[(10. + 10.) / 2.], [(15. + 0.) / 2.]] expected_weights = [[1.], [2.]] expected_training_loss = (1. * (10. + 10.) / 2. + 2. * (15. + 0.) / 2.) / 2. training_loss, unreduced_loss, actual_weights, _ = head.create_loss( features={ 'x': np.array(((42,),), dtype=np.int32), 'example_weights': weights }, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels) with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose( expected_training_loss, training_loss.eval(), atol=1e-4) self.assertAllClose( expected_unreduced_loss, unreduced_loss.eval(), atol=1e-4) self.assertAllClose(expected_weights, actual_weights.eval()) def test_train_labels_none(self): """Tests that error is raised when labels is None.""" head = head_lib.multi_label_head(n_classes=2) def _no_op_train_fn(loss): del loss return control_flow_ops.no_op() with self.assertRaisesRegexp( ValueError, r'You must provide a labels Tensor\. Given: None\.'): head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=np.array([[-10., 10.], [-15., 10.]], dtype=np.float32), labels=None, train_op_fn=_no_op_train_fn) def test_train_invalid_indicator_labels(self): head = head_lib.multi_label_head(n_classes=2) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) # The value 2 is outside the allowed range. labels = np.array([[2, 0], [1, 1]], dtype=np.int64) def _train_op_fn(loss): del loss return control_flow_ops.no_op() spec = head.create_estimator_spec( features={}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'labels must be an integer indicator Tensor with values in ' r'\[0, 1\]'): sess.run(spec.loss) def test_train_invalid_sparse_labels(self): head = head_lib.multi_label_head(n_classes=2) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) # The value 2 is outside the allowed range. labels = sparse_tensor.SparseTensor( values=[2, 0, 1], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) def _train_op_fn(loss): del loss return control_flow_ops.no_op() spec = head.create_estimator_spec( features={}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'labels must be an integer SparseTensor with values in \[0, 2\)'): sess.run(spec.loss) def _test_train(self, head, logits, labels, expected_loss): expected_train_result = 'my_train_op' def _train_op_fn(loss): return string_ops.string_join( [constant_op.constant(expected_train_result), string_ops.as_string(loss, precision=3)]) spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) self.assertIsNotNone(spec.loss) self.assertEqual({}, spec.eval_metric_ops) self.assertIsNotNone(spec.train_op) self.assertIsNone(spec.export_outputs) _assert_no_hooks(self, spec) # Assert predictions, loss, train_op, and summaries. tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNotNone(spec.scaffold.summary_op) loss, train_result, summary_str = sess.run((spec.loss, spec.train_op, spec.scaffold.summary_op)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) self.assertEqual( six.b('{0:s}{1:.3f}'.format(expected_train_result, expected_loss)), train_result) _assert_simple_summaries( self, {metric_keys.MetricKeys.LOSS: expected_loss}, summary_str, tol) def test_train(self): head = head_lib.multi_label_head(n_classes=2) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, sum over examples, divide by batch_size. # loss = ( (10 + 10) / 2 + (15 + 0) / 2 ) / 2 expected_loss = 8.75 self._test_train( head=head, logits=logits, labels=labels, expected_loss=expected_loss) def test_train_sparse_labels(self): head = head_lib.multi_label_head(n_classes=2) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) # Equivalent to multi_hot = [[1, 0], [1, 1]] labels = sparse_tensor.SparseTensor( values=[0, 0, 1], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, sum over examples, divide by batch_size. # loss = ( (10 + 10) / 2 + (15 + 0) / 2 ) / 2 expected_loss = 8.75 self._test_train( head=head, logits=logits, labels=labels, expected_loss=expected_loss) def test_train_with_label_vocabulary(self): head = head_lib.multi_label_head( n_classes=2, label_vocabulary=['class0', 'class1']) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) # Equivalent to multi_hot = [[1, 0], [1, 1]] labels = sparse_tensor.SparseTensor( values=['class0', 'class0', 'class1'], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, sum over examples, divide by batch_size. # loss = ( (10 + 10) / 2 + (15 + 0) / 2 ) / 2 expected_loss = 8.75 self._test_train( head=head, logits=logits, labels=labels, expected_loss=expected_loss) def test_train_with_optimizer(self): head = head_lib.multi_label_head(n_classes=2) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, sum over examples, divide by batch_size. # loss = ( (10 + 10) / 2 + (15 + 0) / 2 ) / 2 expected_loss = 8.75 expected_train_result = 'my_train_op' class _Optimizer(object): def minimize(self, loss, global_step): del global_step return string_ops.string_join( [constant_op.constant(expected_train_result), string_ops.as_string(loss, precision=3)]) spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, optimizer=_Optimizer()) tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) loss, train_result = sess.run((spec.loss, spec.train_op)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) self.assertEqual( six.b('{0:s}{1:.3f}'.format(expected_train_result, expected_loss)), train_result) def test_train_with_update_ops(self): head = head_lib.multi_label_head(n_classes=2) with ops.Graph().as_default(): w = variables.Variable(1) update_op = w.assign_add(1) ops.add_to_collection(ops.GraphKeys.UPDATE_OPS, update_op) t = variables.Variable('') expected_train_result = b'my_train_op' def _train_op_fn(loss): del loss return t.assign(expected_train_result) spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=np.array([[-10., 10.], [-15., 10.]], dtype=np.float32), labels=np.array([[1, 0], [1, 1]], dtype=np.int64), train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) sess.run(spec.train_op) w_value, t_value = sess.run([w, t]) self.assertEqual(2, w_value) self.assertEqual(expected_train_result, t_value) def test_train_with_regularization_losses(self): head = head_lib.multi_label_head( n_classes=2, loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE) logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) regularization_losses = [1.5, 0.5] # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes and over batch and add regularization loss. expected_loss = 35. / 4. + 2. expected_summaries = { metric_keys.MetricKeys.LOSS: expected_loss, metric_keys.MetricKeys.LOSS_REGULARIZATION: 2., } expected_train_result = 'my_train_op' def _train_op_fn(loss): return string_ops.string_join( [constant_op.constant(expected_train_result), string_ops.as_string(loss, precision=3)]) spec = head.create_estimator_spec( features={'x': np.array(((42,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn, regularization_losses=regularization_losses) # Assert predictions, loss, train_op, and summaries. tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNotNone(spec.scaffold.summary_op) loss, train_result, summary_str = sess.run((spec.loss, spec.train_op, spec.scaffold.summary_op)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) self.assertEqual( six.b('{0:s}{1:.3f}'.format(expected_train_result, expected_loss)), train_result) _assert_simple_summaries(self, expected_summaries, summary_str, tol) def test_train_with_weights(self): n_classes = 2 head = head_lib.multi_label_head(n_classes, weight_column='example_weights') logits = np.array([[-10., 10.], [-15., 10.]], dtype=np.float32) labels = np.array([[1, 0], [1, 1]], dtype=np.int64) # For large logits, sigmoid cross entropy loss is approximated as: # loss = labels * (logits < 0) * (-logits) + # (1 - labels) * (logits > 0) * logits => # expected_unweighted_loss = [[10., 10.], [15., 0.]] # Average over classes, weighted sum over examples, divide by batch_size. # loss = ( 1 * (10 + 10) / 2 + 2 * (15 + 0) / 2 ) / 2 expected_loss = 12.5 expected_train_result = 'my_train_op' def _train_op_fn(loss): return string_ops.string_join( [constant_op.constant(expected_train_result), string_ops.as_string(loss, precision=3)]) spec = head.create_estimator_spec( features={ 'x': np.array([[41], [42]], dtype=np.int32), 'example_weights': np.array([[1.], [2.]], dtype=np.float32), }, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) self.assertIsNotNone(spec.loss) self.assertEqual({}, spec.eval_metric_ops) self.assertIsNotNone(spec.train_op) self.assertIsNone(spec.export_outputs) _assert_no_hooks(self, spec) # Assert predictions, loss, train_op, and summaries. tol = 1e-3 with self.test_session() as sess: _initialize_variables(self, spec.scaffold) self.assertIsNotNone(spec.scaffold.summary_op) loss, train_result, summary_str = sess.run((spec.loss, spec.train_op, spec.scaffold.summary_op)) self.assertAllClose(expected_loss, loss, rtol=tol, atol=tol) self.assertEqual( six.b('{0:s}{1:.3f}'.format(expected_train_result, expected_loss)), train_result) _assert_simple_summaries( self, {metric_keys.MetricKeys.LOSS: expected_loss,}, summary_str, tol) def test_multi_dim_weighted_train_create_loss(self): """Logits and labels of shape [2, 2, 3], weights [2, 2].""" head = head_lib.multi_label_head(n_classes=3, weight_column='weights') logits = np.array([[[-10., 10., -10.], [10., -10., 10.]], [[-12., 12., -12.], [12., -12., 12.]]], dtype=np.float32) labels = np.array([[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64) weights = np.array([[1., 1.5], [2., 2.5]], dtype=np.float32) # unreduced_loss = # [[10 + 10 + 0, 0 + 0 + 10], [0 + 0 + 12, 12 + 12 + 0]] / 3 # = [[20/3, 10/3], [4, 8]] expected_unreduced_loss = [[[20./3.], [10./3.]], [[4.], [8.]]] # weights are reshaped to [2, 2, 1] to match logits. expected_weights = [[[1.], [1.5]], [[2.], [2.5]]] # loss = (1*20/3 + 1.5*10/3 + 2*4 + 2.5*8) / 4 = 9.9167 expected_training_loss = 9.9167 training_loss, unreduced_loss, actual_weights, _ = head.create_loss( features={'weights': weights}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels) atol = 1.e-3 with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) self.assertAllClose( expected_training_loss, training_loss.eval(), atol=atol) self.assertAllClose( expected_unreduced_loss, unreduced_loss.eval(), atol=atol) self.assertAllClose(expected_weights, actual_weights.eval()) def test_multi_dim_weighted_train(self): """Logits and labels of shape [2, 2, 3], weights [2, 2].""" head = head_lib.multi_label_head(n_classes=3, weight_column='weights') logits = np.array([[[-10., 10., -10.], [10., -10., 10.]], [[-12., 12., -12.], [12., -12., 12.]]], dtype=np.float32) labels = np.array([[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64) weights = np.array([[1., 1.5], [2., 2.5]], dtype=np.float32) # loss = [[10 + 10 + 0, 0 + 0 + 10], [0 + 0 + 12, 12 + 12 + 0]] / 3 # = [[20/3, 10/3], [4, 8]] # loss = (1*20/3 + 1.5*10/3 + 2*4 + 2.5*8) / 4 = 9.9167 expected_loss = 9.9167 expected_train_result = 'my_train_op' def _train_op_fn(loss): return string_ops.string_join( [constant_op.constant(expected_train_result), string_ops.as_string(loss, precision=3)]) spec = head.create_estimator_spec( features={'weights': weights}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) atol = 1.e-3 with self.test_session() as sess: _initialize_variables(self, monitored_session.Scaffold()) loss, train_result = sess.run((spec.loss, spec.train_op)) self.assertAllClose(expected_loss, loss, atol=atol) self.assertEqual( six.b('{0:s}{1:.3f}'.format(expected_train_result, expected_loss)), train_result) def test_multi_dim_weights_wrong_inner_dim(self): """Logits and labels of shape [2, 2, 3], weights [2, 1].""" head = head_lib.multi_label_head(n_classes=3, weight_column='weights') logits = np.array([[[-10., 10., -10.], [10., -10., 10.]], [[-12., 12., -12.], [12., -12., 12.]]], dtype=np.float32) labels = np.array([[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64) weights = np.array([[1.], [2.]], dtype=np.float32) def _train_op_fn(loss): del loss return control_flow_ops.no_op() spec = head.create_estimator_spec( features={'weights': weights}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[logits_shape: \] \[2 2 3\] \[weights_shape: \] \[2 1\]'): spec.loss.eval() def test_multi_dim_weights_wrong_outer_dim(self): """Logits and labels of shape [2, 2, 3], weights [2, 2, 3].""" head = head_lib.multi_label_head(n_classes=3, weight_column='weights') logits = np.array([[[-10., 10., -10.], [10., -10., 10.]], [[-12., 12., -12.], [12., -12., 12.]]], dtype=np.float32) labels = np.array([[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64) weights = np.array([[[1., 1., 1.], [1.5, 1.5, 1.5]], [[2., 2., 2.], [2.5, 2.5, 2.5]]], dtype=np.float32) weights_placeholder = array_ops.placeholder(dtype=dtypes.float32) def _train_op_fn(loss): del loss return control_flow_ops.no_op() spec = head.create_estimator_spec( features={'weights': weights_placeholder}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session(): _initialize_variables(self, monitored_session.Scaffold()) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[logits_shape: \] \[2 2 3\] \[weights_shape: \] \[2 2 3\]'): spec.loss.eval({weights_placeholder: weights}) def test_multi_dim_weighted_eval(self): """Logits and labels of shape [2, 2, 3], weights [2, 2].""" head = head_lib.multi_label_head(n_classes=3, weight_column='weights') logits = np.array([[[-10., 10., -10.], [10., -10., 10.]], [[-12., 12., -12.], [12., -12., 12.]]], dtype=np.float32) labels = np.array([[[1, 0, 0], [1, 0, 0]], [[0, 1, 1], [0, 1, 1]]], dtype=np.int64) weights = np.array([[1., 1.5], [2., 2.5]], dtype=np.float32) # loss = [[10 + 10 + 0, 0 + 0 + 10], [0 + 0 + 12, 12 + 12 + 0]] / 3 # = [[20/3, 10/3], [4, 8]] # loss = (1*20/3 + 1.5*10/3 + 2*4 + 2.5*8) / 4 = 9.9167 expected_loss = 9.9167 keys = metric_keys.MetricKeys expected_metrics = { keys.LOSS_MEAN: expected_loss * (4. / np.sum(weights)), # auc and auc_pr cannot be reliably calculated for only 4 samples, but # this assert tests that the algorithm remains consistent. keys.AUC: 0.4977, keys.AUC_PR: 0.6645, } self._test_eval( head=head, features={'weights': weights}, logits=logits, labels=labels, expected_loss=expected_loss, expected_metrics=expected_metrics) class PoissonRegressionHead(test.TestCase): def setUp(self): ops.reset_default_graph() def test_train(self): head = head_lib.poisson_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) labels = np.array([[1], [2], [3]], dtype=np.int32) # With x = exp(logits), z = labels. # loss = -ln(exp(-x) * (x^z) / z!) # = x - z * ln(x) + ln(z!) # = exp(logits) - labels * logits - ln(labels!) # But for ln(z!) and z > 1, the Stirling approximation is used # ln(z!) = z*ln(z) - z + 0.5*ln(2*pi*z) # loss = [exp(0) - 1 * 0 + ln(1!), # exp(-1) - 2 * (-1) + 2*ln(2) - 2 + 0.5*ln(2*pi*2), # exp(1) - 3 * 1 + 3*ln(3) - 3 + 0.5*ln(2*pi*3)] # = [1.0, 3.020, 1.482] # training_loss = (1.0 + 3.020 + 1.482) / 3 expected_loss = 1.834 atol = 0.001 expected_train_result = b'my_train_op' def _train_op_fn(loss): with ops.control_dependencies((check_ops.assert_near( math_ops.to_float(expected_loss), math_ops.to_float(loss), atol=atol, name='assert_loss'),)): return constant_op.constant(expected_train_result) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) loss, train_result = sess.run([spec.loss, spec.train_op]) self.assertAlmostEqual(expected_loss, loss, delta=atol) self.assertEqual(expected_train_result, train_result) def test_predict(self): head = head_lib.poisson_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) expected_predictions = np.exp(logits) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.PREDICT, logits=logits) # Assert spec contains expected tensors. keys = prediction_keys.PredictionKeys self.assertItemsEqual( (keys.PREDICTIONS, keys.LOGITS), spec.predictions.keys()) self.assertEqual(dtypes.float32, spec.predictions[keys.PREDICTIONS].dtype) self.assertEqual(dtypes.float32, spec.predictions[keys.LOGITS].dtype) # Assert predictions. with self.test_session(): _initialize_variables(self, spec.scaffold) self.assertAllClose( expected_predictions, spec.predictions[keys.PREDICTIONS].eval()) self.assertAllClose(logits, spec.predictions[keys.LOGITS].eval()) class LogisticRegressionHead(test.TestCase): def setUp(self): ops.reset_default_graph() def test_train(self): head = head_lib.logistic_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) labels = np.array([[.4], [.6], [.8]], dtype=np.float32) # Following the documentation in # tf.nn.sigmoid_cross_entropy_with_logits: # With x = logits, z = labels. # loss = max(x, 0) - x * z + log(1 + exp(-abs(x))) # loss = [0 - 0 * 0.4 + ln(1 + exp(-0)), # 0 + 1 * 0.6 + ln(1 + exp(-1)), # 1 - 1 * 0.8 + ln(1 + exp(-1))] # = [0.6931, 0.9133, 0.5133] # training_loss = (0.6931 + 0.9133 + 0.5133) / 3 expected_loss = 0.7066 atol = 0.001 expected_train_result = b'my_train_op' def _train_op_fn(loss): with ops.control_dependencies((check_ops.assert_near( math_ops.to_float(expected_loss), math_ops.to_float(loss), atol=atol, name='assert_loss'),)): return constant_op.constant(expected_train_result) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) loss, train_result = sess.run([spec.loss, spec.train_op]) self.assertAlmostEqual(expected_loss, loss, delta=atol) self.assertEqual(expected_train_result, train_result) def test_train_labels_too_large(self): head = head_lib.logistic_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) labels = np.array([[.4], [1.2], [.8]], dtype=np.float32) expected_train_result = b'my_train_op' def _train_op_fn(loss): del loss return constant_op.constant(expected_train_result) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[Labels must be in range \[0, 1\]\] .* \[\[0.4\]\[1.2\]\[0.8\]\]'): _ = sess.run(spec.loss) def test_train_labels_negative(self): head = head_lib.logistic_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) labels = np.array([[.4], [-0.2], [.8]], dtype=np.float32) expected_train_result = b'my_train_op' def _train_op_fn(loss): del loss return constant_op.constant(expected_train_result) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.TRAIN, logits=logits, labels=labels, train_op_fn=_train_op_fn) with self.test_session() as sess: _initialize_variables(self, spec.scaffold) with self.assertRaisesRegexp( errors.InvalidArgumentError, r'\[Labels must be in range \[0, 1\]\] .* \[\[0.4\]\[-0.2\]\[0.8\]\]' ): _ = sess.run(spec.loss) def test_predict(self): head = head_lib.logistic_regression_head() # Create estimator spec. logits = np.array([[0], [-1], [1]], dtype=np.float32) expected_predictions = 1. / (1. + np.exp(-logits)) spec = head.create_estimator_spec( features={'x': np.array(((42.,),), dtype=np.int32)}, mode=model_fn.ModeKeys.PREDICT, logits=logits) # Assert spec contains expected tensors. keys = prediction_keys.PredictionKeys self.assertItemsEqual( (keys.PREDICTIONS, keys.LOGITS), spec.predictions.keys()) self.assertEqual(dtypes.float32, spec.predictions[keys.PREDICTIONS].dtype) self.assertEqual(dtypes.float32, spec.predictions[keys.LOGITS].dtype) # Assert predictions. with self.test_session(): _initialize_variables(self, spec.scaffold) self.assertAllClose( expected_predictions, spec.predictions[keys.PREDICTIONS].eval()) self.assertAllClose(logits, spec.predictions[keys.LOGITS].eval()) if __name__ == '__main__': test.main()
apache-2.0
OpenDaisy/daisy-api
daisy/common/store_utils.py
1
5068
# Copyright 2014 IBM Corp. # # 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 import glance_store as store_api from oslo_config import cfg from oslo_log import log as logging import six.moves.urllib.parse as urlparse from daisy.common import utils import daisy.db as db_api from daisy import i18n from daisy import scrubber LOG = logging.getLogger(__name__) _ = i18n._ _LE = i18n._LE _LW = i18n._LW store_utils_opts = [ cfg.BoolOpt('use_user_token', default=True, help=_('Whether to pass through the user token when ' 'making requests to the registry.')), ] CONF = cfg.CONF CONF.register_opts(store_utils_opts) RESTRICTED_URI_SCHEMAS = frozenset(['file', 'filesystem', 'swift+config']) def safe_delete_from_backend(context, image_id, location): """ Given a location, delete an image from the store and update location status to db. This function try to handle all known exceptions which might be raised by those calls on store and DB modules in its implementation. :param context: The request context :param image_id: The image identifier :param location: The image location entry """ try: ret = store_api.delete_from_backend(location['url'], context=context) location['status'] = 'deleted' if 'id' in location: db_api.get_api().image_location_delete(context, image_id, location['id'], 'deleted') return ret except store_api.NotFound: msg = _LW('Failed to delete image %s in store from URI') % image_id LOG.warn(msg) except store_api.StoreDeleteNotSupported as e: LOG.warn(utils.exception_to_str(e)) except store_api.UnsupportedBackend: exc_type = sys.exc_info()[0].__name__ msg = (_LE('Failed to delete image %(image_id)s from store: %(exc)s') % dict(image_id=image_id, exc=exc_type)) LOG.error(msg) def schedule_delayed_delete_from_backend(context, image_id, location): """ Given a location, schedule the deletion of an image location and update location status to db. :param context: The request context :param image_id: The image identifier :param location: The image location entry """ __, db_queue = scrubber.get_scrub_queues() if not CONF.use_user_token: context = None ret = db_queue.add_location(image_id, location, user_context=context) if ret: location['status'] = 'pending_delete' if 'id' in location: # NOTE(zhiyan): New added image location entry will has no 'id' # field since it has not been saved to DB. db_api.get_api().image_location_delete(context, image_id, location['id'], 'pending_delete') else: db_api.get_api().image_location_add(context, image_id, location) return ret def delete_image_location_from_backend(context, image_id, location): """ Given a location, immediately or schedule the deletion of an image location and update location status to db. :param context: The request context :param image_id: The image identifier :param location: The image location entry """ deleted = False if CONF.delayed_delete: deleted = schedule_delayed_delete_from_backend(context, image_id, location) if not deleted: # NOTE(zhiyan) If image metadata has not been saved to DB # such as uploading process failure then we can't use # location status mechanism to support image pending delete. safe_delete_from_backend(context, image_id, location) def validate_external_location(uri): """ Validate if URI of external location are supported. Only over non-local store types are OK, i.e. S3, Swift, HTTP. Note the absence of 'file://' for security reasons, see LP bug #942118, 1400966, 'swift+config://' is also absent for security reasons, see LP bug #1334196. :param uri: The URI of external image location. :return: Whether given URI of external image location are OK. """ # TODO(zhiyan): This function could be moved to glance_store. # TODO(gm): Use a whitelist of allowed schemes scheme = urlparse.urlparse(uri).scheme return (scheme in store_api.get_known_schemes() and scheme not in RESTRICTED_URI_SCHEMAS)
apache-2.0
maxwelltsai/SiMon
SiMon/module_common.py
1
28320
import datetime import abc import glob import os import subprocess import signal import time import sys import re import shutil from SiMon.utilities import Utilities try: import configparser as cp # Python 3 only except ImportError: import ConfigParser as cp # Python 2 only class SimulationTask(object): """ A simulation task is a single simulation which the user requests to finish. It is associated with 1) a set of initial conditions specified in the input file, 2) a (bash) script to start up the code, 3) the status of the simulation (RUN/STOP/model time, start timestamp, last output timestamp, parent simulation ID if it is a restart, etc), and 4) the ending time of the simulation. Notes ----- Traverse the directory structure: A hierarchical directory structure may form for a simulation that has been started for multiple times. For instance, a simulation is running on the directory '/sim1'. It crashes at T=120. So SiMon restarts it by creating a restart directory '/sim1/restart1'. 'restart1' runs until T=200, and then again crashes. So SiMon creates '/sim1/restart1/restart1' in attempt to start from T=200. """ # Constants STATUS_NEW = 0x0 # newly initialized simulation STATUS_STOP = 0x1 # crashed simulation STATUS_RUN = 0x2 # the simulation is running STATUS_STALL = 0x3 # the simulation is running, but stalled STATUS_DONE = 0x4 # the simulation has finished STATUS_ERROR = 0x5 # the simulation is crashed and not possible to be restarted STATUS_LABEL = ["NEW", "STOP", "RUN", "STALL", "DONE", "ERROR"] __metaclass__ = abc.ABCMeta def __init__( self, sim_id, name, full_dir, status, mode="daemon", t_min=0, t_max=0, restarts=None, logger=None, ): """ :param sim_id: :param name: Usually the name of the simulation directory. :type name: basestring :param full_dir: The full path of the simulation directory. :param status: RUN, STOP, RESTARTED :param t_min: default as 0 :param t_max: default as 0 :param restarts: default as None :return: """ self.id = sim_id self.name = name self.full_dir = full_dir self.status = status self.logger = logger self.error_type = "" self.config_file = "SiMon.conf" # the file name of the config file to be placed in each simulation directory self.config = None self.t = 0 # the current model time self.t_min = t_min # minimum time for the simulation to start self.t_max = t_max # maximum time marking the completion of the simulation self.t_max_extended = t_max # extended t_max by restarts self.mtime = ( 0 # timestamp of the last modification of the simulation output files ) self.ctime = 0 # timestamp of the creation of the simulation output files # the candidate instance ID to restart in case crashes # (-1: no candidate, restart from itself;) # (>0: restart from the candidate. If the candidate cannot restart, try siblings) self.cid = -1 self.level = 0 self.parent_id = -1 self.mode = mode self.niceness = ( 0 # Priority, same as UNIX (-20 ~ 19, the lower ==> higher priority) ) self.maximum_number_of_checkpoints = 20 if restarts is None: self.restarts = list() else: self.restarts = restarts # children self.parse_config_file() self.sim_get_status() def __repr__(self, level=0): if level == 0: ret = "[%s] %s\n" % ( SimulationTask.STATUS_LABEL[self.status], self.full_dir, ) else: # placeholder_dash = "|" + '-' * (level * 4) placeholder_dash = "| " placeholder_space = " " * ((level - 1) * 4) mtime_str = datetime.datetime.fromtimestamp(self.mtime).strftime( "%m-%d %H:%M" ) prefix = "T: %g >> %g >> %g" % ( int(self.t_min), int(self.t), int(self.t_max), ) suffix = mtime_str progress_bar = Utilities.progress_bar( self.t, self.t_max, self.t_min, prefix=prefix, suffix=suffix ) info = "%s \t%s\t" % ( Utilities.highlighted_text(str(self.name), "cyan", bold=True), progress_bar, ) ret = "[%s]\t%s%d%s%s\n" % ( SimulationTask.STATUS_LABEL[self.status], placeholder_space, self.id, placeholder_dash, info, ) # ret = " "*level+str(self.id)+repr(self.name)+"\n" for child in self.restarts: ret += child.__repr__(level + 1) return ret def parse_config_file(self): """ Parse the configure file (SiMon.conf) for the simulation. If the file does not exist, a new file with default values will be created. :return: return 0 if succeed, -1 if failed (file not exist, and cannot be created). If the file does not exist but a new file with default values is created, the method returns 1. """ conf_fn = os.path.join(self.full_dir, self.config_file) conf = cp.ConfigParser() if os.path.isfile(conf_fn): conf.read(conf_fn) self.config = conf # synchronize config options to attributes if self.config.has_option("Simulation", "T_end"): self.t_max = self.config.getfloat("Simulation", "T_end") if self.config.has_option("Simulation", "T_start"): self.t_min = self.config.getfloat("Simulation", "T_start") if self.config.has_option("Simulation", "Niceness"): self.niceness = self.config.getint("Simulation", "Niceness") if self.config.has_option("Simulation", "Maximum_n_checkpoints"): self.maximum_number_of_checkpoints = self.config.getint( "Simulation", "Maximum_n_checkpoints" ) else: if self.id > 0: msg = ( "WARNING: Simulation configuration file not exists! " "Creating default configuration as SiMon.conf.\n" ) if self.logger is not None: self.logger.warning(msg) # TODO: write default config file return 0 def sim_start(self): """ Start a new simulation. :return: Return 0 if succeed, -1 if failed. If the simulation is already started, then it will do nothing but return 1. """ start_script_template = "%s & echo $!>.process.pid" orig_dir = os.getcwd() os.chdir(self.full_dir) # Test if the process is running accoding to the .process.pid file if os.path.isfile(".process.pid"): # if the PID file exists, try to read the process ID f_pid = open(".process.pid", "r") pid = int(f_pid.readline().strip()) f_pid.close() if pid > 0: try: os.kill(pid, 0) return 1 # if no exception, the process is already running except (ValueError, OSError): pass # process not started yet # If the process is not started yet, then start it in a normal way if self.config.has_option("Simulation", "Start_command"): start_cmd = self.config.get("Simulation", "Start_command") # self.proc = subprocess.Popen(start_cmd, shell=True) os.system(start_script_template % start_cmd) # sleep for a little while to make sure that the pid file exist time.sleep(0.5) fpid = open(".process.pid", "r") pid = int(fpid.readline()) fpid.close() self.config.set("Simulation", "PID", str(pid)) self.config.set("Simulation", "Timestamp_started", str(time.time())) self.config.write(open(self.config_file, "w")) if self.logger is not None: msg = "Simulation %s started, PID = %d" % (self.name, pid) self.logger.info(msg) else: return -1 os.chdir(orig_dir) return 0 def sim_restart(self): """ Restart the simulation. :return: Return 0 if succeed, -1 if failed. If the simulation is already running, then restart is not necessary, the method will do nothing but return 1. If the simulation is marked as 'STOP' or 'ERROR', then return 2 and do nothing. """ if os.path.isfile("STOP") or os.path.isfile("ERROR"): print( "Restart skipped due to the existence of the STOP file or ERROR file." ) return 2 # Test if the process is running restart_script_template = "%s & echo $!>.process.pid" orig_dir = os.getcwd() os.chdir(self.full_dir) print("The full dir is %s" % self.full_dir) print("restarting simulation: %s" % self.full_dir) if self.logger is not None: self.logger.info("Restarting simulation: %s" % self.full_dir) # Test if the process is running accoding to the .process.pid file if os.path.isfile(".process.pid"): # if the PID file exists, try to read the process ID f_pid = open(".process.pid", "r") pid = int(f_pid.readline().strip()) f_pid.close() if pid > 0: try: os.kill(pid, 0) return 1 # if no exception, the process is already running except (ValueError, OSError): # process not started yet # check how many times the simulation has been restarted restarts = glob.glob("restart*/") n_restarts = len(restarts) print(n_restarts, self.config.getint("Simulation", "Max_restarts")) # check whether it exceeds the maximum times of restarts specified in the per-sim config file if self.config.has_option("Simulation", "Max_restarts"): if n_restarts > self.config.getint( "Simulation", "Max_restarts" ): # if exceed, create an empty file called 'ERROR' f_error = open("ERROR", "w") f_error.close() msg = ( "Simulation %s has been restarted too many times. Further restart skipped..." % self.full_dir ) print(msg) if self.logger is not None: self.logger.error(msg) return -2 else: # if the config entry Max_restarts does not exist in the config file, there is no restart limit pass # now try to restart the simulation if self.config.has_option("Simulation", "Restart_command"): restart_cmd = self.config.get("Simulation", "Restart_command") if restart_cmd is not "" and restart_cmd.strip() is not "None": msg = "Restarting simulation: %s" % self.full_dir print(msg) if self.logger is not None: self.logger.info(msg) # create a restart dir restart_dir = "restart%d" % (n_restarts + 1) os.mkdir(restart_dir) os.chdir(restart_dir) os.system(restart_script_template % restart_cmd) # sleep for a little while to make sure that the pid file exist time.sleep(0.5) fpid = open(".process.pid", "r") pid = int(fpid.readline()) fpid.close() self.config.set("Simulation", "PID", str(pid)) self.config.set( "Simulation", "Timestamp_started", str(time.time()) ) self.config.write(open(self.config_file, "w")) else: msg = ( "%s: unable to restart because the restart command is not properly configured." % self.name ) print(msg) if self.logger is not None: self.logger.error(msg) return -1 else: msg = ( "%s: unable to restart because the restart command is not configured." % self.name ) print(msg) if self.logger is not None: self.logger.error(msg) return -1 os.chdir(orig_dir) return 0 def sim_get_model_time(self): """ Get the model time of the simulation. Because different codes have different output formats, there is no generic way to obtain the model time. The user is required to implement this method to properly obtain the time. :return: the current model time """ orig_dir = os.getcwd() os.chdir(self.full_dir) if self.config.has_option("Simulation", "Output_file"): output_file = self.config.get("Simulation", "Output_file") regex = re.compile("\\d+") if os.path.isfile(output_file): last_line = subprocess.check_output(["tail", "-1", output_file]).decode( "utf-8" ) res = regex.findall(last_line) if len(res) > 0: self.t = float(res[0]) os.chdir(orig_dir) return self.t def sim_get_model_start_time(self): """ Get the t_min value of the current model :return: The starting time of the current model. By default, t_min = 0. But if a model is restarted, then it is possible that t_min equals the time of the restartable snapshot. The user is required to implement this method properly. """ if self.t_min != 0.0: return self.t_min else: return 0.0 def sim_get_model_termination_time(self): """ Get the time t_max by which the model is considered finished. Normally this value is obtained by parsing the config file, but the user may override it. :return: The termination time """ return self.t_max def sim_get_status(self): """ Get the current status of the simulation. Update the config file if necessary. :return: The code of the current simulation status. """ if self.config is None: return 0 orig_dir = os.getcwd() os.chdir(self.full_dir) self.t = self.sim_get_model_time() self.t_min = self.sim_get_model_start_time() # Check the last output time from either the output file or the error file output_file = "" if self.config.has_option("Simulation", "Output_file"): output_file = self.config.get("Simulation", "Output_file") if os.path.isfile(output_file): self.mtime = os.stat(output_file).st_mtime elif self.config.has_option("Simulation", "Error_file"): error_file = self.config.get("Simulation", "Error_file") if os.path.isfile(error_file_file): self.mtime = os.stat(error_file).st_mtime # Get the starting time of the simulation if self.config.has_option("Simulation", "Timestamp_started"): self.ctime = self.config.getfloat("Simulation", "Timestamp_started") # Determine whether the simulation is running using the process ID if os.path.isfile(".process.pid"): # if the PID file exists, try to read the process ID f_pid = open(".process.pid", "r") pid = int(f_pid.readline().strip()) f_pid.close() if pid == 0: if self.mtime == 0: self.status = SimulationTask.STATUS_NEW else: try: os.kill( pid, 0 ) # This just checks if the process is running. It doesn't kill the process # It is running. Check if stalled. # The default value is large to prevent a slow simulation to be mistakenly killed stall_time = 6.0e6 # after 6.e6 seconds if the code doesn't advance, it is considered stalled if self.config.has_option("Simulation", "Stall_time"): # Allow overriding the stall time using the per-simulation config file stall_time = self.config.getfloat("Simulation", "Stall_time") if time.time() - self.mtime > stall_time: self.status = SimulationTask.STATUS_STALL if self.logger is not None: mtime_str = datetime.datetime.fromtimestamp( self.mtime ).strftime("%m-%d %H:%M") msg = ( "job %s is running [PID=%d], but no update in its output file (%s) since %s. " "The stall time of this task is %s sec. " "Marked as STALL" % (self.name, pid, output_file, mtime_str, stall_time) ) print(msg) self.logger.info(msg) else: self.status = SimulationTask.STATUS_RUN except (OSError, ValueError) as e: # The process is not running, check if stopped or done if ( self.t >= self.t_max or self.status == SimulationTask.STATUS_DONE ): self.status = SimulationTask.STATUS_DONE else: if self.ctime == 0.0: self.status = SimulationTask.STATUS_NEW elif os.path.isfile("ERROR"): self.status = SimulationTask.STATUS_ERROR else: self.status = SimulationTask.STATUS_STOP os.chdir(orig_dir) return self.status def sim_kill(self): """ Forcibly kill (i.e. terminate) the current simulation. Practically, this method terminates the process of the simulation code and sets the simulation status to STOP. :return: Return 0 if succeed, -1 if failed. If the simulation is not running, then it cannot be killed, causing the method to do nothing but return 1. """ orig_dir = os.getcwd() os.chdir(self.full_dir) # Find the process by PID if os.path.isfile(".process.pid"): # if the PID file exists, try to read the process ID f_pid = open(".process.pid", "r") pid = int(f_pid.readline().strip()) f_pid.close() try: os.kill(pid, signal.SIGKILL) msg = "Simulation %s (PID: %d) killed." % (self.name, pid) print(msg) if self.logger is not None: self.logger.info(msg) except OSError as err: msg = "%s: Cannot kill the job `%s` with PID = %d\n" % ( str(err), self.name, pid, ) print(msg) if self.logger is not None: self.logger.error(msg) os.chdir(orig_dir) return 0 def sim_stop(self): """ Submit a request to the simulation code, in attempt to stop the simulation before it finishes the originally planned time checkpoint. This method will ask the code to stop the simulation by itself (if supported), rather than forcibly killing the simulation process. :return: Return 0 if succeed, -1 if failed. If the simulation is not running, then it cannot be stopped, causing the method to do nothing but return 1. """ # Create an empty file called 'STOP'. The integrator that detects this file will (hopefully) stop the # integration. orig_dir = os.getcwd() os.chdir(self.full_dir) stop_file = open(os.path.join(self.full_dir, "STOP"), "w") stop_file.close() msg = "A stop request has been sent to simulation %s" % self.name print(msg) if self.logger is not None: self.logger.info(msg) os.chdir(orig_dir) return 0 def sim_backup_checkpoint(self): """ Back up a snapshot of the latest restart files or simulation snapshot. In case of code crash, the backup files can be used for restarting. :return: Return 0 if succeed, -1 if failed. If the existing simulation snapshot is already the latest version, backup is not necessary, causing the method to do nothing but return 1. """ # Try to get the restartable checkpoint file name from the config file orig_dir = os.getcwd() os.chdir(self.full_dir) if self.config.has_option("Simulation", "Restart_file"): restart_fn = self.config.get("Simulation", "Restart_file") ts = ( time.time() ) # get the timestamp as part of the backup restart file name backup_restart_fn = "restart.tmp.%d" % int(ts) if os.path.isfile(os.path.join(self.full_dir, restart_fn)): shutil.copyfile( os.path.join(self.full_dir, restart_fn), os.path.join(self.full_dir, backup_restart_fn), ) msg = "Restart file has been backup as " + backup_restart_fn print(msg) if self.logger is not None: self.logger.info(msg) # delete the oldest backup if there is a limit of maximum number of backup files backup_file_list = sorted( glob.glob(os.path.join(self.full_dir, "restart.tmp.*")) ) if 0 < self.maximum_number_of_checkpoints < len(backup_file_list): for backup_restart_del_fn in backup_file_list[ : -abs(self.maximum_number_of_checkpoints) ]: os.remove(os.path.join(self.full_dir, backup_restart_del_fn)) else: # Without knowing the name of the restartable snapshot, SiMon will not be able to backup if self.logger is not None: self.logger.info( "SiMon does not know how to backup the current simulation %s" % self.name ) return -1 os.chdir(orig_dir) return 0 def sim_delete(self): """ Delete the simulation data (including restarted simulation data). :return: Return 0 if succeed, -1 if failed. A simulation cannot be deleted if it is currently running. In this case, this method does nothing but just return 1. """ if self.mode == "interactive": confirm = Utilities.get_input( "Are you sure you would like to delete the instance " "#%d and its sub-instances? [Y/N] " % self.id ).lower() if confirm != "y": return 1 else: # TODO: code will not goes here because no functions in daemon mode will call inst_delete shutil.rmtree(self.full_dir) return 0 return 0 def sim_shell_exec(self, shell_command=None): """ Execute a shell command under the data directory of the simulation. :param shell_command: the shell command to execute :return: Return 0 if succeed, -1 if failed. """ if shell_command is None: shell_command = Utilities.get_input("CMD>> ") sys.stdout.write( "========== Command on #%d ==> %s (PWD=%s) ==========\n" % (self.id, self.full_dir, self.full_dir) ) original_dir = os.getcwd() os.chdir(self.full_dir) os.system(shell_command) sys.stdout.write( "========== [DONE] Command on #%d ==> %s (PWD=%s) ==========\n" % (self.id, self.full_dir, self.full_dir) ) os.chdir(original_dir) return 0 def sim_clean(self): """ Clean-up the simulation directory. Leaving only input files and restart file there. :return: Return 0 if succeed, -1 if failed. If the simulation is running, clean cannot be performed. In such case, the method does nothing but returns 1. """ return 0 def sim_reset(self): """ Clean-up the simulation directory. Leaving only input files in the simulation directory. Reset the current Simulation status to NOT STARTED. :return: Return 0 if succeed, -1 if failed. """ return 0 def sim_init(self): """ Perform necessary initialization procedures in order to start the simulation. Note that this method will NOT start the simulation. It will only make the simulation ready to start when sim_start() is called. :return: Return 0 if succeed, -1 if failed. If the simulation is running/stopped/finished, the method does nothing but just return 1. """ return 0 def sim_finalize(self): """ Finalize the simulation (e.g. perform data processing) after the simulation is finished. :return: Return 0 if succeed, -1 if failed. If the simulation is running/stopped or not yet started, the method does nothing but return 1. """ return 0 def sim_collect_recent_output_message(self, lines=20): """ Collect the recent lines of output/error messages, generated by the simulation code. :return: Return the messages as a combined string if available. Otherwise return an empty string. """ if self.config.has_option("Simulation", "Output_file"): output_file = self.config.get("Simulation", "Output_file") sys.stdout.write( "========== Diagnose for #%d ==> %s ==========\n" % (self.id, self.full_dir) ) check_dir_name = self.full_dir original_dir = os.getcwd() os.chdir(check_dir_name) os.system("\ntail -%d %s" % (lines, output_file)) restart_dir = sorted(glob.glob("restart*/")) for r_dir in restart_dir: os.chdir(r_dir) sys.stdout.write( "========== Diagnose for restart ==> %s ==========\n" % r_dir ) os.system("\ntail -%d %s" % (lines, output_file)) os.chdir("..") os.chdir(original_dir) return str()
bsd-2-clause
eehlers/reposit
dev_tools/find_replace.py
1
7783
################################################################################## # # find_replace.py - perform a recursive find/replace on a directory tree # # To use this script, first edit it as required (see below) then invoke # as follows: # # find_replace.py -[mode] # Where [mode] is either of: # d - display proposed substitutions # s - perform the substitutions # Plus optionally # v - verbose # # Settings within this script: # # ROOT_DIRS # The list of root folders from which you want the find/replace to begin. # # SUBSTITUTIONS # A list of one or more regexes to be performed on each file. # # INCLUDE_FILES # Regexes to indicate names of files to be processed by the find/replace. # # IGNORE_FILES # Regexes to indicate names of files to be ignored by the find/replace. # NB the script tests first whether the file is to be ignored, then whether it # is to be included. # # IGNORE_DIRS # Regexes to indicate directories to be ignored by the find/replace. # ################################################################################## import sys import os import re import getopt import shutil # ROOT_DIRS - The list of root folders from which # you want the find/replace to begin. ROOT_DIRS = ( '/media/windows/linux/repos/reposit/quantlib/log4cxx/src/main/include/log4cxx', '/media/windows/linux/repos/reposit/quantlib/reposit', '/media/windows/linux/repos/reposit/quantlib/QuantLibAddin2', '/media/windows/linux/repos/reposit/quantlib/QuantLibXL2', ) # CALLBACK FUNCTIONS - Called from regexes which require multiple passes # Convert case def toLower(m): return m.group(0).lower() # Replace pre increment/decrement with post increment/decrement regex1 = re.compile(r'(\w+?)\+\+') regex2 = re.compile(r'(\w+?)--') def callback_example(m): x = regex1.sub('++\1', m.group(2)) x = regex2.sub('--\1', x) return m.group(1) + x + ')' # SUBSTITUTIONS - A list of regexes to be performed. # Each substitution is in the format # (re.compile('find text'), 'replace text'), SUBSTITUTIONS = ( ## Uncomment and modify the examples as required. ## 1) Simple ## Straight find/replace. # (re.compile('aaa'), 'bbb'), ## 2) Group ## Use parentheses to indicate group(s) in the find text. ## Use \x in the replace text to refer to a group, where x = group number. ## Replace text must be a raw string r'' instead of normal string ''. # (re.compile('ccc(.*)ccc'), r'ddd\1ddd'), ## 3) Newline flag ## Use re.S to indicate that . matches newline. ## This allows you to perform substitutions that span lines. # (re.compile('eee.*eee', re.S), 'fff'), ## 4) Multiline flag ## Use re.M to anchor ^ and $ to begin/end of lines within buffer. # (re.compile('^ggg.*ggg$', re.M | re.S), 'hhh'), ## 5) Conversion function ## Instead of replacement text, provide name of conversion function. # (re.compile('abcDEFghi'), toLower), ## Frequently used (re.compile('1_7_0'), '1_8_0'), (re.compile('1\.7\.0'), '1.8.0'), (re.compile('0x010700'), '0x010800'), (re.compile('R010700f0'), 'R010800f0'), (re.compile('0\.10\.0f5'), '0.10.0f6'), (re.compile('0x001000f5'), '0x001000f6'), ) # INCLUDE_FILES # Regexes to indicate names of files to be processed by the find/replace. # Leave this list empty to process all files in the directory tree # except for those excluded by IGNORE_FILES. INCLUDE_FILES = ( # re.compile(r'^.+\.[ch]pp$'), ) # IGNORE_FILES # Regexes to indicate names of files to be ignored by the find/replace. IGNORE_FILES = ( re.compile('^.+\.bmp$'), re.compile('^.+\.exe$'), re.compile('^.+\.exp$'), re.compile('^.+\.ico$'), re.compile('^.+\.jpg$'), re.compile('^.+\.la$'), re.compile('^.+\.lib$'), re.compile('^.+\.log$'), re.compile('^.+\.ncb$'), re.compile('^.+\.o$'), re.compile('^.+\.pdf$'), re.compile('^.+\.plg$'), re.compile('^.+\.png$'), re.compile('^.+\.pyc$'), re.compile('^.+\.xls$'), re.compile('^.+\.zip$'), re.compile('^.+~$'), re.compile('^\.'), re.compile('^Announce\.txt$'), re.compile('^ChangeLog\.txt$'), re.compile('^changes\..+$'), re.compile('^config\.status$'), re.compile('^configure$'), re.compile('^design\.docs$'), re.compile('^history\.docs$'), re.compile('^libtool$'), re.compile('^Makefile$'), re.compile('^Makefile\.in$'), re.compile('^NEWS\.txt$'), re.compile('^News\.txt$'), re.compile('^objecthandler\.cpp$'), re.compile('^ohfunctions\.cpp$'), re.compile('^todonando\.txt$'), ) # IGNORE_DIRS # Regexes to indicate directories to be ignored by the find/replace. IGNORE_DIRS = ( re.compile('^\.'), re.compile('^\.svn$'), re.compile('^autom4te\.cache$'), re.compile('^build$'), re.compile('^configure$'), re.compile('^dev_tools$'), re.compile('^framework$'), re.compile('^html$'), re.compile('^Launcher$'), re.compile('^lib$'), #re.compile('^log4cxx$'), re.compile('^QuantLib$'), re.compile('^QuantLib-site$'), re.compile('^QuantLib-SWIG$'), re.compile('^Workbooks$'), ) def prompt_exit(msg='', status=0): if msg: print msg #if sys.platform == 'win32': # raw_input('press any key to exit') sys.exit(status) def usage(): prompt_exit('usage: ' + sys.argv[0] + ' -[mode]' + ''' where [mode] is either of: d - display proposed substitutions s - perform the substitutions plus optionally v - verbose ''') def logMessage(msg, priority = 1): global logLevel if priority <= logLevel: print msg def ignoreItem(item, ignoreList): for r in ignoreList: if r.match(item): return True def includeItem(item, includeList): if len(includeList) == 0: return True for r in includeList: if r.match(item): return True def processFile(fullPath): global execSub f = open(fullPath, 'r') buf = f.read() bufNew = buf for sub in SUBSTITUTIONS: r, repl = sub bufNew = r.sub(repl, bufNew) if bufNew == buf: logMessage('no sub required in file ' + fullPath) else: if execSub: logMessage('*** overwriting file ' + fullPath, 0) f = open(fullPath, 'w') f.write(bufNew) else: logMessage('*** sub required in file ' + fullPath, 0) def processDir(ignore, dirPath, nameList): i = len(nameList) - 1 while i > -1: name = nameList[i] fullPath = os.path.join(dirPath, name).replace('\\', '/') logMessage('processing path ' + fullPath) if os.path.isdir(fullPath): logMessage('dir') if ignoreItem(name, IGNORE_DIRS): logMessage('ignoring directory ' + fullPath) del nameList[i] elif os.path.isfile(fullPath): if ignoreItem(name, IGNORE_FILES): logMessage('ignoring file ' + fullPath) del nameList[i] else: logMessage('testing filename ' + name) if includeItem(name, INCLUDE_FILES): processFile(fullPath) else: prompt_exit('unknown file type: ' + fullPath) i -= 1 try: opts, args = getopt.getopt(sys.argv[1:], 'dsvh', 'help' ) except getopt.GetoptError: usage() logLevel = 0 execSub = -1 for o, a in opts: if o in ('-h', '--help'): usage() elif o == '-d': execSub = 0 elif o == '-s': execSub = 1 elif o == '-v': logLevel = 1 if execSub == -1: usage() for rootDir in ROOT_DIRS: if not os.path.isdir(rootDir): prompt_exit('invalid directory: ' + rootDir) os.path.walk(rootDir, processDir, None) prompt_exit()
bsd-3-clause
mumuwoyou/vnpy-master
vnpy/api/ksotp/pyscript/generate_md_functions.py
25
7677
# encoding: UTF-8 __author__ = 'CHENXY' from string import join from ksotp_struct import structDict def processCallBack(line): orignalLine = line line = line.replace('\tvirtual void ', '') # 删除行首的无效内容 line = line.replace('{};\n', '') # 删除行尾的无效内容 content = line.split('(') cbName = content[0] # 回调函数名称 cbArgs = content[1] # 回调函数参数 if cbArgs[-1] == ' ': cbArgs = cbArgs.replace(') ', '') else: cbArgs = cbArgs.replace(')', '') cbArgsList = cbArgs.split(', ') # 将每个参数转化为列表 cbArgsTypeList = [] cbArgsValueList = [] for arg in cbArgsList: # 开始处理参数 content = arg.split(' ') if len(content) > 1: cbArgsTypeList.append(content[0]) # 参数类型列表 cbArgsValueList.append(content[1]) # 参数数据列表 createTask(cbName, cbArgsTypeList, cbArgsValueList, orignalLine) createProcess(cbName, cbArgsTypeList, cbArgsValueList) def createTask(cbName, cbArgsTypeList, cbArgsValueList, orignalLine): # 从回调函数生成任务对象,并放入队列 funcline = orignalLine.replace('\tvirtual void ', 'void ' + apiName + '::') funcline = funcline.replace('{};', '') ftask.write(funcline) ftask.write('{\n') ftask.write("\tTask task = Task();\n") ftask.write("\ttask.task_name = " + cbName.upper() + ";\n") # define常量 global define_count fdefine.write("#define " + cbName.upper() + ' ' + str(define_count) + '\n') define_count = define_count + 1 # switch段代码 fswitch.write("case " + cbName.upper() + ':\n') fswitch.write("{\n") fswitch.write("\tthis->" + cbName.replace('On', 'process') + '(task);\n') fswitch.write("\tbreak;\n") fswitch.write("}\n") fswitch.write("\n") for i, type_ in enumerate(cbArgsTypeList): if type_ == 'int': ftask.write("\ttask.task_id = " + cbArgsValueList[i] + ";\n") elif type_ == 'bool': ftask.write("\ttask.task_last = " + cbArgsValueList[i] + ";\n") elif 'RspInfoField' in type_: ftask.write("\tif (pRspInfo)\n") ftask.write("\t{\n") ftask.write("\t\ttask.task_error = " + cbArgsValueList[i] + ";\n") ftask.write("\t}\n") ftask.write("\telse\n") ftask.write("\t{\n") ftask.write("\t\t%s empty_error = %s();\n" %(type_, type_)) ftask.write("\t\tmemset(&empty_error, 0, sizeof(empty_error));\n") ftask.write("\t\ttask.task_error = empty_error;\n") ftask.write("\t}\n") else: # 这里主要针对金仕达接口,对传入的主数据的对象指针也进行空指针检查 ftask.write("\n") ftask.write("\tif (%s) \n" %cbArgsValueList[i].replace('*', '')) ftask.write("\t{\n") ftask.write("\t\ttask.task_data = " + cbArgsValueList[i] + ";\n") ftask.write("\t}\n") ftask.write("\telse\n") ftask.write("\t{\n") ftask.write("\t\t%s empty_data = %s();\n" %(type_, type_)) ftask.write("\t\tmemset(&empty_data, 0, sizeof(empty_data));\n") ftask.write("\t\ttask.task_data = empty_data;\n") ftask.write("\t}\n") ftask.write("\n") #ftask.write("\ttask.task_data = " + cbArgsValueList[i] + ";\n") # 老版本 ftask.write("\tthis->task_queue.push(task);\n") ftask.write("};\n") ftask.write("\n") def createProcess(cbName, cbArgsTypeList, cbArgsValueList): # 从队列中提取任务,并转化为python字典 fprocess.write("void " + apiName + '::' + cbName.replace('On', 'process') + '(Task task)' + "\n") fprocess.write("{\n") fprocess.write("\tPyLock lock;\n") onArgsList = [] for i, type_ in enumerate(cbArgsTypeList): if 'RspInfoField' in type_: fprocess.write("\t"+ type_ + ' task_error = any_cast<' + type_ + '>(task.task_error);\n') fprocess.write("\t"+ "dict error;\n") struct = structDict[type_] for key in struct.keys(): fprocess.write("\t"+ 'error["' + key + '"] = task_error.' + key + ';\n') fprocess.write("\n") onArgsList.append('error') elif type_ in structDict: fprocess.write("\t"+ type_ + ' task_data = any_cast<' + type_ + '>(task.task_data);\n') fprocess.write("\t"+ "dict data;\n") struct = structDict[type_] for key in struct.keys(): fprocess.write("\t"+ 'data["' + key + '"] = task_data.' + key + ';\n') fprocess.write("\n") onArgsList.append('data') elif type_ == 'bool': onArgsList.append('task.task_last') elif type_ == 'int': onArgsList.append('task.task_id') onArgs = join(onArgsList, ', ') fprocess.write('\tthis->' + cbName.replace('On', 'on') + '(' + onArgs +');\n') fprocess.write("};\n") fprocess.write("\n") def processFunction(line): line = line.replace('\tvirtual int ', '') # 删除行首的无效内容 line = line.replace(') = 0;\n', '') # 删除行尾的无效内容 content = line.split('(') fcName = content[0] # 回调函数名称 fcArgs = content[1] # 回调函数参数 fcArgs = fcArgs.replace(')', '') fcArgsList = fcArgs.split(', ') # 将每个参数转化为列表 fcArgsTypeList = [] fcArgsValueList = [] for arg in fcArgsList: # 开始处理参数 content = arg.split(' ') if len(content) > 1: fcArgsTypeList.append(content[0]) # 参数类型列表 fcArgsValueList.append(content[1]) # 参数数据列表 if len(fcArgsTypeList)>0 and fcArgsTypeList[0] in structDict: createFunction(fcName, fcArgsTypeList, fcArgsValueList) def createFunction(fcName, fcArgsTypeList, fcArgsValueList): type_ = fcArgsTypeList[0] struct = structDict[type_] ffunction.write(fcName + '\n') ffunction.write('{\n') ffunction.write('\t' + type_ +' myreq = ' + type_ + '();\n') ffunction.write('\tmemset(&myreq, 0, sizeof(myreq));\n') for key, value in struct.items(): if value == 'string': line = '\tgetChar(req, "' + key + '", myreq.' + key + ');\n' elif value == 'int': line = '\tgetInt(req, "' + key + '", &myreq.' + key + ');\n' elif value == 'double': line = '\tgetDouble(req, "' + key + '", &myreq.' + key + ');\n' ffunction.write(line) ffunction.write('\tint i = this->api->' + fcName + '(&myreq, nRequestID);\n') ffunction.write('\treturn i;\n') ffunction.write('};\n') ffunction.write('\n') ######################################################### apiName = 'MdApi' fcpp = open('KSOTPMdApi.h', 'r') ftask = open('ksotp_md_task.cpp', 'w') fprocess = open('ksotp_md_process.cpp', 'w') ffunction = open('ksotp_md_function.cpp', 'w') fdefine = open('ksotp_md_define.cpp', 'w') fswitch = open('ksotp_md_switch.cpp', 'w') define_count = 1 for line in fcpp: if "\tvirtual void On" in line: processCallBack(line) elif "\tvirtual int" in line: processFunction(line) fcpp.close() ftask.close() fprocess.close() ffunction.close() fswitch.close() fdefine.close()
mit
TeslaProject/external_chromium_org
third_party/cython/src/Tools/site_scons/site_tools/pyext.py
104
9274
"""SCons.Tool.pyext Tool-specific initialization for python extensions builder. AUTHORS: - David Cournapeau - Dag Sverre Seljebotn """ # # __COPYRIGHT__ # # 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import sys import SCons from SCons.Tool import SourceFileScanner, ProgramScanner # Create common python builders def createPythonObjectBuilder(env): """This is a utility function that creates the PythonObject Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: pyobj = env['BUILDERS']['PythonObject'] except KeyError: pyobj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$PYEXTOBJPREFIX', suffix = '$PYEXTOBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['PythonObject'] = pyobj return pyobj def createPythonExtensionBuilder(env): """This is a utility function that creates the PythonExtension Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: pyext = env['BUILDERS']['PythonExtension'] except KeyError: import SCons.Action import SCons.Defaults action = SCons.Action.Action("$PYEXTLINKCOM", "$PYEXTLINKCOMSTR") action_list = [ SCons.Defaults.SharedCheck, action] pyext = SCons.Builder.Builder(action = action_list, emitter = "$SHLIBEMITTER", prefix = '$PYEXTPREFIX', suffix = '$PYEXTSUFFIX', target_scanner = ProgramScanner, src_suffix = '$PYEXTOBJSUFFIX', src_builder = 'PythonObject') env['BUILDERS']['PythonExtension'] = pyext return pyext def pyext_coms(platform): """Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given platform.""" if platform == 'win32': pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\ "$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\ "$_PYEXTCPPINCFLAGS $SOURCES" pyext_cxxcom = "$PYEXTCXX /Fo$TARGET /c $PYEXTCSHARED "\ "$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\ "$_PYEXTCPPINCFLAGS $SOURCES" pyext_linkcom = '${TEMPFILE("$PYEXTLINK $PYEXTLINKFLAGS '\ '/OUT:$TARGET.windows $( $_LIBDIRFLAGS $) '\ '$_LIBFLAGS $_PYEXTRUNTIME $SOURCES.windows")}' else: pyext_cccom = "$PYEXTCC -o $TARGET -c $PYEXTCCSHARED "\ "$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\ "$_PYEXTCPPINCFLAGS $SOURCES" pyext_cxxcom = "$PYEXTCXX -o $TARGET -c $PYEXTCSHARED "\ "$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\ "$_PYEXTCPPINCFLAGS $SOURCES" pyext_linkcom = "$PYEXTLINK -o $TARGET $PYEXTLINKFLAGS "\ "$SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_PYEXTRUNTIME" if platform == 'darwin': pyext_linkcom += ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' return pyext_cccom, pyext_cxxcom, pyext_linkcom def set_basic_vars(env): # Set construction variables which are independant on whether we are using # distutils or not. env['PYEXTCPPPATH'] = SCons.Util.CLVar('$PYEXTINCPATH') env['_PYEXTCPPINCFLAGS'] = '$( ${_concat(INCPREFIX, PYEXTCPPPATH, '\ 'INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['PYEXTOBJSUFFIX'] = '$SHOBJSUFFIX' env['PYEXTOBJPREFIX'] = '$SHOBJPREFIX' env['PYEXTRUNTIME'] = SCons.Util.CLVar("") # XXX: this should be handled with different flags env['_PYEXTRUNTIME'] = '$( ${_concat(LIBLINKPREFIX, PYEXTRUNTIME, '\ 'LIBLINKSUFFIX, __env__)} $)' # XXX: This won't work in all cases (using mingw, for example). To make # this work, we need to know whether PYEXTCC accepts /c and /Fo or -c -o. # This is difficult with the current way tools work in scons. pycc, pycxx, pylink = pyext_coms(sys.platform) env['PYEXTLINKFLAGSEND'] = SCons.Util.CLVar('$LINKFLAGSEND') env['PYEXTCCCOM'] = pycc env['PYEXTCXXCOM'] = pycxx env['PYEXTLINKCOM'] = pylink def _set_configuration_nodistutils(env): # Set env variables to sensible values when not using distutils def_cfg = {'PYEXTCC' : '$SHCC', 'PYEXTCFLAGS' : '$SHCFLAGS', 'PYEXTCCFLAGS' : '$SHCCFLAGS', 'PYEXTCXX' : '$SHCXX', 'PYEXTCXXFLAGS' : '$SHCXXFLAGS', 'PYEXTLINK' : '$LDMODULE', 'PYEXTSUFFIX' : '$LDMODULESUFFIX', 'PYEXTPREFIX' : ''} if sys.platform == 'darwin': def_cfg['PYEXTSUFFIX'] = '.so' for k, v in def_cfg.items(): ifnotset(env, k, v) ifnotset(env, 'PYEXT_ALLOW_UNDEFINED', SCons.Util.CLVar('$ALLOW_UNDEFINED')) ifnotset(env, 'PYEXTLINKFLAGS', SCons.Util.CLVar('$LDMODULEFLAGS')) env.AppendUnique(PYEXTLINKFLAGS = env['PYEXT_ALLOW_UNDEFINED']) def ifnotset(env, name, value): if not env.has_key(name): env[name] = value def set_configuration(env, use_distutils): """Set construction variables which are platform dependants. If use_distutils == True, use distutils configuration. Otherwise, use 'sensible' default. Any variable already defined is untouched.""" # We define commands as strings so that we can either execute them using # eval (same python for scons and distutils) or by executing them through # the shell. dist_cfg = {'PYEXTCC': ("sysconfig.get_config_var('CC')", False), 'PYEXTCFLAGS': ("sysconfig.get_config_var('CFLAGS')", True), 'PYEXTCCSHARED': ("sysconfig.get_config_var('CCSHARED')", False), 'PYEXTLINKFLAGS': ("sysconfig.get_config_var('LDFLAGS')", True), 'PYEXTLINK': ("sysconfig.get_config_var('LDSHARED')", False), 'PYEXTINCPATH': ("sysconfig.get_python_inc()", False), 'PYEXTSUFFIX': ("sysconfig.get_config_var('SO')", False)} from distutils import sysconfig # We set the python path even when not using distutils, because we rarely # want to change this, even if not using distutils ifnotset(env, 'PYEXTINCPATH', sysconfig.get_python_inc()) if use_distutils: for k, (v, should_split) in dist_cfg.items(): val = eval(v) if should_split: val = val.split() ifnotset(env, k, val) else: _set_configuration_nodistutils(env) def generate(env): """Add Builders and construction variables for python extensions to an Environment.""" if not env.has_key('PYEXT_USE_DISTUTILS'): env['PYEXT_USE_DISTUTILS'] = False # This sets all constructions variables used for pyext builders. set_basic_vars(env) set_configuration(env, env['PYEXT_USE_DISTUTILS']) # Create the PythonObject builder pyobj = createPythonObjectBuilder(env) action = SCons.Action.Action("$PYEXTCCCOM", "$PYEXTCCCOMSTR") pyobj.add_emitter('.c', SCons.Defaults.SharedObjectEmitter) pyobj.add_action('.c', action) action = SCons.Action.Action("$PYEXTCXXCOM", "$PYEXTCXXCOMSTR") pyobj.add_emitter('$CXXFILESUFFIX', SCons.Defaults.SharedObjectEmitter) pyobj.add_action('$CXXFILESUFFIX', action) # Create the PythonExtension builder createPythonExtensionBuilder(env) def exists(env): try: # This is not quite right: if someone defines all variables by himself, # it would work without distutils from distutils import sysconfig return True except ImportError: return False
bsd-3-clause
Smona/vrtest
node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py
2779
1665
# Copyright (c) 2011 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. """gypsh output module gypsh is a GYP shell. It's not really a generator per se. All it does is fire up an interactive Python session with a few local variables set to the variables passed to the generator. Like gypd, it's intended as a debugging aid, to facilitate the exploration of .gyp structures after being processed by the input module. The expected usage is "gyp -f gypsh -D OS=desired_os". """ import code import sys # All of this stuff about generator variables was lovingly ripped from gypd.py. # That module has a much better description of what's going on and why. _generator_identity_variables = [ 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'INTERMEDIATE_DIR', 'PRODUCT_DIR', 'RULE_INPUT_ROOT', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'RULE_INPUT_NAME', 'RULE_INPUT_PATH', 'SHARED_INTERMEDIATE_DIR', ] generator_default_variables = { } for v in _generator_identity_variables: generator_default_variables[v] = '<(%s)' % v def GenerateOutput(target_list, target_dicts, data, params): locals = { 'target_list': target_list, 'target_dicts': target_dicts, 'data': data, } # Use a banner that looks like the stock Python one and like what # code.interact uses by default, but tack on something to indicate what # locals are available, and identify gypsh. banner='Python %s on %s\nlocals.keys() = %s\ngypsh' % \ (sys.version, sys.platform, repr(sorted(locals.keys()))) code.interact(banner, local=locals)
mit
norberte/Feature-Based-Opinion-Mining
FeatureBasedOpinionMining/FeatureExtraction/opinion_fetcher.py
1
7851
from __future__ import division from nltk.tokenize import RegexpTokenizer from nltk import pos_tag, stem from nltk.corpus import stopwords import FeatureExtraction.sentiword_net_implementation as sni from glob import glob from re import compile, sub from FeatureExtraction.helper_functions import * snowball = stem.RegexpStemmer('ies$|s$|er$') feature_list = [] def strip_new_line(word): return word.strip('\n') def check_for_but(sentence): if sentence.find(" but ") != -1: return sentence.split(" but ") elif sentence.find(" but,") != -1: return sentence.split(" but,") else: return [sentence] def check_for_and(sentance): if sentance.find(" and ") != -1: return sentance.split(" and ") elif sentance.find(" and,") != -1: return sentance.split(" and,") else: return [sentance] def check_in_feature_list(word): if word in feature_list: return word for i in feature_list: if (len(word)*100)/len(i) > 75 and len(word) <= len(i): if i.find(word) != -1: return i return False def get_all_features(tokens): features, feature = [], None multiple, prev_token_feature = False, False for i in tokens: word = check_in_feature_list(get_root_word(i[0].lower())) if word: if multiple: features.append(word) elif prev_token_feature or not feature: feature = word prev_token_feature = True elif i[0] == "and": prev_token_feature = False if feature: features.append(feature) else: prev_token_feature = False if feature == None: return [] elif not multiple or len(features) == 1: return [feature] else: return features def get_product_names(): product_file = open("product names.txt", "r") product = {} line = product_file.readline() while line: line = line.split(":") product[line[0]] = line[1].strip() line = product_file.readline() product_file.close() return product def get_root_word(word): # convert singular to plural! return snowball.stem(word) def main(SWN_FILENAME): # values to be initialised in constructor cv = sni.SentiWordNetCorpusReader(SWN_FILENAME) tokenizer = RegexpTokenizer(r"[\w\']+") get_tokens = tokenizer.tokenize stopwords_list = stopwords.words('english') feature_name = [] f = open("tokenized_noun_file.txt", "r") # final_file = open("output_test.txt", "w") err_file = open("error_file_copy.txt", "w") opinion_file = open('opinion file.csv', 'w') opinion_file.write('product id,review no,sentence no,feature,opinion,senti score +ve,senti score -ve\n') negation_list = ['don\'t', 'not', 'never'] # tasks to be done in the constructor itself! subs_list = [compile("\'ve"), compile("\'d"), compile("\'s")] replace_list = ["have", "would", "is"] for i in f.readlines(): feature = i.split(":")[0] feature_list.append(feature) f.close() # Start processing !!! # filename = raw_input("Enter filename containing review(also mention the extension): ") tot_files = len(glob("list of products/*.txt")) product = get_product_names() file_count = 0 percent = 0 featureLookUp = {} print("processing.. Go to Progress Report.txt for further details") for filename in glob("list of products/*.txt"): progress_file = open("Progress Report.txt", "w") review_category = {} file_count += 1 # if (file_count*50)//tot_files > percent: # print ":", percent = (file_count * 100) // tot_files progress_file.write("Files Scanned: " + str(file_count) + "/" + str(tot_files) + "\n") progress_file.write("Progress: " + str(percent) + "%\n") progress_file.close() f = open(filename, "r") line = f.readline() reviews = [] while line: reviews.append(line) line = f.readline() f.close() number_of_reviews = len(reviews) review_count = 0 while len(reviews) > 0: review = reviews.pop(0) for i in range(3): review = subs_list[1].sub(replace_list[i], review) sentances = review.split(".") # splitting the review on the basis of fullstop. feature_score = {} # processing each sentance for it's feature feature_adverb_score = {} review_count += 1 final_sentances = [] for i in sentances: if not i: continue sentance = check_for_but(i) for j in sentance: final_sentances.extend( check_for_and(j)) # split the sentances having but in them to 2 diff sentances for sentance_no in range(len(final_sentances)): # scan the final set of sentances to check for features opinion_list = [] t = final_sentances[sentance_no] reverse_polarity = False counter = False tokens = get_tokens(t) pos_tagged_tokens = pos_tag(tokens) tokens_without_stop_words = [] prev_feature = feature_name feature_name = get_all_features(pos_tagged_tokens) # extract features from review for i in feature_name: # opinion_list[i.strip('.,?/-').lower()] = [] if str(i.strip(".,?/-").lower()) not in review_category: review_category[str(i.strip(".,?/-").lower())] = {'pos_review': 0, 'neg_review': 0, 'neutral_review': 0} if (t.find("it") != -1 or t.find("It") != -1) and not feature_name: feature_name = prev_feature for i in pos_tagged_tokens: # Remove the stop words! if (str(i[0].strip(".,?/-").lower()) not in stopwords_list) or ( i[0].strip(".,?/-").lower() == 'not'): tokens_without_stop_words.append(i) # print tokens_without_stop_words overall_pos_score, overall_neg_score = [], [] # overall_pos_score_adverb, overall_neg_score_adverb = [], [] for i in tokens_without_stop_words: if i[1].find("JJ") != -1: # print i[0], pos_score, neg_score = 0, 0 synsets_of_adjective = cv.senti_synsets(i[0], 'a') if synsets_of_adjective: synsets_of_adjective = cv.senti_synsets(i[0]) for synset in synsets_of_adjective: pos_score = pos_score + synset.pos_score / len(synsets_of_adjective) neg_score = neg_score + synset.neg_score / len(synsets_of_adjective) if pos_score > 0 or neg_score > 0: if reverse_polarity: overall_pos_score.append(neg_score) overall_neg_score.append(pos_score) reverse_polarity = False else: overall_pos_score.append(pos_score) overall_neg_score.append(neg_score) opinion_list.append(i[0]) elif i[0] in negation_list: reverse_polarity = True if len(overall_neg_score) == 0: overall_neg_score.append(0) if len(overall_pos_score) == 0: overall_pos_score.append(0) for name in feature_name: for i in range(len(opinion_list)): if review_count in featureLookUp: temp = featureLookUp[review_count] featureLookUp[review_count] = temp + [name] else: featureLookUp[review_count] = [name] opinion_file.write(filename.split('\\')[1].split('.')[0] + "," + str(review_count) + "," + str( sentance_no) + "," + name + "," + opinion_list[i] + "," + str( overall_pos_score[i]) + "," + str(overall_neg_score[i])) opinion_file.write("\n") if name in feature_score: posi_score, negi_score = feature_score[name][0], feature_score[name][1] feature_score[name] = (posi_score + sum(overall_pos_score) / len(overall_pos_score), negi_score + sum(overall_neg_score) / len(overall_neg_score)) else: feature_score[name] = (sum(overall_pos_score) / len(overall_pos_score), sum(overall_neg_score) / len(overall_neg_score)) print("") print("Review Processing Complete. An output file with the name 'output.txt' has been created in the current directory.") opinion_file.close() err_file.close() return featureLookUp, feature_name #final_file.close()
lgpl-3.0
DrXyzzy/cocalc
src/scripts/storage_gluster.py
2
28851
#!/usr/bin/env python ############################################################################### # # CoCalc: Collaborative Calculation # # Copyright (C) 2016, Sagemath Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import argparse, cPickle, hashlib, json, logging, os, sys, time, random from uuid import UUID log = None # This is so we can import salvus/salvus/daemon.py sys.path.append('/home/salvus/salvus/salvus/') def check_uuid(uuid): if UUID(uuid).version != 4: raise RuntimeError("invalid uuid") def uid(uuid): # We take the sha-512 of the uuid just to make it harder to force a collision. Thus even if a # user could somehow generate an account id of their choosing, this wouldn't help them get the # same uid as another user. n = hash(hashlib.sha512(uuid).digest()) % ( 4294967294 - 1000 ) # 2^32-2=max uid, as keith determined by a program + experimentation. return n + 1001 def cmd(s, exit_on_error=True): log.debug(s) #s += ' &>/dev/null' t = time.time() if os.system(s): if exit_on_error: raise RuntimeError("Error running '%s'" % s) log.debug("time: %s seconds" % (time.time() - t)) def cmd2(s): log.debug(s) from subprocess import Popen, PIPE out = Popen( s, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=not isinstance(s, list)) e = out.wait() x = out.stdout.read() + out.stderr.read() log.debug(x) return x, e def path_to_project(storage, project_id): return os.path.join(storage, project_id[:2], project_id[2:4], project_id) def migrate_project_to_storage(src, storage, min_size_mb, max_size_mb, new_only): info_json = os.path.join(src, '.sagemathcloud', 'info.json') if not os.path.exists(info_json): log.debug("Skipping since %s does not exist" % info_json) return project_id = json.loads(open(info_json).read())['project_id'] projectid = project_id.replace('-', '') target = path_to_project(storage, project_id) try: if os.path.exists(target): if new_only: log.debug( "skipping %s (%s) since it already exists (and new_only=True)" % (src, project_id)) return mount_project(storage=storage, project_id=project_id, force=False) else: # create os.makedirs(target) os.chdir(target) current_size_mb = int( os.popen("du -s '%s'" % src).read().split()[0]) // 1000 + 1 size = min(max_size_mb, max(min_size_mb, current_size_mb)) # Using many small img files might seem like a good idea. It isn't, since mount takes massively longer, etc. #img_size_mb = 128 #images = ['%s/%s.img'%(target, i) for i in range(size//img_size_mb + 1)] #for img in images: # cmd("truncate -s %sM %s"%(img_size_mb,img)) #images = ' '.join(images) images = '%s/%s.img' % (target, 0) cmd("truncate -s %sM %s" % (size, images)) cmd("zpool create -m /home/%s project-%s %s" % (projectid, project_id, images)) cmd("zfs set compression=gzip project-%s" % project_id) cmd("zfs set dedup=on project-%s" % project_id) cmd("zfs set snapdir=visible project-%s" % project_id) # rsync data over double_verbose = False cmd("time rsync -axH%s --delete --exclude .forever --exclude .bup %s/ /home/%s/" % ('v' if double_verbose else '', src, projectid), exit_on_error=False) id = uid(project_id) cmd("chown %s:%s -R /home/%s/" % (id, id, projectid)) cmd("df -h /home/%s; zfs get compressratio project-%s; zpool get dedupratio project-%s" % (projectid, project_id, project_id)) finally: unmount_project(project_id=project_id) def mount_project(storage, project_id, force): check_uuid(project_id) id = uid(project_id) target = path_to_project(storage, project_id) out, e = cmd2("zpool import %s project-%s -d %s" % ('-f' if force else '', project_id, target)) if e: if 'a pool with that name is already created' in out: # no problem pass else: print "could not get pool" sys.exit(1) projectid = project_id.replace('-', '') # the -o makes it so in the incredibly unlikely event of a collision, no big deal. cmd("groupadd -g %s -o %s" % (id, projectid), exit_on_error=False) cmd("useradd -u %s -g %s -o -d /home/%s/ %s" % (id, id, projectid, projectid), exit_on_error=False) # error if user already exists is fine. def unmount_project(project_id): check_uuid(project_id) projectid = project_id.replace('-', '') cmd("pkill -9 -u %s" % projectid, exit_on_error=False) cmd("deluser --force %s" % projectid, exit_on_error=False) time.sleep(.5) out, e = cmd2("zpool export project-%s" % project_id) if e: if 'no such pool' not in out: # not just a problem due to pool not being mounted. print "Error unmounting pool -- %s" % out sys.exit(1) def tinc_address(): return os.popen('ifconfig tun0|grep "inet addr"').read().split()[1].split( ':')[1].strip() def info_json(path): if not os.path.exists('locations.dat'): sys.stderr.write( 'Please run this from a node with db access to create locations.dat\n\t\techo "select location,project_id from projects limit 30000;" | cqlsh_connect 10.1.3.2 |grep "{" > locations.dat' ) sys.exit(1) db = {} host = tinc_address() log.info("parsing database...") for x in open('locations.dat').readlines(): if x.strip(): location, project_id = x.split('|') location = json.loads(location.strip()) project_id = project_id.strip() if location['host'] == host: if location['username'] in db: log.warning("WARNING: collision -- %s, %s" % (location, project_id)) db[location['username']] = { 'location': location, 'project_id': project_id, 'base_url': '' } v = [os.path.abspath(x) for x in path] for i, path in enumerate(v): log.info("** %s of %s" % (i + 1, len(v))) SMC = os.path.join(path, '.sagemathcloud') if not os.path.exists(SMC): log.warning( "Skipping '%s' since no .sagemathcloud directory" % path) continue f = os.path.join(path, '.sagemathcloud', 'info.json') username = os.path.split(path)[-1] if not os.path.exists(f): if username not in db: log.warning("Skipping '%s' since not in database!" % username) else: s = json.dumps(db[username], separators=(',', ':')) log.info("writing '%s': '%s'" % (f, s)) open(f, 'w').write(s) os.system('chmod a+rw %s' % f) def modtime(f): try: return int(os.stat(f).st_mtime) except: return 0 # 1970... def copy_file_efficiently(src, dest): """ Copy a possibly sparse file from a brick to a mounted glusterfs volume, if the dest is older. This for now -- later we might use a different method when the file is above a certain size threshold (?). However, I can't think of any possible better method, really; anything involving computing a diff between the two files would require *reading* them, so already takes way too long (in sharp contrast to the ever-clever bup, which uses a blum filter!). This will raise a RuntimeError if something goes wrong. """ import uuid s0, s1 = os.path.split(dest) if s1.startswith('.glusterfs'): # never copy around/sync any of the temp files we create below. return # The clock of the destination is used when doing this copy, so it's # *critical* that the clocks be in sync. Run ntp!!!!! dest_modtime = modtime(dest) if dest_modtime >= modtime(src): return if not os.path.exists(s0): os.makedirs(s0) lock = os.path.join(s0, ".glusterfs-lock-%s" % s1) dest0 = os.path.join(s0, ".glusterfs-tmp-%s-%s" % (str(uuid.uuid4()), s1)) now = time.time() recent = now - 5 * 60 # recent time = 5 minutes ago if os.path.exists(lock): log.debug( "another daemon is either copying the same file right now (or died)." ) # If mod time of the lock is recent, just give up. t = modtime(lock) if t >= recent: return # recent lock # check that dest0 exists and has mod time < 5 minutes; otherwise, take control. if os.path.exists(dest0) and modtime(dest0) >= recent: return if os.stat(src).st_mode == 33280: log.info( "skipping copy since source '%s' suddenly became special link file", src) return log.info("sync: %s --> %s" % (src, dest)) t = time.time() try: log.info(cmd2('ls -lhs "%s"' % src)[0]) cmd("touch '%s'; cp -av '%s' '%s'" % (lock, src, dest0), exit_on_error=True) # check that modtime of dest is *still* older, i.e., that somehow somebody didn't # just step in and change it. if modtime(dest) == dest_modtime: # modtime was unchanged. cmd("mv -v '%s' '%s'" % (dest0, dest), exit_on_error=True) finally: # remove the tmp file instead of leaving it there all corrupted. if os.path.exists(dest0): try: os.unlink(dest0) except: pass if os.path.exists(lock): try: os.unlink(lock) except: pass total_time = time.time() - t log.info("time: %s" % total_time) return total_time def sync(src, dest): """ copy all older files from src/ to dest/. -- src/ = underyling *brick* path for some glusterfs host -- dest/ = remote mounted glusterfs filesystem """ src = os.path.abspath(src) dest = os.path.abspath(dest) cache_file = "/var/lib/glusterd/glustersync/cache.pickle" if not os.path.exists("/var/lib/glusterd/glustersync"): os.makedirs("/var/lib/glusterd/glustersync") if os.path.exists(cache_file): cache_all = cPickle.loads(open(cache_file).read()) else: cache_all = {} if dest not in cache_all: cache_all[dest] = {} cache = cache_all[dest] log.info("sync: '%s' --> '%s'" % (src, dest)) import stat def walktree(top): #log.info("scanning '%s'", top) v = os.listdir(top) random.shuffle(v) for i, f in enumerate(v): if f == '.glusterfs': # skip the glusterfs meta-data continue if len(v) > 10: log.debug("%s(%s/%s): %s", top, i + 1, len(v), f) pathname = os.path.join(top, f) src_name = os.path.join(src, pathname) dest_name = os.path.join(dest, pathname) st = os.stat(src_name) if st.st_mode == 33280: # glusterfs meta-info file to indicate a moved file... continue if stat.S_ISDIR(st.st_mode): # It's a directory: create in target if necessary, then recurse... ## !! we skip creation; this is potentially expensive and isn't needed for our application. ##if not os.path.exists(dest_name): ## try: ## os.makedirs(dest_name) ## except OSError: ## if not os.path.exists(dest_name): ## raise RuntimeError("unable to make directory '%s'"%dest_name) try: walktree(pathname) except OSError, mesg: log.warning("error walking '%s': %s", pathname, mesg) elif stat.S_ISREG(st.st_mode): mtime = int(st.st_mtime) if cache.get(src_name, {'mtime': 0})['mtime'] >= mtime: continue try: copy_file_efficiently( src_name, dest_name ) # checks dest modtime before actually doing copy. cache[src_name] = { 'mtime': mtime, 'size_mb': st.st_blocks // 2000 } except RuntimeError, mesg: log.warning("error copying %s to %s; skipping.", src_name, dest_name) else: # Unknown file type, print a message log.warning("unknown file type: %s", pathname) os.chdir(src) walktree('.') s = cPickle.dumps(cache_all) open(cache_file, 'w').write(s) def sync_watch(sources, dests, min_sync_time): ### WARNING -- this code does not work very well, and is sort of pointless. AVOID! """ Watch filesystem trees and on modification or creation, cp file, possibly creating directories. The frequency of copying is limited in various ways. This uses inotify so that it is event driven. You must increase the number of watched files that are allowed! "sudo sysctl fs.inotify.max_user_watches=10000000" and in /etc/sysctl.conf: fs.inotify.max_user_watches=10000000 - sources = list of underyling *brick* path for some glusterfs host - dests = list of paths of remote mounted glusterfs filesystems - min_sync_time = never sync a file more frequently than this many seconds; no matter what, we also wait at least twice the time it takes to sync out the file before syncing it again. """ sources = [os.path.abspath(src) for src in sources] dests = [os.path.abspath(dest) for dest in dests] next_sync = {} # soonest time when may again sync a given file modified_files = set([]) received_files = set([]) def add(pathname): try: if os.stat(pathname).st_mode == 33280: # ignore gluster special files log.debug("ignoring gluster special file: '%s'", pathname) return except: pass log.debug("inotify: %s" % pathname) s = os.path.split(pathname) if s[1].startswith('.glusterfs-lock-'): received_files.add( os.path.join(s[0], s[1][len('.glusterfs-lock-'):])) elif s[1].startswith('.glusterfs'): return elif os.path.isfile(pathname): modified_files.add(pathname) def handle_modified_files(): if not modified_files: return log.debug("handling modified_files=%s", modified_files) log.debug("received_files=%s", received_files) now = time.time() do_later = [] for path in modified_files: if path in sources: # ignore changes to the sources directories continue if path in received_files: # recently copied to us. continue if path not in next_sync or now >= next_sync[path]: src = None for s in sources: if path.startswith(s): src = s break if not src: log.warning( "not copying '%s' -- must be under a source: %s" % (path, sources)) continue t0 = time.time() for dest in dests: dest_path = os.path.join(dest, path[len(src) + 1:]) log.info("copy('%s', '%s')" % (path, dest_path)) try: copy_file_efficiently(path, dest_path) except Exception, msg: log.warning("problem syncing %s to %s! -- %s" % (path, dest_path, msg)) # no matter what, we wait at least twice the time (from now) that it takes to sync out the file before syncing it again. next_sync[path] = time.time() + max(2 * (time.time() - t0), min_sync_time) else: pass #log.debug("waiting until later to sync (too frequent): '%s' "%path) do_later.append(path) modified_files.clear() received_files.clear() modified_files.update(do_later) import pyinotify wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO | pyinotify.IN_MODIFY | pyinotify.IN_CLOSE_WRITE class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "Creating:", event.pathname if os.path.isdir(event.pathname): # created a directory -- add it to the watch list watchers.append(wm.add_watch(event.pathname, mask)) add(event.pathname) def process_IN_MOVED_TO(self, event): print "File moved to:", event.pathname add(event.pathname) def process_IN_MODIFY(self, event): print "Modified:", event.pathname add(event.pathname) def process_IN_CLOSE_WRITE(self, event): print "Close write:", event.pathname add(event.pathname) handler = EventHandler() # we get inotify events for *at most* timeout seconds, then handle them all notifier = pyinotify.Notifier(wm, handler, timeout=1) t = time.time() watchers = [] for src in sources: log.info("adding watches to '%s' (this could take several minutes)..." % src) dot_gluster = os.path.join(src, '.glusterfs') watchers.append( wm.add_watch( src, mask, rec=True, exclude_filter=pyinotify.ExcludeFilter(['^' + dot_gluster]))) log.info("watch added (%s seconds): listening for file events..." % (time.time() - t)) def check_for_events(): #print "check_for_events" notifier.process_events() while notifier.check_events( ): #loop in case more events appear while we are processing notifier.read_events() notifier.process_events() while True: check_for_events() handle_modified_files() time.sleep(1) def volume_info(): # parse 'gluster volume info' as a python object. s, e = cmd2('unset PYTHONPATH; unset PYTHONHOME; gluster volume info') if e: raise RuntimeError(e) v = {} for x in s.split("\nVolume Name: "): z = x.strip().splitlines() if z: name = z[0] m = {'bricks': []} for k in z[1:]: i = k.find(':') if i == -1: continue key = k[:i].strip() val = k[i + 1:].strip() if val: if key.startswith('Brick'): m['bricks'].append(val) else: m[key] = val v[name] = m return v def ip_address(dest): # get the ip address that is used to communicate with the given destination import misc return misc.local_ip_address(dest) def mount_target_volumes(volume_name): info = volume_info() dests = [] ip = None mount = cmd2('mount')[0] for name, data in volume_info().iteritems(): if name.startswith('dc'): v = name.split('-') if len(v) >= 2 and v[1] == volume_name: use = True for brick in data['bricks']: brick_ip, path = brick.split(':') if ip_address(brick_ip) == brick_ip: # this volume is partly hosted on this computer, hence not a target. use = False break if use: # ensure volume is mounted and add to list if 'mnt/%s' % name not in mount: cmd("mkdir -p '/mnt/%s'; mount -t glusterfs localhost:'/%s' '/mnt/%s'" % (name, name, name)) dests.append('/mnt/%s' % name) return dests def find_bricks(volume_name): bricks = [] ip = None for name, data in volume_info().iteritems(): if name.startswith('dc'): v = name.split('-') if len(v) >= 2 and v[1] == volume_name: for brick in data['bricks']: brick_ip, path = brick.split(':') if ip_address(brick_ip) == brick_ip: bricks.append(path) return bricks def setup_log(loglevel='DEBUG', logfile=''): logging.basicConfig() global log log = logging.getLogger('storage') if loglevel: level = getattr(logging, loglevel.upper()) log.setLevel(level) if logfile: log.addHandler(logging.FileHandler(logfile)) log.info("logger started") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Project storage") parser.add_argument( "--loglevel", dest='loglevel', type=str, default='INFO', help="log level: useful options include INFO, WARNING and DEBUG") parser.add_argument( "--logfile", dest="logfile", type=str, default='', help="store log in this file (default: '' = don't log to a file)") subparsers = parser.add_subparsers(help='sub-command help') def migrate(args): if not args.storage: args.storage = os.environ['SALVUS_STORAGE'] v = [os.path.abspath(x) for x in args.src] for i, src in enumerate(v): log.info("\n** %s of %s" % (i + 1, len(v))) migrate_project_to_storage( src=src, storage=args.storage, min_size_mb=args.min_size_mb, max_size_mb=10000, new_only=args.new_only) parser_migrate = subparsers.add_parser( 'migrate', help='migrate to or update project in storage pool') parser_migrate.add_argument( "--storage", help= "the directory where project image directories are stored (default: $SALVUS_STORAGE enviro var)", type=str, default='') parser_migrate.add_argument( "--min_size_mb", help="min size of zfs image in megabytes (default: 512)", type=int, default=512) parser_migrate.add_argument( "--new_only", help="if image already created, do nothing (default: False)", default=False, action="store_const", const=True) parser_migrate.add_argument( "src", help="the current project home directory", type=str, nargs="+") parser_migrate.set_defaults(func=migrate) def mount(args): if not args.storage: args.storage = os.environ['SALVUS_STORAGE'] mount_project( storage=args.storage, project_id=args.project_id, force=args.f) parser_mount = subparsers.add_parser( 'mount', help='mount a project that is available in the storage pool') parser_mount.add_argument( "--storage", help= "the directory where project image directories are stored (default: $SALVUS_STORAGE enviro var)", type=str, default='') parser_mount.add_argument("project_id", help="the project id", type=str) parser_mount.add_argument( "-f", help="force (default: False)", default=False, action="store_const", const=True) parser_mount.set_defaults(func=mount) def unmount(args): unmount_project(project_id=args.project_id) parser_unmount = subparsers.add_parser( 'umount', help='unmount a project that is available in the storage pool') parser_unmount.add_argument("project_id", help="the project id", type=str) parser_unmount.set_defaults(func=unmount) def _info_json(args): info_json(path=args.path) parser_migrate = subparsers.add_parser( 'info_json', help='query database, then write info.json file if there is none') parser_migrate.add_argument( "path", help="path to a project home directory (old non-pooled)", type=str, nargs="+") parser_migrate.set_defaults(func=_info_json) def _sync(args): if not args.dest: args.dest = ','.join(mount_target_volumes(args.volume)) if not args.src: args.src = ','.join(find_bricks(args.volume)) def main(): while True: try: if args.watch: sync_watch( sources=args.src.split(','), dests=args.dest.split(','), min_sync_time=args.min_sync_time) else: for src in args.src.split(','): for dest in args.dest.split(','): sync(src=src, dest=dest) except KeyboardInterrupt: return except Exception, mesg: print mesg if not args.daemon: return time.sleep(5) if args.daemon: if not args.pidfile: raise RuntimeError( "in --daemon mode you *must* specify --pidfile") import daemon daemon.daemonize(args.pidfile) main() parser_sync = subparsers.add_parser( 'sync', help= 'Cross data center project sync: simply uses the local "cp" command and local mounts of the glusterfs, but provides massive speedups due to sparseness of image files' ) parser_sync.add_argument( "--watch", help= "after running once, use inotify to watch for changes to the src filesystem and cp when they occur", default=False, action="store_const", const=True) parser_sync.add_argument( "--min_sync_time", help= "never copy a file more frequently than this (default: 30 seconds)", type=int, default=30) parser_sync.add_argument( "--daemon", help="daemon mode; will repeatedly sync", dest="daemon", default=False, action="store_const", const=True) parser_sync.add_argument( "--pidfile", dest="pidfile", type=str, default='', help="store pid in this file when daemonized") parser_sync.add_argument( "--dest", help= "comma separated list of destinations; if not given, all remote gluster volumes with name dc[n]-volume are mounted and targeted", type=str, default='') parser_sync.add_argument( "--src", help= "comma separated paths to bricks; if not given, local bricks for dc[n]-volume are used", type=str, default='') parser_sync.add_argument( "--volume", help= "if there are volumes dc0-projects, dc1-projects, dc2-projects, then pass option --volume=projects (default: 'projects')", default='projects') parser_sync.set_defaults(func=_sync) args = parser.parse_args() setup_log(loglevel=args.loglevel, logfile=args.logfile) args.func(args) else: setup_log()
agpl-3.0
us-ignite/us_ignite
us_ignite/smart_gigabit_communities/views.py
1
1477
from django.shortcuts import render from django.template.response import TemplateResponse from models import * import random # Create your views here. def reverse_pitch(request): # "Static" text here. OPTIONAL intro = "US Ignite Will Convene Reverse Pitch Events in Nine Communities Throughout the United States " desc = "From Arizona to Texas to Vermont, US Ignite will co-host and sponsor multiple reverse pitch events for technologists and entrepreneurs throughout February and March. This reverse pitch competition is for makers, developers and entrepreneurs developing ultra high-bandwidth hardware, software and applications that want to impact their local community. Entrepreneurs will hear pitches from civic organizations and then compete for part of a prize pool of cash and in-kind services. US Ignite will co-sponsor these events in nine of the organization's Smart Gigabit Communities, which are a network of communities nationwide that have each committed to leverage next-generation smart city and Internet technologies to keep pace with the world's rapidly changing, technology-driven economy." random_int = random.uniform(0.1, 2.0) pitch_list = Pitch.objects.filter(active=True).order_by('order').all()[:6] context = { 'intro': intro, 'desc': desc, 'pitch_list': pitch_list, 'random_int': random_int } return TemplateResponse(request, 'smart_gigabit_communities/reverse_pitch.html', context)
bsd-3-clause
cristiana214/cristianachavez214-cristianachavez
python/src/Lib/multiprocessing/pool.py
52
17699
# # Module providing the `Pool` class for managing a process pool # # multiprocessing/pool.py # # Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt # __all__ = ['Pool'] # # Imports # import threading import Queue import itertools import collections import time from multiprocessing import Process, cpu_count, TimeoutError from multiprocessing.util import Finalize, debug # # Constants representing the state of a pool # RUN = 0 CLOSE = 1 TERMINATE = 2 # # Miscellaneous # job_counter = itertools.count() def mapstar(args): return map(*args) # # Code run by worker processes # def worker(inqueue, outqueue, initializer=None, initargs=()): put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initializer is not None: initializer(*initargs) while 1: try: task = get() except (EOFError, IOError): debug('worker got EOFError or IOError -- exiting') break if task is None: debug('worker got sentinel -- exiting') break job, i, func, args, kwds = task try: result = (True, func(*args, **kwds)) except Exception, e: result = (False, e) put((job, i, result)) # # Class representing a process pool # class Pool(object): ''' Class which supports an async version of the `apply()` builtin ''' Process = Process def __init__(self, processes=None, initializer=None, initargs=()): self._setup_queues() self._taskqueue = Queue.Queue() self._cache = {} self._state = RUN if processes is None: try: processes = cpu_count() except NotImplementedError: processes = 1 self._pool = [] for i in range(processes): w = self.Process( target=worker, args=(self._inqueue, self._outqueue, initializer, initargs) ) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() self._task_handler = threading.Thread( target=Pool._handle_tasks, args=(self._taskqueue, self._quick_put, self._outqueue, self._pool) ) self._task_handler.daemon = True self._task_handler._state = RUN self._task_handler.start() self._result_handler = threading.Thread( target=Pool._handle_results, args=(self._outqueue, self._quick_get, self._cache) ) self._result_handler.daemon = True self._result_handler._state = RUN self._result_handler.start() self._terminate = Finalize( self, self._terminate_pool, args=(self._taskqueue, self._inqueue, self._outqueue, self._pool, self._task_handler, self._result_handler, self._cache), exitpriority=15 ) def _setup_queues(self): from .queues import SimpleQueue self._inqueue = SimpleQueue() self._outqueue = SimpleQueue() self._quick_put = self._inqueue._writer.send self._quick_get = self._outqueue._reader.recv def apply(self, func, args=(), kwds={}): ''' Equivalent of `apply()` builtin ''' assert self._state == RUN return self.apply_async(func, args, kwds).get() def map(self, func, iterable, chunksize=None): ''' Equivalent of `map()` builtin ''' assert self._state == RUN return self.map_async(func, iterable, chunksize).get() def imap(self, func, iterable, chunksize=1): ''' Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()` ''' assert self._state == RUN if chunksize == 1: result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for i, x in enumerate(iterable)), result._set_length)) return result else: assert chunksize > 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, mapstar, (x,), {}) for i, x in enumerate(task_batches)), result._set_length)) return (item for chunk in result for item in chunk) def imap_unordered(self, func, iterable, chunksize=1): ''' Like `imap()` method but ordering of results is arbitrary ''' assert self._state == RUN if chunksize == 1: result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for i, x in enumerate(iterable)), result._set_length)) return result else: assert chunksize > 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, mapstar, (x,), {}) for i, x in enumerate(task_batches)), result._set_length)) return (item for chunk in result for item in chunk) def apply_async(self, func, args=(), kwds={}, callback=None): ''' Asynchronous equivalent of `apply()` builtin ''' assert self._state == RUN result = ApplyResult(self._cache, callback) self._taskqueue.put(([(result._job, None, func, args, kwds)], None)) return result def map_async(self, func, iterable, chunksize=None, callback=None): ''' Asynchronous equivalent of `map()` builtin ''' assert self._state == RUN if not hasattr(iterable, '__len__'): iterable = list(iterable) if chunksize is None: chunksize, extra = divmod(len(iterable), len(self._pool) * 4) if extra: chunksize += 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self._cache, chunksize, len(iterable), callback) self._taskqueue.put((((result._job, i, mapstar, (x,), {}) for i, x in enumerate(task_batches)), None)) return result @staticmethod def _handle_tasks(taskqueue, put, outqueue, pool): thread = threading.current_thread() for taskseq, set_length in iter(taskqueue.get, None): i = -1 for i, task in enumerate(taskseq): if thread._state: debug('task handler found thread._state != RUN') break try: put(task) except IOError: debug('could not put task on queue') break else: if set_length: debug('doing set_length()') set_length(i+1) continue break else: debug('task handler got sentinel') try: # tell result handler to finish when cache is empty debug('task handler sending sentinel to result handler') outqueue.put(None) # tell workers there is no more work debug('task handler sending sentinel to workers') for p in pool: put(None) except IOError: debug('task handler got IOError when sending sentinels') debug('task handler exiting') @staticmethod def _handle_results(outqueue, get, cache): thread = threading.current_thread() while 1: try: task = get() except (IOError, EOFError): debug('result handler got EOFError/IOError -- exiting') return if thread._state: assert thread._state == TERMINATE debug('result handler found thread._state=TERMINATE') break if task is None: debug('result handler got sentinel') break job, i, obj = task try: cache[job]._set(i, obj) except KeyError: pass while cache and thread._state != TERMINATE: try: task = get() except (IOError, EOFError): debug('result handler got EOFError/IOError -- exiting') return if task is None: debug('result handler ignoring extra sentinel') continue job, i, obj = task try: cache[job]._set(i, obj) except KeyError: pass if hasattr(outqueue, '_reader'): debug('ensuring that outqueue is not full') # If we don't make room available in outqueue then # attempts to add the sentinel (None) to outqueue may # block. There is guaranteed to be no more than 2 sentinels. try: for i in range(10): if not outqueue._reader.poll(): break get() except (IOError, EOFError): pass debug('result handler exiting: len(cache)=%s, thread._state=%s', len(cache), thread._state) @staticmethod def _get_tasks(func, it, size): it = iter(it) while 1: x = tuple(itertools.islice(it, size)) if not x: return yield (func, x) def __reduce__(self): raise NotImplementedError( 'pool objects cannot be passed between processes or pickled' ) def close(self): debug('closing pool') if self._state == RUN: self._state = CLOSE self._taskqueue.put(None) def terminate(self): debug('terminating pool') self._state = TERMINATE self._terminate() def join(self): debug('joining pool') assert self._state in (CLOSE, TERMINATE) self._task_handler.join() self._result_handler.join() for p in self._pool: p.join() @staticmethod def _help_stuff_finish(inqueue, task_handler, size): # task_handler may be blocked trying to put items on inqueue debug('removing tasks from inqueue until task handler finished') inqueue._rlock.acquire() while task_handler.is_alive() and inqueue._reader.poll(): inqueue._reader.recv() time.sleep(0) @classmethod def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, task_handler, result_handler, cache): # this is guaranteed to only be called once debug('finalizing pool') task_handler._state = TERMINATE taskqueue.put(None) # sentinel debug('helping task handler/workers to finish') cls._help_stuff_finish(inqueue, task_handler, len(pool)) assert result_handler.is_alive() or len(cache) == 0 result_handler._state = TERMINATE outqueue.put(None) # sentinel if pool and hasattr(pool[0], 'terminate'): debug('terminating workers') for p in pool: p.terminate() debug('joining task handler') task_handler.join(1e100) debug('joining result handler') result_handler.join(1e100) if pool and hasattr(pool[0], 'terminate'): debug('joining pool workers') for p in pool: p.join() # # Class whose instances are returned by `Pool.apply_async()` # class ApplyResult(object): def __init__(self, cache, callback): self._cond = threading.Condition(threading.Lock()) self._job = job_counter.next() self._cache = cache self._ready = False self._callback = callback cache[self._job] = self def ready(self): return self._ready def successful(self): assert self._ready return self._success def wait(self, timeout=None): self._cond.acquire() try: if not self._ready: self._cond.wait(timeout) finally: self._cond.release() def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value def _set(self, i, obj): self._success, self._value = obj if self._callback and self._success: self._callback(self._value) self._cond.acquire() try: self._ready = True self._cond.notify() finally: self._cond.release() del self._cache[self._job] # # Class whose instances are returned by `Pool.map_async()` # class MapResult(ApplyResult): def __init__(self, cache, chunksize, length, callback): ApplyResult.__init__(self, cache, callback) self._success = True self._value = [None] * length self._chunksize = chunksize if chunksize <= 0: self._number_left = 0 self._ready = True else: self._number_left = length//chunksize + bool(length % chunksize) def _set(self, i, success_result): success, result = success_result if success: self._value[i*self._chunksize:(i+1)*self._chunksize] = result self._number_left -= 1 if self._number_left == 0: if self._callback: self._callback(self._value) del self._cache[self._job] self._cond.acquire() try: self._ready = True self._cond.notify() finally: self._cond.release() else: self._success = False self._value = result del self._cache[self._job] self._cond.acquire() try: self._ready = True self._cond.notify() finally: self._cond.release() # # Class whose instances are returned by `Pool.imap()` # class IMapIterator(object): def __init__(self, cache): self._cond = threading.Condition(threading.Lock()) self._job = job_counter.next() self._cache = cache self._items = collections.deque() self._index = 0 self._length = None self._unsorted = {} cache[self._job] = self def __iter__(self): return self def next(self, timeout=None): self._cond.acquire() try: try: item = self._items.popleft() except IndexError: if self._index == self._length: raise StopIteration self._cond.wait(timeout) try: item = self._items.popleft() except IndexError: if self._index == self._length: raise StopIteration raise TimeoutError finally: self._cond.release() success, value = item if success: return value raise value __next__ = next # XXX def _set(self, i, obj): self._cond.acquire() try: if self._index == i: self._items.append(obj) self._index += 1 while self._index in self._unsorted: obj = self._unsorted.pop(self._index) self._items.append(obj) self._index += 1 self._cond.notify() else: self._unsorted[i] = obj if self._index == self._length: del self._cache[self._job] finally: self._cond.release() def _set_length(self, length): self._cond.acquire() try: self._length = length if self._index == self._length: self._cond.notify() del self._cache[self._job] finally: self._cond.release() # # Class whose instances are returned by `Pool.imap_unordered()` # class IMapUnorderedIterator(IMapIterator): def _set(self, i, obj): self._cond.acquire() try: self._items.append(obj) self._index += 1 self._cond.notify() if self._index == self._length: del self._cache[self._job] finally: self._cond.release() # # # class ThreadPool(Pool): from .dummy import Process def __init__(self, processes=None, initializer=None, initargs=()): Pool.__init__(self, processes, initializer, initargs) def _setup_queues(self): self._inqueue = Queue.Queue() self._outqueue = Queue.Queue() self._quick_put = self._inqueue.put self._quick_get = self._outqueue.get @staticmethod def _help_stuff_finish(inqueue, task_handler, size): # put sentinels at head of inqueue to make workers finish inqueue.not_empty.acquire() try: inqueue.queue.clear() inqueue.queue.extend([None] * size) inqueue.not_empty.notify_all() finally: inqueue.not_empty.release()
apache-2.0
foufou55/Sick-Beard
sickbeard/notifiers/xbmc.py
35
22455
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import urllib import urllib2 import socket import base64 import time import sickbeard from sickbeard import logger from sickbeard import common from sickbeard.exceptions import ex from sickbeard.encodingKludge import fixStupidEncodings try: import xml.etree.cElementTree as etree except ImportError: import xml.etree.ElementTree as etree try: import json except ImportError: from lib import simplejson as json class XBMCNotifier: sb_logo_url = 'http://www.sickbeard.com/xbmc-notify.png' def _get_xbmc_version(self, host, username, password): """Returns XBMC JSON-RPC API version (odd # = dev, even # = stable) Sends a request to the XBMC host using the JSON-RPC to determine if the legacy API or if the JSON-RPC API functions should be used. Fallback to testing legacy HTTPAPI before assuming it is just a badly configured host. Args: host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password Returns: Returns API number or False List of possible known values: API | XBMC Version -----+--------------- 2 | v10 (Dharma) 3 | (pre Eden) 4 | v11 (Eden) 5 | (pre Frodo) 6 | v12 (Frodo) """ # since we need to maintain python 2.5 compatability we can not pass a timeout delay to urllib2 directly (python 2.6+) # override socket timeout to reduce delay for this call alone socket.setdefaulttimeout(10) checkCommand = '{"jsonrpc":"2.0","method":"JSONRPC.Version","id":1}' result = self._send_to_xbmc_json(checkCommand, host, username, password) # revert back to default socket timeout socket.setdefaulttimeout(sickbeard.SOCKET_TIMEOUT) if result: return result["result"]["version"] else: # fallback to legacy HTTPAPI method testCommand = {'command': 'Help'} request = self._send_to_xbmc(testCommand, host, username, password) if request: # return a fake version number, so it uses the legacy method return 1 else: return False def _notify_xbmc(self, message, title="Sick Beard", host=None, username=None, password=None, force=False): """Internal wrapper for the notify_snatch and notify_download functions Detects JSON-RPC version then branches the logic for either the JSON-RPC or legacy HTTP API methods. Args: message: Message body of the notice to send title: Title of the notice to send host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password force: Used for the Test method to override config saftey checks Returns: Returns a list results in the format of host:ip:result The result will either be 'OK' or False, this is used to be parsed by the calling function. """ # fill in omitted parameters if not host: host = sickbeard.XBMC_HOST if not username: username = sickbeard.XBMC_USERNAME if not password: password = sickbeard.XBMC_PASSWORD # suppress notifications if the notifier is disabled but the notify options are checked if not sickbeard.USE_XBMC and not force: logger.log("Notification for XBMC not enabled, skipping this notification", logger.DEBUG) return False result = '' for curHost in [x.strip() for x in host.split(",")]: logger.log(u"Sending XBMC notification to '" + curHost + "' - " + message, logger.MESSAGE) xbmcapi = self._get_xbmc_version(curHost, username, password) if xbmcapi: if (xbmcapi <= 4): logger.log(u"Detected XBMC version <= 11, using XBMC HTTP API", logger.DEBUG) command = {'command': 'ExecBuiltIn', 'parameter': 'Notification(' + title.encode("utf-8") + ',' + message.encode("utf-8") + ')'} notifyResult = self._send_to_xbmc(command, curHost, username, password) if notifyResult: result += curHost + ':' + str(notifyResult) else: logger.log(u"Detected XBMC version >= 12, using XBMC JSON API", logger.DEBUG) command = '{"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"%s","message":"%s", "image": "%s"},"id":1}' % (title.encode("utf-8"), message.encode("utf-8"), self.sb_logo_url) notifyResult = self._send_to_xbmc_json(command, curHost, username, password) if notifyResult: result += curHost + ':' + notifyResult["result"].decode(sickbeard.SYS_ENCODING) else: logger.log(u"Failed to detect XBMC version for '" + curHost + "', check configuration and try again.", logger.DEBUG) result += curHost + ':False' return result ############################################################################## # Legacy HTTP API (pre XBMC 12) methods ############################################################################## def _send_to_xbmc(self, command, host=None, username=None, password=None): """Handles communication to XBMC servers via HTTP API Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the XBMC API via HTTP host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password Returns: Returns response.result for successful commands or False if there was an error """ # fill in omitted parameters if not username: username = sickbeard.XBMC_USERNAME if not password: password = sickbeard.XBMC_PASSWORD if not host: logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) return False for key in command: if type(command[key]) == unicode: command[key] = command[key].encode('utf-8') enc_command = urllib.urlencode(command) logger.log(u"XBMC encoded API command: " + enc_command, logger.DEBUG) url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command) try: req = urllib2.Request(url) # if we have a password, use authentication if password: base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) logger.log(u"Contacting XBMC (with auth header) via url: " + fixStupidEncodings(url), logger.DEBUG) else: logger.log(u"Contacting XBMC via url: " + fixStupidEncodings(url), logger.DEBUG) response = urllib2.urlopen(req) result = response.read().decode(sickbeard.SYS_ENCODING) response.close() logger.log(u"XBMC HTTP response: " + result.replace('\n', ''), logger.DEBUG) return result except (urllib2.URLError, IOError), e: logger.log(u"Warning: Couldn't contact XBMC HTTP at " + fixStupidEncodings(url) + " " + ex(e), logger.WARNING) return False def _update_library(self, host=None, showName=None): """Handles updating XBMC host via HTTP API Attempts to update the XBMC video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: XBMC webserver host:port showName: Name of a TV show to specifically target the library update for Returns: Returns True or False """ if not host: logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) return False logger.log(u"Updating XMBC library via HTTP method for host: " + host, logger.DEBUG) # if we're doing per-show if showName: logger.log(u"Updating library in XBMC via HTTP method for show " + showName, logger.DEBUG) pathSql = 'select path.strPath from path, tvshow, tvshowlinkpath where ' \ 'tvshow.c00 = "%s" and tvshowlinkpath.idShow = tvshow.idShow ' \ 'and tvshowlinkpath.idPath = path.idPath' % (showName) # use this to get xml back for the path lookups xmlCommand = {'command': 'SetResponseFormat(webheader;false;webfooter;false;header;<xml>;footer;</xml>;opentag;<tag>;closetag;</tag>;closefinaltag;false)'} # sql used to grab path(s) sqlCommand = {'command': 'QueryVideoDatabase(%s)' % (pathSql)} # set output back to default resetCommand = {'command': 'SetResponseFormat()'} # set xml response format, if this fails then don't bother with the rest request = self._send_to_xbmc(xmlCommand, host) if not request: return False sqlXML = self._send_to_xbmc(sqlCommand, host) request = self._send_to_xbmc(resetCommand, host) if not sqlXML: logger.log(u"Invalid response for " + showName + " on " + host, logger.DEBUG) return False encSqlXML = urllib.quote(sqlXML, ':\\/<>') try: et = etree.fromstring(encSqlXML) except SyntaxError, e: logger.log(u"Unable to parse XML returned from XBMC: " + ex(e), logger.ERROR) return False paths = et.findall('.//field') if not paths: logger.log(u"No valid paths found for " + showName + " on " + host, logger.DEBUG) return False for path in paths: # we do not need it double-encoded, gawd this is dumb unEncPath = urllib.unquote(path.text).decode(sickbeard.SYS_ENCODING) logger.log(u"XBMC Updating " + showName + " on " + host + " at " + unEncPath, logger.DEBUG) updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video, %s)' % (unEncPath)} request = self._send_to_xbmc(updateCommand, host) if not request: logger.log(u"Update of show directory failed on " + showName + " on " + host + " at " + unEncPath, logger.ERROR) return False # sleep for a few seconds just to be sure xbmc has a chance to finish each directory if len(paths) > 1: time.sleep(5) # do a full update if requested else: logger.log(u"Doing Full Library XBMC update on host: " + host, logger.DEBUG) updateCommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(video)'} request = self._send_to_xbmc(updateCommand, host) if not request: logger.log(u"XBMC Full Library update failed on: " + host, logger.ERROR) return False return True ############################################################################## # JSON-RPC API (XBMC 12+) methods ############################################################################## def _send_to_xbmc_json(self, command, host=None, username=None, password=None): """Handles communication to XBMC servers via JSONRPC Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the XBMC JSON-RPC via HTTP host: XBMC webserver host:port username: XBMC webserver username password: XBMC webserver password Returns: Returns response.result for successful commands or False if there was an error """ # fill in omitted parameters if not username: username = sickbeard.XBMC_USERNAME if not password: password = sickbeard.XBMC_PASSWORD if not host: logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) return False command = command.encode('utf-8') logger.log(u"XBMC JSON command: " + command, logger.DEBUG) url = 'http://%s/jsonrpc' % (host) try: req = urllib2.Request(url, command) req.add_header("Content-type", "application/json") # if we have a password, use authentication if password: base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) logger.log(u"Contacting XBMC (with auth header) via url: " + fixStupidEncodings(url), logger.DEBUG) else: logger.log(u"Contacting XBMC via url: " + fixStupidEncodings(url), logger.DEBUG) try: response = urllib2.urlopen(req) except urllib2.URLError, e: logger.log(u"Error while trying to retrieve XBMC API version for " + host + ": " + ex(e), logger.WARNING) return False # parse the json result try: result = json.load(response) response.close() logger.log(u"XBMC JSON response: " + str(result), logger.DEBUG) return result # need to return response for parsing except ValueError, e: logger.log(u"Unable to decode JSON: " + response, logger.WARNING) return False except IOError, e: logger.log(u"Warning: Couldn't contact XBMC JSON API at " + fixStupidEncodings(url) + " " + ex(e), logger.WARNING) return False def _update_library_json(self, host=None, showName=None): """Handles updating XBMC host via HTTP JSON-RPC Attempts to update the XBMC video library for a specific tv show if passed, otherwise update the whole library if enabled. Args: host: XBMC webserver host:port showName: Name of a TV show to specifically target the library update for Returns: Returns True or False """ if not host: logger.log(u'No XBMC host passed, aborting update', logger.DEBUG) return False logger.log(u"Updating XMBC library via JSON method for host: " + host, logger.MESSAGE) # if we're doing per-show if showName: tvshowid = -1 logger.log(u"Updating library in XBMC via JSON method for show " + showName, logger.DEBUG) # get tvshowid by showName showsCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.GetTVShows","id":1}' showsResponse = self._send_to_xbmc_json(showsCommand, host) if (showsResponse == False): return False shows = showsResponse["result"]["tvshows"] for show in shows: if (show["label"] == showName): tvshowid = show["tvshowid"] break # exit out of loop otherwise the label and showname will not match up # this can be big, so free some memory del shows # we didn't find the show (exact match), thus revert to just doing a full update if enabled if (tvshowid == -1): logger.log(u'Exact show name not matched in XBMC TV show list', logger.DEBUG) return False # lookup tv-show path pathCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.GetTVShowDetails","params":{"tvshowid":%d, "properties": ["file"]},"id":1}' % (tvshowid) pathResponse = self._send_to_xbmc_json(pathCommand, host) path = pathResponse["result"]["tvshowdetails"]["file"] logger.log(u"Received Show: " + show["label"] + " with ID: " + str(tvshowid) + " Path: " + path, logger.DEBUG) if (len(path) < 1): logger.log(u"No valid path found for " + showName + " with ID: " + str(tvshowid) + " on " + host, logger.WARNING) return False logger.log(u"XBMC Updating " + showName + " on " + host + " at " + path, logger.DEBUG) updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","params":{"directory":%s},"id":1}' % (json.dumps(path)) request = self._send_to_xbmc_json(updateCommand, host) if not request: logger.log(u"Update of show directory failed on " + showName + " on " + host + " at " + path, logger.ERROR) return False # catch if there was an error in the returned request for r in request: if 'error' in r: logger.log(u"Error while attempting to update show directory for " + showName + " on " + host + " at " + path, logger.ERROR) return False # do a full update if requested else: logger.log(u"Doing Full Library XBMC update on host: " + host, logger.MESSAGE) updateCommand = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan","id":1}' request = self._send_to_xbmc_json(updateCommand, host, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD) if not request: logger.log(u"XBMC Full Library update failed on: " + host, logger.ERROR) return False return True ############################################################################## # Public functions which will call the JSON or Legacy HTTP API methods ############################################################################## def notify_snatch(self, ep_name): if sickbeard.XBMC_NOTIFY_ONSNATCH: self._notify_xbmc(ep_name, common.notifyStrings[common.NOTIFY_SNATCH]) def notify_download(self, ep_name): if sickbeard.XBMC_NOTIFY_ONDOWNLOAD: self._notify_xbmc(ep_name, common.notifyStrings[common.NOTIFY_DOWNLOAD]) def notify_subtitle_download(self, ep_name, lang): if sickbeard.XBMC_NOTIFY_ONSUBTITLEDOWNLOAD: self._notify_xbmc(ep_name + ": " + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) def test_notify(self, host, username, password): return self._notify_xbmc("Testing XBMC notifications from Sick Beard", "Test Notification", host, username, password, force=True) def update_library(self, showName=None): """Public wrapper for the update library functions to branch the logic for JSON-RPC or legacy HTTP API Checks the XBMC API version to branch the logic to call either the legacy HTTP API or the newer JSON-RPC over HTTP methods. Do the ability of accepting a list of hosts deliminated by comma, we split off the first host to send the update to. This is a workaround for SQL backend users as updating multiple clients causes duplicate entries. Future plan is to revist how we store the host/ip/username/pw/options so that it may be more flexible. Args: showName: Name of a TV show to specifically target the library update for Returns: Returns True or False """ if sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY: if not sickbeard.XBMC_HOST: logger.log(u"No XBMC hosts specified, check your settings", logger.DEBUG) return False if sickbeard.XBMC_UPDATE_ONLYFIRST: # only send update to first host in the list if requested -- workaround for xbmc sql backend users host = sickbeard.XBMC_HOST.split(",")[0].strip() else: host = sickbeard.XBMC_HOST result = 0 for curHost in [x.strip() for x in host.split(",")]: logger.log(u"Sending request to update library for XBMC host: '" + curHost + "'", logger.MESSAGE) xbmcapi = self._get_xbmc_version(curHost, sickbeard.XBMC_USERNAME, sickbeard.XBMC_PASSWORD) if xbmcapi: if (xbmcapi <= 4): # try to update for just the show, if it fails, do full update if enabled if not self._update_library(curHost, showName) and sickbeard.XBMC_UPDATE_FULL: logger.log(u"Single show update failed, falling back to full update", logger.WARNING) self._update_library(curHost) else: # try to update for just the show, if it fails, do full update if enabled if not self._update_library_json(curHost, showName) and sickbeard.XBMC_UPDATE_FULL: logger.log(u"Single show update failed, falling back to full update", logger.WARNING) self._update_library_json(curHost) else: logger.log(u"Failed to detect XBMC version for '" + curHost + "', check configuration and try again.", logger.DEBUG) result = result + 1 # needed for the 'update xbmc' submenu command # as it only cares of the final result vs the individual ones if result == 0: return True else: return False notifier = XBMCNotifier
gpl-3.0
TheWardoctor/Wardoctors-repo
script.module.covenant/lib/resources/lib/modules/filmon.py
25
1267
# -*- coding: utf-8 -*- import re,urlparse,json from resources.lib.modules import client def resolve(url): try: if '/vod/' in url: url = re.compile('/(\d+)').findall(url)[-1] url = 'http://www.filmon.com/vod/info/%s' % url elif '/tv/' in url: url = url.replace('/tv/', '/channel/') elif not '/channel/' in url: raise Exception() headers = {'X-Requested-With': 'XMLHttpRequest'} cookie = client.request(url, output='cookie') cid = client.request(url, headers=headers) cid = json.loads(cid)['id'] headers = {'X-Requested-With': 'XMLHttpRequest', 'Referer': url} url = 'http://www.filmon.com/ajax/getChannelInfo?channel_id=%s' % cid result = client.request(url, cookie=cookie, headers=headers) result = json.loads(result) try: result = result['streams'] except: result = result['data']['streams'] result = [i[1] for i in result.items()] url = [(i['url'], int(i['watch-timeout'])) for i in result] url = [i for i in url if '.m3u8' in i[0]] url.sort() url = url[-1][0] return url except: return
apache-2.0
sarvex/tensorflow
tensorflow/compiler/tests/matrix_band_part_test.py
25
4854
# 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class MatrixBandPartTest(xla_test.XLATestCase, parameterized.TestCase): @parameterized.parameters( { 'batch_shape': [], 'rows': 1, 'cols': 1 }, { 'batch_shape': [], 'rows': 1, 'cols': 2 }, { 'batch_shape': [], 'rows': 1, 'cols': 7 }, { 'batch_shape': [], 'rows': 2, 'cols': 1 }, { 'batch_shape': [], 'rows': 2, 'cols': 2 }, { 'batch_shape': [], 'rows': 2, 'cols': 7 }, { 'batch_shape': [], 'rows': 7, 'cols': 1 }, { 'batch_shape': [], 'rows': 7, 'cols': 2 }, { 'batch_shape': [], 'rows': 7, 'cols': 7 }, { 'batch_shape': [2,], 'rows': 1, 'cols': 1 }, { 'batch_shape': [2,], 'rows': 1, 'cols': 2 }, { 'batch_shape': [2,], 'rows': 1, 'cols': 7 }, { 'batch_shape': [2,], 'rows': 2, 'cols': 1 }, { 'batch_shape': [2,], 'rows': 2, 'cols': 2 }, { 'batch_shape': [2,], 'rows': 2, 'cols': 7 }, { 'batch_shape': [2,], 'rows': 7, 'cols': 1 }, { 'batch_shape': [2,], 'rows': 7, 'cols': 2 }, { 'batch_shape': [2,], 'rows': 7, 'cols': 7 }, { 'batch_shape': [1, 3, 2], 'rows': 1, 'cols': 1 }, { 'batch_shape': [1, 3, 2], 'rows': 1, 'cols': 2 }, { 'batch_shape': [1, 3, 2], 'rows': 1, 'cols': 7 }, { 'batch_shape': [1, 3, 2], 'rows': 2, 'cols': 1 }, { 'batch_shape': [1, 3, 2], 'rows': 2, 'cols': 2 }, { 'batch_shape': [1, 3, 2], 'rows': 2, 'cols': 7 }, { 'batch_shape': [1, 3, 2], 'rows': 7, 'cols': 1 }, { 'batch_shape': [1, 3, 2], 'rows': 7, 'cols': 2 }, { 'batch_shape': [1, 3, 2], 'rows': 7, 'cols': 7 }, ) def testMatrixBandPart(self, batch_shape, rows, cols): # TODO(b/125505881): Disabled due to LLVM backend crash. if self.device == 'XLA_CPU' and cols == 7 and rows == 1 and batch_shape == [ 1, 3, 2 ]: pass for dtype in self.float_types: with self.session(): mat = np.ones(batch_shape + [rows, cols]).astype(dtype) batch_mat = np.tile(mat, batch_shape + [1, 1]) for lower in -1, 0, 1, rows - 1: for upper in -1, 0, 1, cols - 1: band_np = mat if lower >= 0: band_np = np.triu(band_np, -lower) if upper >= 0: band_np = np.tril(band_np, upper) if batch_shape: band_np = np.tile(band_np, batch_shape + [1, 1]) placeholder = array_ops.placeholder(dtype) with self.test_scope(): band = array_ops.matrix_band_part( placeholder, constant_op.constant(lower, dtype=dtypes.int32), constant_op.constant(upper, dtype=dtypes.int32)) feed_dict = {placeholder: batch_mat} self.assertAllEqual(band_np, band.eval(feed_dict=feed_dict)) if __name__ == "__main__": test.main()
apache-2.0
af1rst/bite-project
deps/gdata-python-client/samples/apps/marketplace_sample/gdata/tlslite/utils/jython_compat.py
358
5270
"""Miscellaneous functions to mask Python/Jython differences.""" import os import sha if os.name != "java": BaseException = Exception from sets import Set import array import math def createByteArraySequence(seq): return array.array('B', seq) def createByteArrayZeros(howMany): return array.array('B', [0] * howMany) def concatArrays(a1, a2): return a1+a2 def bytesToString(bytes): return bytes.tostring() def stringToBytes(s): bytes = createByteArrayZeros(0) bytes.fromstring(s) return bytes def numBits(n): if n==0: return 0 return int(math.floor(math.log(n, 2))+1) class CertChainBase: pass class SelfTestBase: pass class ReportFuncBase: pass #Helper functions for working with sets (from Python 2.3) def iterSet(set): return iter(set) def getListFromSet(set): return list(set) #Factory function for getting a SHA1 object def getSHA1(s): return sha.sha(s) import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: import java import jarray BaseException = java.lang.Exception def createByteArraySequence(seq): if isinstance(seq, type("")): #If it's a string, convert seq = [ord(c) for c in seq] return jarray.array(seq, 'h') #use short instead of bytes, cause bytes are signed def createByteArrayZeros(howMany): return jarray.zeros(howMany, 'h') #use short instead of bytes, cause bytes are signed def concatArrays(a1, a2): l = list(a1)+list(a2) return createByteArraySequence(l) #WAY TOO SLOW - MUST BE REPLACED------------ def bytesToString(bytes): return "".join([chr(b) for b in bytes]) def stringToBytes(s): bytes = createByteArrayZeros(len(s)) for count, c in enumerate(s): bytes[count] = ord(c) return bytes #WAY TOO SLOW - MUST BE REPLACED------------ def numBits(n): if n==0: return 0 n= 1L * n; #convert to long, if it isn't already return n.__tojava__(java.math.BigInteger).bitLength() #This properly creates static methods for Jython class staticmethod: def __init__(self, anycallable): self.__call__ = anycallable #Properties are not supported for Jython class property: def __init__(self, anycallable): pass #True and False have to be specially defined False = 0 True = 1 class StopIteration(Exception): pass def enumerate(collection): return zip(range(len(collection)), collection) class Set: def __init__(self, seq=None): self.values = {} if seq: for e in seq: self.values[e] = None def add(self, e): self.values[e] = None def discard(self, e): if e in self.values.keys(): del(self.values[e]) def union(self, s): ret = Set() for e in self.values.keys(): ret.values[e] = None for e in s.values.keys(): ret.values[e] = None return ret def issubset(self, other): for e in self.values.keys(): if e not in other.values.keys(): return False return True def __nonzero__( self): return len(self.values.keys()) def __contains__(self, e): return e in self.values.keys() def iterSet(set): return set.values.keys() def getListFromSet(set): return set.values.keys() """ class JCE_SHA1: def __init__(self, s=None): self.md = java.security.MessageDigest.getInstance("SHA1") if s: self.update(s) def update(self, s): self.md.update(s) def copy(self): sha1 = JCE_SHA1() sha1.md = self.md.clone() return sha1 def digest(self): digest = self.md.digest() bytes = jarray.zeros(20, 'h') for count in xrange(20): x = digest[count] if x < 0: x += 256 bytes[count] = x return bytes """ #Factory function for getting a SHA1 object #The JCE_SHA1 class is way too slow... #the sha.sha object we use instead is broken in the jython 2.1 #release, and needs to be patched def getSHA1(s): #return JCE_SHA1(s) return sha.sha(s) #Adjust the string to an array of bytes def stringToJavaByteArray(s): bytes = jarray.zeros(len(s), 'b') for count, c in enumerate(s): x = ord(c) if x >= 128: x -= 256 bytes[count] = x return bytes import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr
apache-2.0
Kazade/NeHe-Website
google_appengine/lib/django-1.2/tests/regressiontests/forms/localflavor/id.py
39
6972
from django.contrib.localflavor.id.forms import (IDPhoneNumberField, IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField, IDProvinceSelect, IDLicensePlatePrefixSelect) from utils import LocalFlavorTestCase class IDLocalFlavorTests(LocalFlavorTestCase): def test_IDProvinceSelect(self): f = IDProvinceSelect() out = u'''<select name="provinces"> <option value="BLI">Bali</option> <option value="BTN">Banten</option> <option value="BKL">Bengkulu</option> <option value="DIY">Yogyakarta</option> <option value="JKT">Jakarta</option> <option value="GOR">Gorontalo</option> <option value="JMB">Jambi</option> <option value="JBR">Jawa Barat</option> <option value="JTG">Jawa Tengah</option> <option value="JTM">Jawa Timur</option> <option value="KBR">Kalimantan Barat</option> <option value="KSL">Kalimantan Selatan</option> <option value="KTG">Kalimantan Tengah</option> <option value="KTM">Kalimantan Timur</option> <option value="BBL">Kepulauan Bangka-Belitung</option> <option value="KRI">Kepulauan Riau</option> <option value="LPG" selected="selected">Lampung</option> <option value="MLK">Maluku</option> <option value="MUT">Maluku Utara</option> <option value="NAD">Nanggroe Aceh Darussalam</option> <option value="NTB">Nusa Tenggara Barat</option> <option value="NTT">Nusa Tenggara Timur</option> <option value="PPA">Papua</option> <option value="PPB">Papua Barat</option> <option value="RIU">Riau</option> <option value="SLB">Sulawesi Barat</option> <option value="SLS">Sulawesi Selatan</option> <option value="SLT">Sulawesi Tengah</option> <option value="SLR">Sulawesi Tenggara</option> <option value="SLU">Sulawesi Utara</option> <option value="SMB">Sumatera Barat</option> <option value="SMS">Sumatera Selatan</option> <option value="SMU">Sumatera Utara</option> </select>''' self.assertEqual(f.render('provinces', 'LPG'), out) def test_IDLicensePlatePrefixSelect(self): f = IDLicensePlatePrefixSelect() out = u'''<select name="codes"> <option value="A">Banten</option> <option value="AA">Magelang</option> <option value="AB">Yogyakarta</option> <option value="AD">Surakarta - Solo</option> <option value="AE">Madiun</option> <option value="AG">Kediri</option> <option value="B">Jakarta</option> <option value="BA">Sumatera Barat</option> <option value="BB">Tapanuli</option> <option value="BD">Bengkulu</option> <option value="BE" selected="selected">Lampung</option> <option value="BG">Sumatera Selatan</option> <option value="BH">Jambi</option> <option value="BK">Sumatera Utara</option> <option value="BL">Nanggroe Aceh Darussalam</option> <option value="BM">Riau</option> <option value="BN">Kepulauan Bangka Belitung</option> <option value="BP">Kepulauan Riau</option> <option value="CC">Corps Consulate</option> <option value="CD">Corps Diplomatic</option> <option value="D">Bandung</option> <option value="DA">Kalimantan Selatan</option> <option value="DB">Sulawesi Utara Daratan</option> <option value="DC">Sulawesi Barat</option> <option value="DD">Sulawesi Selatan</option> <option value="DE">Maluku</option> <option value="DG">Maluku Utara</option> <option value="DH">NTT - Timor</option> <option value="DK">Bali</option> <option value="DL">Sulawesi Utara Kepulauan</option> <option value="DM">Gorontalo</option> <option value="DN">Sulawesi Tengah</option> <option value="DR">NTB - Lombok</option> <option value="DS">Papua dan Papua Barat</option> <option value="DT">Sulawesi Tenggara</option> <option value="E">Cirebon</option> <option value="EA">NTB - Sumbawa</option> <option value="EB">NTT - Flores</option> <option value="ED">NTT - Sumba</option> <option value="F">Bogor</option> <option value="G">Pekalongan</option> <option value="H">Semarang</option> <option value="K">Pati</option> <option value="KB">Kalimantan Barat</option> <option value="KH">Kalimantan Tengah</option> <option value="KT">Kalimantan Timur</option> <option value="L">Surabaya</option> <option value="M">Madura</option> <option value="N">Malang</option> <option value="P">Jember</option> <option value="R">Banyumas</option> <option value="RI">Federal Government</option> <option value="S">Bojonegoro</option> <option value="T">Purwakarta</option> <option value="W">Sidoarjo</option> <option value="Z">Garut</option> </select>''' self.assertEqual(f.render('codes', 'BE'), out) def test_IDPhoneNumberField(self): error_invalid = [u'Enter a valid phone number'] valid = { '0812-3456789': u'0812-3456789', '081234567890': u'081234567890', '021 345 6789': u'021 345 6789', '0213456789': u'0213456789', '+62-21-3456789': u'+62-21-3456789', '(021) 345 6789': u'(021) 345 6789', } invalid = { '0123456789': error_invalid, '+62-021-3456789': error_invalid, '+62-021-3456789': error_invalid, '+62-0812-3456789': error_invalid, '0812345678901': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDPhoneNumberField, valid, invalid) def test_IDPostCodeField(self): error_invalid = [u'Enter a valid post code'] valid = { '12340': u'12340', '25412': u'25412', ' 12340 ': u'12340', } invalid = { '12 3 4 0': error_invalid, '12345': error_invalid, '10100': error_invalid, '123456': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDPostCodeField, valid, invalid) def test_IDNationalIdentityNumberField(self): error_invalid = [u'Enter a valid NIK/KTP number'] valid = { ' 12.3456.010178 3456 ': u'12.3456.010178.3456', '1234560101783456': u'12.3456.010178.3456', '12.3456.010101.3456': u'12.3456.010101.3456', } invalid = { '12.3456.310278.3456': error_invalid, '00.0000.010101.0000': error_invalid, '1234567890123456': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDNationalIdentityNumberField, valid, invalid) def test_IDLicensePlateField(self): error_invalid = [u'Enter a valid vehicle license plate number'] valid = { ' b 1234 ab ': u'B 1234 AB', 'B 1234 ABC': u'B 1234 ABC', 'A 12': u'A 12', 'DK 12345 12': u'DK 12345 12', 'RI 10': u'RI 10', 'CD 12 12': u'CD 12 12', } invalid = { 'CD 10 12': error_invalid, 'CD 1234 12': error_invalid, 'RI 10 AB': error_invalid, 'B 12345 01': error_invalid, 'N 1234 12': error_invalid, 'A 12 XYZ': error_invalid, 'Q 1234 AB': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDLicensePlateField, valid, invalid)
bsd-3-clause
TRESCLOUD/odoopub
addons/website_crm_partner_assign/controllers/main.py
63
7473
# -*- coding: utf-8 -*- import werkzeug from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.models.website import slug, unslug from openerp.tools.translate import _ class WebsiteCrmPartnerAssign(http.Controller): _references_per_page = 40 @http.route([ '/partners', '/partners/page/<int:page>', '/partners/grade/<model("res.partner.grade"):grade>', '/partners/grade/<model("res.partner.grade"):grade>/page/<int:page>', '/partners/country/<model("res.country"):country>', '/partners/country/<model("res.country"):country>/page/<int:page>', '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>', '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>/page/<int:page>', ], type='http', auth="public", website=True) def partners(self, country=None, grade=None, page=0, **post): country_all = post.pop('country_all', False) partner_obj = request.registry['res.partner'] country_obj = request.registry['res.country'] search = post.get('search', '') base_partner_domain = [('is_company', '=', True), ('grade_id.website_published', '=', True), ('website_published', '=', True)] if search: base_partner_domain += ['|', ('name', 'ilike', search), ('website_description', 'ilike', search)] # group by grade grade_domain = list(base_partner_domain) if not country and not country_all: country_code = request.session['geoip'].get('country_code') if country_code: country_ids = country_obj.search(request.cr, request.uid, [('code', '=', country_code)], context=request.context) if country_ids: country = country_obj.browse(request.cr, request.uid, country_ids[0], context=request.context) if country: grade_domain += [('country_id', '=', country.id)] grades = partner_obj.read_group( request.cr, SUPERUSER_ID, grade_domain, ["id", "grade_id"], groupby="grade_id", orderby="grade_id DESC", context=request.context) grades_partners = partner_obj.search( request.cr, SUPERUSER_ID, grade_domain, context=request.context, count=True) # flag active grade for grade_dict in grades: grade_dict['active'] = grade and grade_dict['grade_id'][0] == grade.id grades.insert(0, { 'grade_id_count': grades_partners, 'grade_id': (0, _("All Categories")), 'active': bool(grade is None), }) # group by country country_domain = list(base_partner_domain) if grade: country_domain += [('grade_id', '=', grade.id)] countries = partner_obj.read_group( request.cr, SUPERUSER_ID, country_domain, ["id", "country_id"], groupby="country_id", orderby="country_id", context=request.context) countries_partners = partner_obj.search( request.cr, SUPERUSER_ID, country_domain, context=request.context, count=True) # flag active country for country_dict in countries: country_dict['active'] = country and country_dict['country_id'] and country_dict['country_id'][0] == country.id countries.insert(0, { 'country_id_count': countries_partners, 'country_id': (0, _("All Countries")), 'active': bool(country is None), }) # current search if grade: base_partner_domain += [('grade_id', '=', grade.id)] if country: base_partner_domain += [('country_id', '=', country.id)] # format pager if grade and not country: url = '/partners/grade/' + slug(grade) elif country and not grade: url = '/partners/country/' + slug(country) elif country and grade: url = '/partners/grade/' + slug(grade) + '/country/' + slug(country) else: url = '/partners' url_args = {} if search: url_args['search'] = search partner_count = partner_obj.search_count( request.cr, SUPERUSER_ID, base_partner_domain, context=request.context) pager = request.website.pager( url=url, total=partner_count, page=page, step=self._references_per_page, scope=7, url_args=url_args) # search partners matching current search parameters partner_ids = partner_obj.search( request.cr, SUPERUSER_ID, base_partner_domain, order="grade_id DESC", context=request.context) # todo in trunk: order="grade_id DESC, implemented_count DESC", offset=pager['offset'], limit=self._references_per_page partners = partner_obj.browse(request.cr, SUPERUSER_ID, partner_ids, request.context) # remove me in trunk partners = sorted(partners, key=lambda x: (x.grade_id.sequence if x.grade_id else 0, len([i for i in x.implemented_partner_ids if i.website_published])), reverse=True) partners = partners[pager['offset']:pager['offset'] + self._references_per_page] google_map_partner_ids = ','.join(map(str, [p.id for p in partners])) values = { 'countries': countries, 'current_country': country, 'grades': grades, 'current_grade': grade, 'partners': partners, 'google_map_partner_ids': google_map_partner_ids, 'pager': pager, 'searches': post, 'search_path': "%s" % werkzeug.url_encode(post), } return request.website.render("website_crm_partner_assign.index", values) # Do not use semantic controller due to SUPERUSER_ID @http.route(['/partners/<partner_id>'], type='http', auth="public", website=True) def partners_detail(self, partner_id, partner_name='', **post): _, partner_id = unslug(partner_id) current_grade, current_country = None, None grade_id = post.get('grade_id') country_id = post.get('country_id') if grade_id: grade_ids = request.registry['res.partner.grade'].exists(request.cr, request.uid, int(grade_id), context=request.context) if grade_ids: current_grade = request.registry['res.partner.grade'].browse(request.cr, request.uid, grade_ids[0], context=request.context) if country_id: country_ids = request.registry['res.country'].exists(request.cr, request.uid, int(country_id), context=request.context) if country_ids: current_country = request.registry['res.country'].browse(request.cr, request.uid, country_ids[0], context=request.context) if partner_id: partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id, context=request.context) if partner.exists() and partner.website_published: values = { 'main_object': partner, 'partner': partner, 'current_grade': current_grade, 'current_country': current_country } return request.website.render("website_crm_partner_assign.partner", values) return self.partners(**post)
agpl-3.0
UWMediBook/backend
db/migrations/0004_auto_20160719_0254.py
1
1783
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-19 02:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('db', '0003_auto_20160717_2102'), ] operations = [ migrations.CreateModel( name='Physician', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, unique=True)), ('first_name', models.CharField(default=b'', max_length=30)), ('last_name', models.CharField(default=b'', max_length=30)), ('phone_number', models.CharField(default=b'', max_length=15)), ('address', models.CharField(default=b'', max_length=255)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.AddField( model_name='doctor', name='email', field=models.CharField(default=b'', max_length=255), ), migrations.AddField( model_name='doctor', name='password', field=models.CharField(default=b'wordpass', max_length=255), ), migrations.AlterField( model_name='user', name='doctor', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='doctor_users', to='db.Doctor'), ), migrations.AddField( model_name='physician', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_physicians', to='db.User'), ), ]
apache-2.0
paulross/cpip
src/cpip/util/StrTree.py
1
3197
#!/usr/bin/env python # CPIP is a C/C++ Preprocessor implemented in Python. # Copyright (C) 2008-2017 Paul Ross # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Paul Ross: apaulross@gmail.com """Treats a string as a tree.""" __author__ = 'Paul Ross' __date__ = '2011-07-10' __rights__ = 'Copyright (c) 2008-2017 Paul Ross' #import os #import time #import logging class StrTree(object): """A string tree or Trie.""" def __init__(self, theIterable=None): """Initialise the class with a optional sequence of strings. :param theIterable: A sequence of strings. :type theIterable: ``NoneType, set([str])`` :returns: ``NoneType``""" self._ir = {} self._b = False if theIterable is not None: for aS in theIterable: self.add(aS) def __str__(self): return '\n'.join(self._str(0)) def _str(self, d): p = ' ' * d sL = ['%s%s %d' % (p, self._b, d)] kS = self._ir.keys() for k in kS: sL.append('%s"%s"' % (p, k)) sL.extend(self._ir[k]._str(d+1)) return sL def add(self, s): """Add a string. :param s: The string to add. :type s: ``str`` :returns: ``NoneType``""" if s: if s[0] not in self._ir: self._ir[s[0]] = StrTree() self._ir[s[0]].add(s[1:]) else: self._b = True def has(self, s, i=0): """Returns the index of the end of s that match a complete word in the tree. i.e. ``[i:return_value]`` is in the dictionary. :param s: value :type s: :py:class:`cpip.util.BufGen.BufGen`, ``str`` :param i: index :type i: ``int`` :returns: ``int`` -- index. :raises: ``IndexError, KeyError`` NOTE: IndexError and KeyError are trapped here. """ assert(i >= 0) try: myI = self._ir[s[i]].has(s, i+1) if myI > 0: return myI if self._b: return i except (IndexError, KeyError): if self._b: return i return 0 def values(self): """Returns all values.""" return self._values([]) def _values(self, l): r = [] if self._b: r.append(''.join(l)) for k in self._ir.keys(): l.append(k) r.extend(self._ir[k]._values(l)) l.pop() return r
gpl-2.0
nanditav/15712-TensorFlow
tensorflow/python/framework/common_shapes.py
2
23611
# Copyright 2015 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 library of common shape functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six.moves from tensorflow.python import pywrap_tensorflow from tensorflow.python.framework import cpp_shape_inference_pb2 from tensorflow.python.framework import errors from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util def scalar_shape(unused_op): """Shape function for ops that output a scalar value.""" return [tensor_shape.scalar()] def unchanged_shape(op): """Shape function for ops that output an tensor like their first input.""" return [op.inputs[0].get_shape()] def unchanged_shape_with_rank(rank): """Returns a shape function for ops that constrain the rank of their input. Args: rank: The exact rank of the input and output. Returns: A shape function for ops that output a tensor of the same size as their input, with a particular rank. """ def _ShapeFunction(op): return [op.inputs[0].get_shape().with_rank(rank)] return _ShapeFunction def unchanged_shape_with_rank_at_least(rank): """Returns a shape function for ops that constrain the rank of their input. Args: rank: A lower bound on the rank of the input and output. Returns: A shape function for ops that output a tensor of the same size as their input, with a particular rank. """ def _ShapeFunction(op): return [op.inputs[0].get_shape().with_rank_at_least(rank)] return _ShapeFunction def unchanged_shape_with_rank_at_most(rank): """Returns a shape function for ops that constrain the rank of their input. Args: rank: An upper bound on the rank of the input and output. Returns: A shape function for ops that output a tensor of the same size as their input, with a particular rank. """ def _ShapeFunction(op): return [op.inputs[0].get_shape().with_rank_at_most(rank)] return _ShapeFunction def matmul_shape(op): """Shape function for a MatMul op.""" a_shape = op.inputs[0].get_shape().with_rank(2) transpose_a = op.get_attr("transpose_a") b_shape = op.inputs[1].get_shape().with_rank(2) transpose_b = op.get_attr("transpose_b") output_rows = a_shape[1] if transpose_a else a_shape[0] output_cols = b_shape[0] if transpose_b else b_shape[1] inner_a = a_shape[0] if transpose_a else a_shape[1] inner_b = b_shape[1] if transpose_b else b_shape[0] inner_a.assert_is_compatible_with(inner_b) return [tensor_shape.TensorShape([output_rows, output_cols])] def get_conv_output_size(input_size, filter_size, strides, padding_type): """Returns the spatial size of a n-d convolution/pooling output.""" input_size = tuple([tensor_shape.as_dimension(x).value for x in input_size]) filter_size = tuple([tensor_shape.as_dimension(x).value for x in filter_size]) strides = [int(x) for x in strides] if all(x == 1 for x in input_size) and all(x == 1 for x in filter_size): return input_size if any(x is not None and y is not None and x > y for x, y in zip(filter_size, input_size)): raise ValueError("Filter must not be larger than the input: " "Filter: %r Input: %r" % (filter_size, input_size)) if padding_type == b"VALID": def _valid(in_dim, k_dim, s_dim): if in_dim is not None and k_dim is not None: return (in_dim - k_dim + s_dim) // s_dim else: return None output_size = [ _valid(in_dim, k_dim, s_dim) for in_dim, k_dim, s_dim in zip(input_size, filter_size, strides) ] elif padding_type == b"SAME": def _same(in_dim, s_dim): if in_dim is not None: return (in_dim + s_dim - 1) // s_dim else: return None output_size = [_same(in_dim, s_dim) for in_dim, s_dim in zip(input_size, strides)] else: raise ValueError("Invalid padding: %r" % padding_type) return tuple(output_size) def get2d_conv_output_size(input_height, input_width, filter_height, filter_width, row_stride, col_stride, padding_type): """Returns the number of rows and columns in a convolution/pooling output.""" return get_conv_output_size((input_height, input_width), (filter_height, filter_width), (row_stride, col_stride), padding_type) def conv2d_shape(op): """Shape function for a Conv2D op. This op has two inputs: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] * filter, a 4D tensor with shape = [filter_rows, filter_cols, depth_in, depth_out] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows and out_cols depend on the value of the op's "padding" and "strides" attrs. Args: op: A Conv2D Operation. Returns: A list containing the Shape of the Conv2D output. Raises: ValueError: If the shapes of the input or filter are incompatible. """ input_shape = op.inputs[0].get_shape().with_rank(4) filter_shape = op.inputs[1].get_shape().with_rank(4) try: data_format = op.get_attr("data_format") except ValueError: data_format = None if data_format == b"NCHW": # Convert input shape to the default NHWC for inference. input_shape = [input_shape[0], input_shape[2], input_shape[3], input_shape[1]] batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] filter_rows = filter_shape[0] filter_cols = filter_shape[1] depth_out = filter_shape[3] # Check that the input depths are compatible. input_shape[3].assert_is_compatible_with(filter_shape[2]) if data_format == b"NCHW": stride_b, stride_d, stride_r, stride_c = op.get_attr("strides") else: stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") if stride_b != 1 or stride_d != 1: raise ValueError("Current implementation does not yet support " "strides in the batch and depth dimensions.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, filter_rows, filter_cols, stride_r, stride_c, padding) output_shape = [batch_size, out_rows, out_cols, depth_out] if data_format == b"NCHW": # Convert output shape back to NCHW. output_shape = [output_shape[0], output_shape[3], output_shape[1], output_shape[2]] return [tensor_shape.TensorShape(output_shape)] def depthwise_conv2d_native_shape(op): """Shape function for a DepthwiseConv2D op. This op has two inputs: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] * filter, a 4D tensor with shape = [filter_rows, filter_cols, depth_in, depthwise_multiplier] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_in*depthwise_multiplier], where out_rows and out_cols depend on the value of the op's "padding" and "strides" attrs. Args: op: A DepthwiseConv2dNative Operation. Returns: A list containing the Shape of the DepthwiseConv2DNative output. Raises: ValueError: If the shapes of the input or filter are incompatible. """ input_shape = op.inputs[0].get_shape().with_rank(4) filter_shape = op.inputs[1].get_shape().with_rank(4) batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] filter_rows = filter_shape[0] filter_cols = filter_shape[1] depth_out = filter_shape[3] * filter_shape[2] # Check that the input depths are compatible. input_shape[3].assert_is_compatible_with(filter_shape[2]) stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") if stride_b != 1 or stride_d != 1: raise ValueError("Current implementation does not yet support " "strides in the batch and depth dimensions.") if stride_r != stride_c: # TODO(shlens): Add support for this. raise ValueError("Current implementation only supports equal length " "strides in the row and column dimensions.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. stride = stride_r padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, filter_rows, filter_cols, stride, stride, padding) return [tensor_shape.TensorShape([batch_size, out_rows, out_cols, depth_out])] def separable_conv2d_shape(op): """Shape function for a SeparableConv2D op. This op has three inputs: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] * depthwise_filter, a 4D tensor with shape = [filter_rows, filter_cols, depth_in, depth_multiplier] * pointwise_filter, a 4D tensor with shape = [1, 1, depth_in * depth_multiplier, depth_out] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows and out_cols depend on the value of the op's "padding" and "strides" attrs. Args: op: A SeparableConv2D Operation. Returns: A list containing the Shape of the SeparableConv2D output. Raises: ValueError: If the shapes of the input or filter are incompatible. """ input_shape = op.inputs[0].get_shape().with_rank(4) depthwise_filter_shape = op.inputs[1].get_shape().merge_with( tensor_shape.TensorShape([None, None, input_shape[3], None])) pointwise_depth_in = depthwise_filter_shape[2] * depthwise_filter_shape[3] pointwise_filter_shape = op.inputs[2].get_shape().merge_with( tensor_shape.TensorShape([1, 1, pointwise_depth_in, None])) batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] filter_rows = depthwise_filter_shape[0] filter_cols = depthwise_filter_shape[1] depth_out = pointwise_filter_shape[3] stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") if stride_b != 1 or stride_d != 1: raise ValueError("Current implementation does not yet support " "strides in the batch and depth dimensions.") if stride_r != stride_c: # TODO(shlens): Add support for this. raise ValueError("Current implementation only supports equal length " "strides in the row and column dimensions.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. stride = stride_r padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, filter_rows, filter_cols, stride, stride, padding) return [tensor_shape.TensorShape([batch_size, out_rows, out_cols, depth_out])] def avg_pool_shape(op): """Shape function for an AvgPool op. This op has one input: * input, a 4D tensor with shape = [batch_size, rows, cols, depth] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows and out_cols depend on the value of the op's "ksize", "strides", and "padding" attrs. Args: op: An AvgPool Operation. Returns: A single-element list containing the Shape of the AvgPool output. Raises: ValueError: If the shape of the input is invalid or incompatible with the values of the attrs. """ input_shape = op.inputs[0].get_shape().with_rank(4) try: data_format = op.get_attr("data_format") except ValueError: data_format = None if data_format == b"NCHW": # Convert input shape to the default NHWC for inference. input_shape = [input_shape[0], input_shape[2], input_shape[3], input_shape[1]] if data_format == b"NCHW": ksize_b, ksize_d, ksize_r, ksize_c = op.get_attr("ksize") stride_b, stride_d, stride_r, stride_c = op.get_attr("strides") else: ksize_b, ksize_r, ksize_c, ksize_d = op.get_attr("ksize") stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] depth = input_shape[3] if ksize_b != 1 or ksize_d != 1: raise ValueError("Current implementation does not support pooling " "in the batch and depth dimensions.") if stride_b != 1 or stride_d != 1: raise ValueError("Current implementation does not support strides " "in the batch and depth dimensions.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, ksize_r, ksize_c, stride_r, stride_c, padding) output_shape = [batch_size, out_rows, out_cols, depth] if data_format == b"NCHW": # Convert output shape back to NCHW. output_shape = [output_shape[0], output_shape[3], output_shape[1], output_shape[2]] return [tensor_shape.TensorShape(output_shape)] def max_pool_shape(op): """Shape function for a MaxPool op. This op has one input: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows, out_cols, and depth_out depend on the value of the op's "ksize", "strides", and "padding" attrs. Args: op: A MaxPool Operation. Returns: A single-element list containing the Shape of the MaxPool output. Raises: ValueError: If the shape of the input is invalid or incompatible with the values of the attrs. """ input_shape = op.inputs[0].get_shape().with_rank(4) try: data_format = op.get_attr("data_format") except ValueError: data_format = None if data_format == b"NCHW": # Convert input shape to the default NHWC for inference. input_shape = [input_shape[0], input_shape[2], input_shape[3], input_shape[1]] if data_format == b"NCHW": ksize_b, ksize_d, ksize_r, ksize_c = op.get_attr("ksize") stride_b, stride_d, stride_r, stride_c = op.get_attr("strides") else: ksize_b, ksize_r, ksize_c, ksize_d = op.get_attr("ksize") stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] depth = input_shape[3] if ksize_b != 1: raise ValueError("Current implementation does not support pooling " "in the batch dimension.") if stride_b != 1: raise ValueError("Current implementation does not support strides " "in the batch dimension.") if not ((ksize_r == 1 and ksize_c == 1) or ksize_d == 1): raise ValueError("MaxPooling supports exactly one of pooling across depth " "or pooling across width/height.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. if ksize_d == 1: padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, ksize_r, ksize_c, stride_r, stride_c, padding) output_shape = [batch_size, out_rows, out_cols, depth] else: if depth % ksize_d > 0: raise ValueError("Depthwise max pooling requires the depth window " "to evenly divide the input depth.") if stride_d != ksize_d: raise ValueError("Depthwise max pooling requires the depth window " "to equal the depth stride.") output_shape = [batch_size, in_rows, in_cols, depth // ksize_d] if data_format == b"NCHW": # Convert output shape back to NCHW. output_shape = [output_shape[0], output_shape[3], output_shape[1], output_shape[2]] return [tensor_shape.TensorShape(output_shape)] def no_outputs(unused_op): """Shape function for use with ops that have no outputs.""" return [] def unknown_shape(op): """Shape function for use with ops whose output shapes are unknown.""" return [tensor_shape.unknown_shape() for _ in op.outputs] def broadcast_shape(shape_x, shape_y): """Returns the broadcasted shape between `shape_x` and `shape_y`. Args: shape_x: A `TensorShape` shape_y: A `TensorShape` Returns: A `TensorShape` representing the broadcasted shape. Raises: ValueError: If the two shapes can not be broadcasted. """ if shape_x.ndims is None or shape_y.ndims is None: return tensor_shape.unknown_shape() # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed(list(six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tensor_shape.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. # TODO(mrry): If we eliminate the shape checks in C++, we must still # assert that the unknown dim is either 1 or the same as the known dim. if dim_x.value is not None and dim_x.value > 1: return_dims.append(dim_x) elif dim_y.value is not None and dim_y.value > 1: return_dims.append(dim_y) else: return_dims.append(None) elif dim_x.value == 1: # We will broadcast dim_x to dim_y. return_dims.append(dim_y) elif dim_y.value == 1: # We will broadcast dim_y to dim_x. return_dims.append(dim_x) elif dim_x.value == dim_y.value: # The dimensions are compatible, so output is the same size in that # dimension. return_dims.append(dim_x.merge_with(dim_y)) else: raise ValueError("Incompatible shapes for broadcasting: %s and %s" % (shape_x, shape_y)) return tensor_shape.TensorShape(return_dims) def call_cpp_shape_fn(op, input_tensors_needed=None, input_tensors_as_shapes_needed=None, debug_python_shape_fn=None): """A shape function that delegates to the registered C++ shape function. Args: op: the node in the graph for which to compute output shapes. input_tensors_needed: a list of input tensor indices for which to compute the input tensor's value and pass to the C++ shape function. input_tensors_as_shapes_needed: a list of input tensor indices for which to compute the constant_value_as_shape and pass to the C++ shape function. debug_python_shape_fn: For testing only during migration to using call_cpp_shape_fn. Do not submit calls that set this, as the comparison is slow. If non-None, the python shape function; this function will be called and its output compared to that of the C++ shape function. Returns: A dictionary with the following keys: shapes: A TensorShape list of the output shapes of the op, as computed using the C++ shape inference function registered for the op. handle_shapes: A TensorShape list of the shapes for handle outputs, if any. handle_dtypes: A list of DataType enums for the handle outputs, if any. Raises: ValueError: If the C++ shape function returned an error (e.g. because the shapes of the inputs are of the wrong rank or otherwise incompatible according to the shape function). """ node_def_str = op.node_def.SerializeToString() def tensor_to_inference_result(t): r = cpp_shape_inference_pb2.CppShapeInferenceResult() r.shape.CopyFrom(t.get_shape().as_proto()) # pylint: disable=protected-access r.handle_shape.CopyFrom(t._handle_shape) r.handle_dtype = t._handle_dtype # pylint: enable=protected-access return r.SerializeToString() input_shapes = [tensor_to_inference_result(i) for i in op.inputs] input_tensors = [None for i in input_shapes] if input_tensors_needed: for idx in input_tensors_needed: v = tensor_util.constant_value(op.inputs[idx]) if v is not None: input_tensors[idx] = np.asarray(v) serialized_unknown_shape = ( tensor_shape.TensorShape(None).as_proto().SerializeToString()) arr = [serialized_unknown_shape for i in input_shapes] if input_tensors_as_shapes_needed: for idx in input_tensors_as_shapes_needed: s = tensor_util.constant_value_as_shape(op.inputs[idx]) if s is not None: arr[idx] = s.as_proto().SerializeToString() input_tensors_as_shapes = arr try: with errors.raise_exception_on_not_ok_status() as status: output_shapes = pywrap_tensorflow.RunCppShapeInference( node_def_str, input_shapes, input_tensors, input_tensors_as_shapes, status) except errors.InvalidArgumentError as err: raise ValueError(err.message) # Convert TensorShapeProto values in output_shapes. result_protos = [ cpp_shape_inference_pb2.CppShapeInferenceResult().FromString(s) for s in output_shapes ] result = [r.shape for r in result_protos] result_handle_shapes = [r.handle_shape for r in result_protos] result_handle_dtypes = [r.handle_dtype for r in result_protos] if debug_python_shape_fn: try: python_result = [tensor_shape.as_shape(s) for s in debug_python_shape_fn(op)] except Exception as err: raise AssertionError("Python shape function return error but " "C++ shape functon did not: %s" % str(err)) if str(result) != str(python_result): raise ValueError( ("Python vs CPP shape mismatch. " "CPP: %s vs python: %s on node %s " "with input shapes %s") % ( str(result), str(python_result), str(op.node_def), ",".join([str(i.get_shape()) for i in op.inputs]))) return {"shapes": result, "handle_shapes": result_handle_shapes, "handle_dtypes": result_handle_dtypes}
apache-2.0
mortcanty/earthengine
src/Crypto/Signature/PKCS1_PSS.py
123
12228
# -*- coding: utf-8 -*- # # Signature/PKCS1_PSS.py : PKCS#1 PPS # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """RSA digital signature protocol with appendix according to PKCS#1 PSS. See RFC3447__ or the `original RSA Labs specification`__. This scheme is more properly called ``RSASSA-PSS``. For example, a sender may authenticate a message using SHA-1 and PSS like this: >>> from Crypto.Signature import PKCS1_PSS >>> from Crypto.Hash import SHA >>> from Crypto.PublicKey import RSA >>> from Crypto import Random >>> >>> message = 'To be signed' >>> key = RSA.importKey(open('privkey.der').read()) >>> h = SHA.new() >>> h.update(message) >>> signer = PKCS1_PSS.new(key) >>> signature = PKCS1_PSS.sign(key) At the receiver side, verification can be done like using the public part of the RSA key: >>> key = RSA.importKey(open('pubkey.der').read()) >>> h = SHA.new() >>> h.update(message) >>> verifier = PKCS1_PSS.new(key) >>> if verifier.verify(h, signature): >>> print "The signature is authentic." >>> else: >>> print "The signature is not authentic." :undocumented: __revision__, __package__ .. __: http://www.ietf.org/rfc/rfc3447.txt .. __: http://www.rsa.com/rsalabs/node.asp?id=2125 """ # Allow nested scopes in Python 2.1 # See http://oreilly.com/pub/a/python/2001/04/19/pythonnews.html from __future__ import nested_scopes __revision__ = "$Id$" __all__ = [ 'new', 'PSS_SigScheme' ] from Crypto.Util.py3compat import * if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * import Crypto.Util.number from Crypto.Util.number import ceil_shift, ceil_div, long_to_bytes from Crypto.Util.strxor import strxor class PSS_SigScheme: """This signature scheme can perform PKCS#1 PSS RSA signature or verification.""" def __init__(self, key, mgfunc, saltLen): """Initialize this PKCS#1 PSS signature scheme object. :Parameters: key : an RSA key object If a private half is given, both signature and verification are possible. If a public half is given, only verification is possible. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. saltLen : int Length of the salt, in bytes. """ self._key = key self._saltLen = saltLen self._mgfunc = mgfunc def can_sign(self): """Return True if this cipher object can be used for signing messages.""" return self._key.has_private() def sign(self, mhash): """Produce the PKCS#1 PSS signature of a message. This function is named ``RSASSA-PSS-SIGN``, and is specified in section 8.1.1 of RFC3447. :Parameters: mhash : hash object The hash that was carried out over the message. This is an object belonging to the `Crypto.Hash` module. :Return: The PSS signature encoded as a string. :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given hash algorithm. :Raise TypeError: If the RSA key has no private half. :attention: Modify the salt length and the mask generation function only if you know what you are doing. The receiver must use the same parameters too. """ # TODO: Verify the key is RSA randfunc = self._key._randfunc # Set defaults for salt length and mask generation function if self._saltLen == None: sLen = mhash.digest_size else: sLen = self._saltLen if self._mgfunc: mgf = self._mgfunc else: mgf = lambda x,y: MGF1(x,y,mhash) modBits = Crypto.Util.number.size(self._key.n) # See 8.1.1 in RFC3447 k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 em = EMSA_PSS_ENCODE(mhash, modBits-1, randfunc, mgf, sLen) # Step 2a (OS2IP) and 2b (RSASP1) m = self._key.decrypt(em) # Step 2c (I2OSP) S = bchr(0x00)*(k-len(m)) + m return S def verify(self, mhash, S): """Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: mhash : hash object The hash that was carried out over the message. This is an object belonging to the `Crypto.Hash` module. S : string The signature that needs to be validated. :Return: True if verification is correct. False otherwise. """ # TODO: Verify the key is RSA # Set defaults for salt length and mask generation function if self._saltLen == None: sLen = mhash.digest_size else: sLen = self._saltLen if self._mgfunc: mgf = self._mgfunc else: mgf = lambda x,y: MGF1(x,y,mhash) modBits = Crypto.Util.number.size(self._key.n) # See 8.1.2 in RFC3447 k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 if len(S) != k: return False # Step 2a (O2SIP), 2b (RSAVP1), and partially 2c (I2OSP) # Note that signature must be smaller than the module # but RSA.py won't complain about it. # TODO: Fix RSA object; don't do it here. em = self._key.encrypt(S, 0)[0] # Step 2c emLen = ceil_div(modBits-1,8) em = bchr(0x00)*(emLen-len(em)) + em # Step 3 try: result = EMSA_PSS_VERIFY(mhash, em, modBits-1, mgf, sLen) except ValueError: return False # Step 4 return result def MGF1(mgfSeed, maskLen, hash): """Mask Generation Function, described in B.2.1""" T = b("") for counter in xrange(ceil_div(maskLen, hash.digest_size)): c = long_to_bytes(counter, 4) T = T + hash.new(mgfSeed + c).digest() assert(len(T)>=maskLen) return T[:maskLen] def EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen): """ Implement the ``EMSA-PSS-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.1). The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message being signed. emBits : int Maximum length of the final encoding, in bits. randFunc : callable An RNG function that accepts as only parameter an int, and returns a string of random bytes, to be used as salt. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Return: An ``emLen`` byte long string that encodes the hash (with ``emLen = \ceil(emBits/8)``). :Raise ValueError: When digest or salt length are too big. """ emLen = ceil_div(emBits,8) # Bitmask of digits that fill up lmask = 0 for i in xrange(8*emLen-emBits): lmask = lmask>>1 | 0x80 # Step 1 and 2 have been already done # Step 3 if emLen < mhash.digest_size+sLen+2: raise ValueError("Digest or salt length are too long for given key size.") # Step 4 salt = b("") if randFunc and sLen>0: salt = randFunc(sLen) # Step 5 and 6 h = mhash.new(bchr(0x00)*8 + mhash.digest() + salt) # Step 7 and 8 db = bchr(0x00)*(emLen-sLen-mhash.digest_size-2) + bchr(0x01) + salt # Step 9 dbMask = mgf(h.digest(), emLen-mhash.digest_size-1) # Step 10 maskedDB = strxor(db,dbMask) # Step 11 maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:] # Step 12 em = maskedDB + h.digest() + bchr(0xBC) return em def EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen): """ Implement the ``EMSA-PSS-VERIFY`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.1.2). ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: mhash : hash object The hash object that holds the digest of the message to be verified. em : string The signature to verify, therefore proving that the sender really signed the message that was received. emBits : int Length of the final encoding (em), in bits. mgf : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. sLen : int Length of the salt, in bytes. :Return: 0 if the encoding is consistent, 1 if it is inconsistent. :Raise ValueError: When digest or salt length are too big. """ emLen = ceil_div(emBits,8) # Bitmask of digits that fill up lmask = 0 for i in xrange(8*emLen-emBits): lmask = lmask>>1 | 0x80 # Step 1 and 2 have been already done # Step 3 if emLen < mhash.digest_size+sLen+2: return False # Step 4 if ord(em[-1:])!=0xBC: return False # Step 5 maskedDB = em[:emLen-mhash.digest_size-1] h = em[emLen-mhash.digest_size-1:-1] # Step 6 if lmask & bord(em[0]): return False # Step 7 dbMask = mgf(h, emLen-mhash.digest_size-1) # Step 8 db = strxor(maskedDB, dbMask) # Step 9 db = bchr(bord(db[0]) & ~lmask) + db[1:] # Step 10 if not db.startswith(bchr(0x00)*(emLen-mhash.digest_size-sLen-2) + bchr(0x01)): return False # Step 11 salt = b("") if sLen: salt = db[-sLen:] # Step 12 and 13 hp = mhash.new(bchr(0x00)*8 + mhash.digest() + salt).digest() # Step 14 if h!=hp: return False return True def new(key, mgfunc=None, saltLen=None): """Return a signature scheme object `PSS_SigScheme` that can be used to perform PKCS#1 PSS signature or verification. :Parameters: key : RSA key object The key to use to sign or verify the message. This is a `Crypto.PublicKey.RSA` object. Signing is only possible if *key* is a private RSA key. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 is used. saltLen : int Length of the salt, in bytes. If not specified, it matches the output size of the hash function. """ return PSS_SigScheme(key, mgfunc, saltLen)
mit
Cosiroc/bleau-database
django-application/BleauDatabaseDjangoSite/settings.py
2
10035
#################################################################################################### # # Bleau Database - A database of the bouldering area of Fontainebleau # Copyright (C) 2016 Fabrice Salvaire # # 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/>. # #################################################################################################### #################################################################################################### """Django settings for Bleau Database project. """ #################################################################################################### import os from django.conf import settings # from django_jinja.builtins import DEFAULT_EXTENSIONS #################################################################################################### # # Debug # # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #################################################################################################### # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #################################################################################################### ROOT_URLCONF = 'BleauDatabaseDjangoSite.urls' WSGI_APPLICATION = 'BleauDatabaseDjangoSite.wsgi.application' ALLOWED_HOSTS = ['bleaudb-admin.bleausard.fr', 'bleaudb-admin.bleausard.fr.'] # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')*#b)3xtlw5_zhy*$yuwg+o6q#hm&=2i&xfh^v^t#6b5jx!!(^' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] #################################################################################################### # # Database # DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'bleaudb', 'USER': 'bleaudb', 'PASSWORD': 'bleaudb', } } #################################################################################################### # # Application definition # INSTALLED_APPS = [ # /!\ ordered list # 'django.contrib.sites', 'suit', # before admin 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'rest_framework', 'rest_framework_swagger', 'reversion', 'django_jinja', # to complete Jinja2 backend 'django_jinja.contrib._humanize', 'BleauDatabaseDjangoApplication', ] MIDDLEWARE_CLASSES = [ # /!\ ordered list 'reversion.middleware.RevisionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # to setup translation 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', # for CSRF protection 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # for messaging 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #################################################################################################### # # Template # TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", # 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'APP_DIRS': True, # looks for app/jinja2 # 'DIRS': [ # os.path.join(BASE_DIR, 'BleauDatabaseDjangoApplication', 'jinja2'), # ], 'OPTIONS': { # 'environment': 'BleauDatabaseDjangoApplication.jinja2.environment', # for standard backend "app_dirname": "jinja2", "match_extension": ".html", # "match_extension": ".jinja", "newstyle_gettext": True, "context_processors": [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # "django.template.context_processors.i18n", # "django.template.context_processors.media", # "django.template.context_processors.static", # "django.template.context_processors.tz", ], # "extensions": DEFAULT_EXTENSIONS + [ "extensions": [ "jinja2.ext.do", "jinja2.ext.loopcontrols", "jinja2.ext.with_", "jinja2.ext.i18n", "jinja2.ext.autoescape", "django_jinja.builtins.extensions.CsrfExtension", "django_jinja.builtins.extensions.CacheExtension", "django_jinja.builtins.extensions.TimezoneExtension", "django_jinja.builtins.extensions.UrlsExtension", "django_jinja.builtins.extensions.StaticFilesExtension", "django_jinja.builtins.extensions.DjangoFiltersExtension", ], "bytecode_cache": { "name": "default", "backend": "django_jinja.cache.BytecodeCache", "enabled": False, }, "autoescape": True, "auto_reload": settings.DEBUG, "translation_engine": "django.utils.translation", }, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] #################################################################################################### # # Password validation # AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #################################################################################################### # # Internationalization # LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True #################################################################################################### # # LOGIN URLs # # LOGIN_REDIRECT_URL = 'accounts.profile' LOGIN_REDIRECT_URL = 'index' LOGIN_URL = 'accounts.login' LOGOUT_URL = 'accounts.logout' #################################################################################################### # # Django Suit configuration # SUIT_CONFIG = { # header 'ADMIN_NAME': 'Bleau DB', 'HEADER_DATE_FORMAT': 'l, j F Y', 'HEADER_TIME_FORMAT': 'H:i', # forms 'SHOW_REQUIRED_ASTERISK': True, 'CONFIRM_UNSAVED_CHANGES': True, # 'MENU': ( # 'sites', # {'app': 'auth', 'models': ('user', 'group')}, # {'label': 'Bleau DB', # 'app': 'BleauDatabaseDjangoApplication', # 'models': ('circuit',), # }, # ), 'LIST_PER_PAGE': 15 } #################################################################################################### # # REST Framework # REST_FRAMEWORK = { # http://www.django-rest-framework.org/api-guide/permissions/ # IsAdminUser 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticatedOrReadOnly',), 'PAGE_SIZE': 100, } SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_key': '', 'api_version': '1.0', # 'api_path': '/', # 'base_path': '', 'doc_expansion': 'none', 'enabled_methods': [ 'get', 'post', 'put', 'patch', 'delete' ], 'info': { 'title': 'Bleau Database REST API', 'description': ''' This page provides an automatically generated documentation for the <a href="/about-rest-api">Bleau Database REST API</a>. You can learn the data schemas and try it out. Data are licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">CC BY-NC-SA 3.0.</a> ''', # 'contact': 'fabrice.salvaire@orange.fr', # 'license': 'CC BY-NC-SA 3.0', # 'licenseUrl': 'http://creativecommons.org/licenses/by-nc-sa/3.0/', # 'termsOfServiceUrl': '/mentions-legales', }, 'is_authenticated': False, 'is_superuser': False, 'permission_denied_handler': None, 'resource_access_handler': None, # 'token_type': Token, } #################################################################################################### # # Email # # Log to console EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
agpl-3.0
amitay/samba
source4/scripting/python/samba/tests/dcerpc/rpc_talloc.py
20
2841
# test generated python code from pidl # Copyright (C) Andrew Tridgell August 2010 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # to run this test, use one of these: # # python -m testtools.run samba.tests.dcerpc.rpc_talloc # # or if you have trial installed (from twisted), use # # trial samba.tests.dcerpc.rpc_talloc """Tests for the talloc handling in the generated Python DCE/RPC bindings.""" import sys sys.path.insert(0, "bin/python") import samba import samba.tests from samba.dcerpc import drsuapi import talloc talloc.enable_null_tracking() class TallocTests(samba.tests.TestCase): '''test talloc behaviour of pidl generated python code''' def check_blocks(self, object, num_expected): '''check that the number of allocated blocks is correct''' nblocks = talloc.total_blocks(object) if object is None: nblocks -= self.initial_blocks self.assertEquals(nblocks, num_expected) def get_rodc_partial_attribute_set(self): '''get a list of attributes for RODC replication''' partial_attribute_set = drsuapi.DsPartialAttributeSet() # we expect one block for the object, and one for the structure self.check_blocks(partial_attribute_set, 2) attids = [1, 2, 3] partial_attribute_set.version = 1 partial_attribute_set.attids = attids partial_attribute_set.num_attids = len(attids) # we expect one block object, a structure, an ARRAY, and a # reference to the array self.check_blocks(partial_attribute_set, 3) return partial_attribute_set def pas_test(self): pas = self.get_rodc_partial_attribute_set() self.check_blocks(pas, 3) req8 = drsuapi.DsGetNCChangesRequest8() self.check_blocks(req8, 2) self.check_blocks(None, 5) req8.partial_attribute_set = pas if req8.partial_attribute_set.attids[1] != 2: raise Exception("Wrong value in attids[2]") # we now get an additional reference self.check_blocks(None, 6) def test_run(self): self.initial_blocks = talloc.total_blocks(None) self.check_blocks(None, 0) self.pas_test() self.check_blocks(None, 0)
gpl-3.0
redomino/redomino.appytransforms
redomino/appytransforms/tests/test_portal.py
1
1719
# coding=utf-8 import unittest2 as unittest from redomino.appytransforms.testing import REDOMINO_ODTTRANSFORMS_INTEGRATION_TESTING class TestPortal(unittest.TestCase): layer = REDOMINO_ODTTRANSFORMS_INTEGRATION_TESTING def test_portal_transforms(self): """ portal transforms correctly registered? """ from Products.PortalTransforms.interfaces import IPortalTransformsTool from zope.component import getUtility portal_transforms = getUtility(IPortalTransformsTool) self.assertTrue('odt_transform' in portal_transforms.objectIds()) def test_mimetype(self): """ custom mimetype registered? """ from zope.component import getUtility from Products.MimetypesRegistry.interfaces import IMimetypesRegistryTool mimetypes_registry = getUtility(IMimetypesRegistryTool) self.assertEquals(1, len(mimetypes_registry.lookup('application/vnd.oasis.opendocument.text.transformed'))) def test_portal_transforms_ods(self): """ portal transforms correctly registered? """ from Products.PortalTransforms.interfaces import IPortalTransformsTool from zope.component import getUtility portal_transforms = getUtility(IPortalTransformsTool) self.assertTrue('ods_transform' in portal_transforms.objectIds()) def test_mimetype_ods(self): """ custom mimetype registered? """ from zope.component import getUtility from Products.MimetypesRegistry.interfaces import IMimetypesRegistryTool mimetypes_registry = getUtility(IMimetypesRegistryTool) self.assertEquals(1, len(mimetypes_registry.lookup('application/vnd.oasis.opendocument.spreadsheet.transformed')))
gpl-2.0
brandond/ansible
lib/ansible/modules/packaging/os/swupd.py
31
8748
#!/usr/bin/python # (c) 2017, Alberto Murillo <alberto.murillo.silva@intel.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: swupd short_description: Manages updates and bundles in ClearLinux systems. description: - Manages updates and bundles with the swupd bundle manager, which is used by the Clear Linux Project for Intel Architecture. version_added: "2.3" author: Alberto Murillo (@albertomurillo) options: contenturl: description: - URL pointing to the contents of available bundles. If not specified, the contents are retrieved from clearlinux.org. format: description: - The format suffix for version file downloads. For example [1,2,3,staging,etc]. If not specified, the default format is used. manifest: description: - The manifest contains information about the bundles at certaion version of the OS. Specify a Manifest version to verify against that version or leave unspecified to verify against the current version. aliases: [release, version] name: description: - Name of the (I)bundle to install or remove. aliases: [bundle] state: description: - Indicates the desired (I)bundle state. C(present) ensures the bundle is installed while C(absent) ensures the (I)bundle is not installed. default: present choices: [present, absent] update: description: - Updates the OS to the latest version. type: bool url: description: - Overrides both I(contenturl) and I(versionurl). verify: description: - Verify content for OS version. type: bool versionurl: description: - URL for version string download. ''' EXAMPLES = ''' - name: Update the OS to the latest version swupd: update: yes - name: Installs the "foo" bundle swupd: name: foo state: present - name: Removes the "foo" bundle swupd: name: foo state: absent - name: Check integrity of filesystem swupd: verify: yes - name: Downgrade OS to release 12920 swupd: verify: yes manifest: 12920 ''' RETURN = ''' stdout: description: stdout of swupd returned: always type: str stderr: description: stderr of swupd returned: always type: str ''' import os from ansible.module_utils.basic import AnsibleModule class Swupd(object): FILES_NOT_MATCH = "files did not match" FILES_REPLACED = "missing files were replaced" FILES_FIXED = "files were fixed" FILES_DELETED = "files were deleted" def __init__(self, module): # Fail if swupd is not found self.module = module self.swupd_cmd = module.get_bin_path("swupd", False) if not self.swupd_cmd: module.fail_json(msg="Could not find swupd.") # Initialize parameters for key in module.params.keys(): setattr(self, key, module.params[key]) # Initialize return values self.changed = False self.failed = False self.msg = None self.rc = None self.stderr = "" self.stdout = "" def _run_cmd(self, cmd): self.rc, self.stdout, self.stderr = self.module.run_command(cmd, check_rc=False) def _get_cmd(self, command): cmd = "%s %s" % (self.swupd_cmd, command) if self.format: cmd += " --format=%s" % self.format if self.manifest: cmd += " --manifest=%s" % self.manifest if self.url: cmd += " --url=%s" % self.url else: if self.contenturl and command != "check-update": cmd += " --contenturl=%s" % self.contenturl if self.versionurl: cmd += " --versionurl=%s" % self.versionurl return cmd def _is_bundle_installed(self, bundle): try: os.stat("/usr/share/clear/bundles/%s" % bundle) except OSError: return False return True def _needs_update(self): cmd = self._get_cmd("check-update") self._run_cmd(cmd) if self.rc == 0: return True if self.rc == 1: return False self.failed = True self.msg = "Failed to check for updates" def _needs_verify(self): cmd = self._get_cmd("verify") self._run_cmd(cmd) if self.rc != 0: self.failed = True self.msg = "Failed to check for filesystem inconsistencies." if self.FILES_NOT_MATCH in self.stdout: return True return False def install_bundle(self, bundle): """Installs a bundle with `swupd bundle-add bundle`""" if self.module.check_mode: self.module.exit_json(changed=not self._is_bundle_installed(bundle)) if self._is_bundle_installed(bundle): self.msg = "Bundle %s is already installed" % bundle return cmd = self._get_cmd("bundle-add %s" % bundle) self._run_cmd(cmd) if self.rc == 0: self.changed = True self.msg = "Bundle %s installed" % bundle return self.failed = True self.msg = "Failed to install bundle %s" % bundle def remove_bundle(self, bundle): """Removes a bundle with `swupd bundle-remove bundle`""" if self.module.check_mode: self.module.exit_json(changed=self._is_bundle_installed(bundle)) if not self._is_bundle_installed(bundle): self.msg = "Bundle %s not installed" return cmd = self._get_cmd("bundle-remove %s" % bundle) self._run_cmd(cmd) if self.rc == 0: self.changed = True self.msg = "Bundle %s removed" % bundle return self.failed = True self.msg = "Failed to remove bundle %s" % bundle def update_os(self): """Updates the os with `swupd update`""" if self.module.check_mode: self.module.exit_json(changed=self._needs_update()) if not self._needs_update(): self.msg = "There are no updates available" return cmd = self._get_cmd("update") self._run_cmd(cmd) if self.rc == 0: self.changed = True self.msg = "Update successful" return self.failed = True self.msg = "Failed to check for updates" def verify_os(self): """Verifies filesystem against specified or current version""" if self.module.check_mode: self.module.exit_json(changed=self._needs_verify()) if not self._needs_verify(): self.msg = "No files where changed" return cmd = self._get_cmd("verify --fix") self._run_cmd(cmd) if self.rc == 0 and (self.FILES_REPLACED in self.stdout or self.FILES_FIXED in self.stdout or self.FILES_DELETED in self.stdout): self.changed = True self.msg = "Fix successful" return self.failed = True self.msg = "Failed to verify the OS" def main(): """The main function.""" module = AnsibleModule( argument_spec=dict( contenturl=dict(type="str"), format=dict(type="str"), manifest=dict(aliases=["release", "version"], type="int"), name=dict(aliases=["bundle"], type="str"), state=dict(default="present", choices=["present", "absent"], type="str"), update=dict(default=False, type="bool"), url=dict(type="str"), verify=dict(default=False, type="bool"), versionurl=dict(type="str"), ), required_one_of=[["name", "update", "verify"]], mutually_exclusive=[["name", "update", "verify"]], supports_check_mode=True ) swupd = Swupd(module) name = module.params["name"] state = module.params["state"] update = module.params["update"] verify = module.params["verify"] if update: swupd.update_os() elif verify: swupd.verify_os() elif state == "present": swupd.install_bundle(name) elif state == "absent": swupd.remove_bundle(name) else: swupd.failed = True if swupd.failed: module.fail_json(msg=swupd.msg, stdout=swupd.stdout, stderr=swupd.stderr) else: module.exit_json(changed=swupd.changed, msg=swupd.msg, stdout=swupd.stdout, stderr=swupd.stderr) if __name__ == '__main__': main()
gpl-3.0
detrout/debian-statsmodels
statsmodels/sandbox/distributions/sppatch.py
33
23649
'''patching scipy to fit distributions and expect method This adds new methods to estimate continuous distribution parameters with some fixed/frozen parameters. It also contains functions that calculate the expected value of a function for any continuous or discrete distribution It temporarily also contains Bootstrap and Monte Carlo function for testing the distribution fit, but these are neither general nor verified. Author: josef-pktd License: Simplified BSD ''' from __future__ import print_function from statsmodels.compat.python import range, lmap import numpy as np from scipy import stats, optimize, integrate ########## patching scipy #vonmises doesn't define finite bounds, because it is intended for circular #support which does not define a proper pdf on the real line stats.distributions.vonmises.a = -np.pi stats.distributions.vonmises.b = np.pi #the next 3 functions are for fit with some fixed parameters #As they are written, they do not work as functions, only as methods def _fitstart(self, x): '''example method, method of moment estimator as starting values Parameters ---------- x : array data for which the parameters are estimated Returns ------- est : tuple preliminary estimates used as starting value for fitting, not necessarily a consistent estimator Notes ----- This needs to be written and attached to each individual distribution This example was written for the gamma distribution, but not verified with literature ''' loc = np.min([x.min(),0]) a = 4/stats.skew(x)**2 scale = np.std(x) / np.sqrt(a) return (a, loc, scale) def _fitstart_beta(self, x, fixed=None): '''method of moment estimator as starting values for beta distribution Parameters ---------- x : array data for which the parameters are estimated fixed : None or array_like sequence of numbers and np.nan to indicate fixed parameters and parameters to estimate Returns ------- est : tuple preliminary estimates used as starting value for fitting, not necessarily a consistent estimator Notes ----- This needs to be written and attached to each individual distribution References ---------- for method of moment estimator for known loc and scale http://en.wikipedia.org/wiki/Beta_distribution#Parameter_estimation http://www.itl.nist.gov/div898/handbook/eda/section3/eda366h.htm NIST reference also includes reference to MLE in Johnson, Kotz, and Balakrishan, Volume II, pages 221-235 ''' #todo: separate out this part to be used for other compact support distributions # e.g. rdist, vonmises, and truncnorm # but this might not work because it might still be distribution specific a, b = x.min(), x.max() eps = (a-b)*0.01 if fixed is None: #this part not checked with books loc = a - eps scale = (a - b) * (1 + 2*eps) else: if np.isnan(fixed[-2]): #estimate loc loc = a - eps else: loc = fixed[-2] if np.isnan(fixed[-1]): #estimate scale scale = (b + eps) - loc else: scale = fixed[-1] #method of moment for known loc scale: scale = float(scale) xtrans = (x - loc)/scale xm = xtrans.mean() xv = xtrans.var() tmp = (xm*(1-xm)/xv - 1) p = xm * tmp q = (1 - xm) * tmp return (p, q, loc, scale) #check return type and should fixed be returned ? def _fitstart_poisson(self, x, fixed=None): '''maximum likelihood estimator as starting values for Poisson distribution Parameters ---------- x : array data for which the parameters are estimated fixed : None or array_like sequence of numbers and np.nan to indicate fixed parameters and parameters to estimate Returns ------- est : tuple preliminary estimates used as starting value for fitting, not necessarily a consistent estimator Notes ----- This needs to be written and attached to each individual distribution References ---------- MLE : http://en.wikipedia.org/wiki/Poisson_distribution#Maximum_likelihood ''' #todo: separate out this part to be used for other compact support distributions # e.g. rdist, vonmises, and truncnorm # but this might not work because it might still be distribution specific a = x.min() eps = 0 # is this robust ? if fixed is None: #this part not checked with books loc = a - eps else: if np.isnan(fixed[-1]): #estimate loc loc = a - eps else: loc = fixed[-1] #MLE for standard (unshifted, if loc=0) Poisson distribution xtrans = (x - loc) lambd = xtrans.mean() #second derivative d loglike/ dlambd Not used #dlldlambd = 1/lambd # check return (lambd, loc) #check return type and should fixed be returned ? def nnlf_fr(self, thetash, x, frmask): # new frozen version # - sum (log pdf(x, theta),axis=0) # where theta are the parameters (including loc and scale) # try: if frmask != None: theta = frmask.copy() theta[np.isnan(frmask)] = thetash else: theta = thetash loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) except IndexError: raise ValueError("Not enough input arguments.") if not self._argcheck(*args) or scale <= 0: return np.inf x = np.array((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (np.any(cond0)): return np.inf else: N = len(x) #raise ValueError return self._nnlf(x, *args) + N*np.log(scale) def fit_fr(self, data, *args, **kwds): '''estimate distribution parameters by MLE taking some parameters as fixed Parameters ---------- data : array, 1d data for which the distribution parameters are estimated, args : list ? check starting values for optimization kwds : - 'frozen' : array_like values for frozen distribution parameters and, for elements with np.nan, the corresponding parameter will be estimated Returns ------- argest : array estimated parameters Examples -------- generate random sample >>> np.random.seed(12345) >>> x = stats.gamma.rvs(2.5, loc=0, scale=1.2, size=200) estimate all parameters >>> stats.gamma.fit(x) array([ 2.0243194 , 0.20395655, 1.44411371]) >>> stats.gamma.fit_fr(x, frozen=[np.nan, np.nan, np.nan]) array([ 2.0243194 , 0.20395655, 1.44411371]) keep loc fixed, estimate shape and scale parameters >>> stats.gamma.fit_fr(x, frozen=[np.nan, 0.0, np.nan]) array([ 2.45603985, 1.27333105]) keep loc and scale fixed, estimate shape parameter >>> stats.gamma.fit_fr(x, frozen=[np.nan, 0.0, 1.0]) array([ 3.00048828]) >>> stats.gamma.fit_fr(x, frozen=[np.nan, 0.0, 1.2]) array([ 2.57792969]) estimate only scale parameter for fixed shape and loc >>> stats.gamma.fit_fr(x, frozen=[2.5, 0.0, np.nan]) array([ 1.25087891]) Notes ----- self is an instance of a distribution class. This can be attached to scipy.stats.distributions.rv_continuous *Todo* * check if docstring is correct * more input checking, args is list ? might also apply to current fit method ''' loc0, scale0 = lmap(kwds.get, ['loc', 'scale'],[0.0, 1.0]) Narg = len(args) if Narg == 0 and hasattr(self, '_fitstart'): x0 = self._fitstart(data) elif Narg > self.numargs: raise ValueError("Too many input arguments.") else: args += (1.0,)*(self.numargs-Narg) # location and scale are at the end x0 = args + (loc0, scale0) if 'frozen' in kwds: frmask = np.array(kwds['frozen']) if len(frmask) != self.numargs+2: raise ValueError("Incorrect number of frozen arguments.") else: # keep starting values for not frozen parameters x0 = np.array(x0)[np.isnan(frmask)] else: frmask = None #print(x0 #print(frmask return optimize.fmin(self.nnlf_fr, x0, args=(np.ravel(data), frmask), disp=0) #The next two functions/methods calculate expected value of an arbitrary #function, however for the continuous functions intquad is use, which might #require continuouity or smoothness in the function. #TODO: add option for Monte Carlo integration def expect(self, fn=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False): '''calculate expected value of a function with respect to the distribution location and scale only tested on a few examples Parameters ---------- all parameters are keyword parameters fn : function (default: identity mapping) Function for which integral is calculated. Takes only one argument. args : tuple argument (parameters) of the distribution lb, ub : numbers lower and upper bound for integration, default is set to the support of the distribution conditional : boolean (False) If true then the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Returns ------- expected value : float Notes ----- This function has not been checked for it's behavior when the integral is not finite. The integration behavior is inherited from scipy.integrate.quad. ''' if fn is None: def fun(x, *args): return x*self.pdf(x, loc=loc, scale=scale, *args) else: def fun(x, *args): return fn(x)*self.pdf(x, loc=loc, scale=scale, *args) if lb is None: lb = loc + self.a * scale #(self.a - loc)/(1.0*scale) if ub is None: ub = loc + self.b * scale #(self.b - loc)/(1.0*scale) if conditional: invfac = (self.sf(lb, loc=loc, scale=scale, *args) - self.sf(ub, loc=loc, scale=scale, *args)) else: invfac = 1.0 return integrate.quad(fun, lb, ub, args=args)[0]/invfac def expect_v2(self, fn=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False): '''calculate expected value of a function with respect to the distribution location and scale only tested on a few examples Parameters ---------- all parameters are keyword parameters fn : function (default: identity mapping) Function for which integral is calculated. Takes only one argument. args : tuple argument (parameters) of the distribution lb, ub : numbers lower and upper bound for integration, default is set using quantiles of the distribution, see Notes conditional : boolean (False) If true then the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Returns ------- expected value : float Notes ----- This function has not been checked for it's behavior when the integral is not finite. The integration behavior is inherited from scipy.integrate.quad. The default limits are lb = self.ppf(1e-9, *args), ub = self.ppf(1-1e-9, *args) For some heavy tailed distributions, 'alpha', 'cauchy', 'halfcauchy', 'levy', 'levy_l', and for 'ncf', the default limits are not set correctly even when the expectation of the function is finite. In this case, the integration limits, lb and ub, should be chosen by the user. For example, for the ncf distribution, ub=1000 works in the examples. There are also problems with numerical integration in some other cases, for example if the distribution is very concentrated and the default limits are too large. ''' #changes: 20100809 #correction and refactoring how loc and scale are handled #uses now _pdf #needs more testing for distribution with bound support, e.g. genpareto if fn is None: def fun(x, *args): return (loc + x*scale)*self._pdf(x, *args) else: def fun(x, *args): return fn(loc + x*scale)*self._pdf(x, *args) if lb is None: #lb = self.a try: lb = self.ppf(1e-9, *args) #1e-14 quad fails for pareto except ValueError: lb = self.a else: lb = max(self.a, (lb - loc)/(1.0*scale)) #transform to standardized if ub is None: #ub = self.b try: ub = self.ppf(1-1e-9, *args) except ValueError: ub = self.b else: ub = min(self.b, (ub - loc)/(1.0*scale)) if conditional: invfac = self._sf(lb,*args) - self._sf(ub,*args) else: invfac = 1.0 return integrate.quad(fun, lb, ub, args=args, limit=500)[0]/invfac ### for discrete distributions #TODO: check that for a distribution with finite support the calculations are # done with one array summation (np.dot) #based on _drv2_moment(self, n, *args), but streamlined def expect_discrete(self, fn=None, args=(), loc=0, lb=None, ub=None, conditional=False): '''calculate expected value of a function with respect to the distribution for discrete distribution Parameters ---------- (self : distribution instance as defined in scipy stats) fn : function (default: identity mapping) Function for which integral is calculated. Takes only one argument. args : tuple argument (parameters) of the distribution optional keyword parameters lb, ub : numbers lower and upper bound for integration, default is set to the support of the distribution, lb and ub are inclusive (ul<=k<=ub) conditional : boolean (False) If true then the expectation is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval (k such that ul<=k<=ub). Returns ------- expected value : float Notes ----- * function is not vectorized * accuracy: uses self.moment_tol as stopping criterium for heavy tailed distribution e.g. zipf(4), accuracy for mean, variance in example is only 1e-5, increasing precision (moment_tol) makes zipf very slow * suppnmin=100 internal parameter for minimum number of points to evaluate could be added as keyword parameter, to evaluate functions with non-monotonic shapes, points include integers in (-suppnmin, suppnmin) * uses maxcount=1000 limits the number of points that are evaluated to break loop for infinite sums (a maximum of suppnmin+1000 positive plus suppnmin+1000 negative integers are evaluated) ''' #moment_tol = 1e-12 # increase compared to self.moment_tol, # too slow for only small gain in precision for zipf #avoid endless loop with unbound integral, eg. var of zipf(2) maxcount = 1000 suppnmin = 100 #minimum number of points to evaluate (+ and -) if fn is None: def fun(x): #loc and args from outer scope return (x+loc)*self._pmf(x, *args) else: def fun(x): #loc and args from outer scope return fn(x+loc)*self._pmf(x, *args) # used pmf because _pmf does not check support in randint # and there might be problems(?) with correct self.a, self.b at this stage # maybe not anymore, seems to work now with _pmf self._argcheck(*args) # (re)generate scalar self.a and self.b if lb is None: lb = (self.a) else: lb = lb - loc if ub is None: ub = (self.b) else: ub = ub - loc if conditional: invfac = self.sf(lb,*args) - self.sf(ub+1,*args) else: invfac = 1.0 tot = 0.0 low, upp = self._ppf(0.001, *args), self._ppf(0.999, *args) low = max(min(-suppnmin, low), lb) upp = min(max(suppnmin, upp), ub) supp = np.arange(low, upp+1, self.inc) #check limits #print('low, upp', low, upp tot = np.sum(fun(supp)) diff = 1e100 pos = upp + self.inc count = 0 #handle cases with infinite support while (pos <= ub) and (diff > self.moment_tol) and count <= maxcount: diff = fun(pos) tot += diff pos += self.inc count += 1 if self.a < 0: #handle case when self.a = -inf diff = 1e100 pos = low - self.inc while (pos >= lb) and (diff > self.moment_tol) and count <= maxcount: diff = fun(pos) tot += diff pos -= self.inc count += 1 if count > maxcount: # replace with proper warning print('sum did not converge') return tot/invfac stats.distributions.rv_continuous.fit_fr = fit_fr stats.distributions.rv_continuous.nnlf_fr = nnlf_fr stats.distributions.rv_continuous.expect = expect stats.distributions.rv_discrete.expect = expect_discrete stats.distributions.beta_gen._fitstart = _fitstart_beta #not tried out yet stats.distributions.poisson_gen._fitstart = _fitstart_poisson #not tried out yet ########## end patching scipy def distfitbootstrap(sample, distr, nrepl=100): '''run bootstrap for estimation of distribution parameters hard coded: only one shape parameter is allowed and estimated, loc=0 and scale=1 are fixed in the estimation Parameters ---------- sample : array original sample data for bootstrap distr : distribution instance with fit_fr method nrepl : integer number of bootstrap replications Returns ------- res : array (nrepl,) parameter estimates for all bootstrap replications ''' nobs = len(sample) res = np.zeros(nrepl) for ii in range(nrepl): rvsind = np.random.randint(nobs, size=nobs) x = sample[rvsind] res[ii] = distr.fit_fr(x, frozen=[np.nan, 0.0, 1.0]) return res def distfitmc(sample, distr, nrepl=100, distkwds={}): '''run Monte Carlo for estimation of distribution parameters hard coded: only one shape parameter is allowed and estimated, loc=0 and scale=1 are fixed in the estimation Parameters ---------- sample : array original sample data, in Monte Carlo only used to get nobs, distr : distribution instance with fit_fr method nrepl : integer number of Monte Carlo replications Returns ------- res : array (nrepl,) parameter estimates for all Monte Carlo replications ''' arg = distkwds.pop('arg') nobs = len(sample) res = np.zeros(nrepl) for ii in range(nrepl): x = distr.rvs(arg, size=nobs, **distkwds) res[ii] = distr.fit_fr(x, frozen=[np.nan, 0.0, 1.0]) return res def printresults(sample, arg, bres, kind='bootstrap'): '''calculate and print(Bootstrap or Monte Carlo result Parameters ---------- sample : array original sample data arg : float (for general case will be array) bres : array parameter estimates from Bootstrap or Monte Carlo run kind : {'bootstrap', 'montecarlo'} output is printed for Mootstrap (default) or Monte Carlo Returns ------- None, currently only printing Notes ----- still a bit a mess because it is used for both Bootstrap and Monte Carlo made correction: reference point for bootstrap is estimated parameter not clear: I'm not doing any ddof adjustment in estimation of variance, do we need ddof>0 ? todo: return results and string instead of printing ''' print('true parameter value') print(arg) print('MLE estimate of parameters using sample (nobs=%d)'% (nobs)) argest = distr.fit_fr(sample, frozen=[np.nan, 0.0, 1.0]) print(argest) if kind == 'bootstrap': #bootstrap compares to estimate from sample argorig = arg arg = argest print('%s distribution of parameter estimate (nrepl=%d)'% (kind, nrepl)) print('mean = %f, bias=%f' % (bres.mean(0), bres.mean(0)-arg)) print('median', np.median(bres, axis=0)) print('var and std', bres.var(0), np.sqrt(bres.var(0))) bmse = ((bres - arg)**2).mean(0) print('mse, rmse', bmse, np.sqrt(bmse)) bressorted = np.sort(bres) print('%s confidence interval (90%% coverage)' % kind) print(bressorted[np.floor(nrepl*0.05)], bressorted[np.floor(nrepl*0.95)]) print('%s confidence interval (90%% coverage) normal approximation' % kind) print(stats.norm.ppf(0.05, loc=bres.mean(), scale=bres.std()),) print(stats.norm.isf(0.05, loc=bres.mean(), scale=bres.std())) print('Kolmogorov-Smirnov test for normality of %s distribution' % kind) print(' - estimated parameters, p-values not really correct') print(stats.kstest(bres, 'norm', (bres.mean(), bres.std()))) if __name__ == '__main__': examplecases = ['largenumber', 'bootstrap', 'montecarlo'][:] if 'largenumber' in examplecases: print('\nDistribution: vonmises') for nobs in [200]:#[20000, 1000, 100]: x = stats.vonmises.rvs(1.23, loc=0, scale=1, size=nobs) print('\nnobs:', nobs) print('true parameter') print('1.23, loc=0, scale=1') print('unconstraint') print(stats.vonmises.fit(x)) print(stats.vonmises.fit_fr(x, frozen=[np.nan, np.nan, np.nan])) print('with fixed loc and scale') print(stats.vonmises.fit_fr(x, frozen=[np.nan, 0.0, 1.0])) print('\nDistribution: gamma') distr = stats.gamma arg, loc, scale = 2.5, 0., 20. for nobs in [200]:#[20000, 1000, 100]: x = distr.rvs(arg, loc=loc, scale=scale, size=nobs) print('\nnobs:', nobs) print('true parameter') print('%f, loc=%f, scale=%f' % (arg, loc, scale)) print('unconstraint') print(distr.fit(x)) print(distr.fit_fr(x, frozen=[np.nan, np.nan, np.nan])) print('with fixed loc and scale') print(distr.fit_fr(x, frozen=[np.nan, 0.0, 1.0])) print('with fixed loc') print(distr.fit_fr(x, frozen=[np.nan, 0.0, np.nan])) ex = ['gamma', 'vonmises'][0] if ex == 'gamma': distr = stats.gamma arg, loc, scale = 2.5, 0., 1 elif ex == 'vonmises': distr = stats.vonmises arg, loc, scale = 1.5, 0., 1 else: raise ValueError('wrong example') nobs = 100 nrepl = 1000 sample = distr.rvs(arg, loc=loc, scale=scale, size=nobs) print('\nDistribution:', distr) if 'bootstrap' in examplecases: print('\nBootstrap') bres = distfitbootstrap(sample, distr, nrepl=nrepl ) printresults(sample, arg, bres) if 'montecarlo' in examplecases: print('\nMonteCarlo') mcres = distfitmc(sample, distr, nrepl=nrepl, distkwds=dict(arg=arg, loc=loc, scale=scale)) printresults(sample, arg, mcres, kind='montecarlo')
bsd-3-clause
ojengwa/odoo
addons/portal_project_issue/tests/test_access_rights.py
338
10547
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2013-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.addons.portal_project.tests.test_access_rights import TestPortalProjectBase from openerp.exceptions import AccessError from openerp.osv.orm import except_orm from openerp.tools import mute_logger class TestPortalProjectBase(TestPortalProjectBase): def setUp(self): super(TestPortalProjectBase, self).setUp() cr, uid = self.cr, self.uid # Useful models self.project_issue = self.registry('project.issue') # Various test issues self.issue_1_id = self.project_issue.create(cr, uid, { 'name': 'Test1', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_2_id = self.project_issue.create(cr, uid, { 'name': 'Test2', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_3_id = self.project_issue.create(cr, uid, { 'name': 'Test3', 'user_id': False, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_4_id = self.project_issue.create(cr, uid, { 'name': 'Test4', 'user_id': self.user_projectuser_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_5_id = self.project_issue.create(cr, uid, { 'name': 'Test5', 'user_id': self.user_portal_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) self.issue_6_id = self.project_issue.create(cr, uid, { 'name': 'Test6', 'user_id': self.user_public_id, 'project_id': self.project_pigs_id}, {'mail_create_nolog': True}) class TestPortalIssue(TestPortalProjectBase): @mute_logger('openerp.addons.base.ir.ir_model', 'openerp.models') def test_00_project_access_rights(self): """ Test basic project access rights, for project and portal_project """ cr, uid, pigs_id = self.cr, self.uid, self.project_pigs_id # ---------------------------------------- # CASE1: public project # ---------------------------------------- # Do: Alfred reads project -> ok (employee ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # Test: all project issues readable self.project_issue.read(cr, self.user_projectuser_id, issue_ids, ['name']) # Test: all project issues writable self.project_issue.write(cr, self.user_projectuser_id, issue_ids, {'description': 'TestDescription'}) # Do: Bert reads project -> crash, no group # Test: no project issue visible self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)]) # Test: no project issue readable self.assertRaises(AccessError, self.project_issue.read, cr, self.user_none_id, issue_ids, ['name']) # Test: no project issue writable self.assertRaises(AccessError, self.project_issue.write, cr, self.user_none_id, issue_ids, {'description': 'TestDescription'}) # Do: Chell reads project -> ok (portal ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # Test: all project issues readable self.project_issue.read(cr, self.user_portal_id, issue_ids, ['name']) # Test: no project issue writable self.assertRaises(AccessError, self.project_issue.write, cr, self.user_portal_id, issue_ids, {'description': 'TestDescription'}) # Do: Donovan reads project -> ok (public ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_public_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a public project') # ---------------------------------------- # CASE2: portal project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'portal'}) # Do: Alfred reads project -> ok (employee ok public) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of a portal project') # Do: Bert reads project -> crash, no group # Test: no project issue searchable self.assertRaises(AccessError, self.project_issue.search, cr, self.user_none_id, [('project_id', '=', pigs_id)]) # Data: issue follower self.project_issue.message_subscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id]) # Do: Chell reads project -> ok (portal ok public) # Test: only followed project issues visible + assigned issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: portal user should see the followed issues of a portal project') # Data: issue follower cleaning self.project_issue.message_unsubscribe_users(cr, self.user_projectuser_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id]) # ---------------------------------------- # CASE3: employee project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'employees'}) # Do: Alfred reads project -> ok (employee ok employee) # Test: all project issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: project user cannot see all issues of an employees project') # Do: Chell reads project -> ko (portal ko employee) # Test: no project issue visible + assigned issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) self.assertFalse(issue_ids, 'access rights: portal user should not see issues of an employees project, even if assigned') # ---------------------------------------- # CASE4: followers project # ---------------------------------------- self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'followers'}) # Do: Alfred reads project -> ko (employee ko followers) # Test: no project issue visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_4_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see issues of a not-followed followers project, only assigned') # Do: Chell reads project -> ko (portal ko employee) # Test: no project issue visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: portal user should not see issues of a not-followed followers project, only assigned') # Data: subscribe Alfred, Chell and Donovan as follower self.project_project.message_subscribe_users(cr, uid, [pigs_id], [self.user_projectuser_id, self.user_portal_id, self.user_public_id]) self.project_issue.message_subscribe_users(cr, self.user_manager_id, [self.issue_1_id, self.issue_3_id], [self.user_portal_id, self.user_projectuser_id]) # Do: Alfred reads project -> ok (follower ok followers) # Test: followed + assigned issues visible issue_ids = self.project_issue.search(cr, self.user_projectuser_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_4_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see followed + assigned issues of a follower project') # Do: Chell reads project -> ok (follower ok follower) # Test: followed + assigned issues visible issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)]) test_issue_ids = set([self.issue_1_id, self.issue_3_id, self.issue_5_id]) self.assertEqual(set(issue_ids), test_issue_ids, 'access rights: employee user should not see followed + assigned issues of a follower project')
agpl-3.0
chechunli/googletest
test/gtest_help_test.py
2968
5856
#!/usr/bin/env python # # Copyright 2009, 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. """Tests the --help flag of Google C++ Testing Framework. SYNOPSIS gtest_help_test.py --build_dir=BUILD/DIR # where BUILD/DIR contains the built gtest_help_test_ file. gtest_help_test.py """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import gtest_test_utils IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') FLAG_PREFIX = '--gtest_' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to' UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), re.sub('^--', '/', LIST_TESTS_FLAG), re.sub('_', '-', LIST_TESTS_FLAG)] INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing' SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess( [PROGRAM_PATH, LIST_TESTS_FLAG]).output # The help message must match this regex. HELP_REGEX = re.compile( FLAG_PREFIX + r'list_tests.*' + FLAG_PREFIX + r'filter=.*' + FLAG_PREFIX + r'also_run_disabled_tests.*' + FLAG_PREFIX + r'repeat=.*' + FLAG_PREFIX + r'shuffle.*' + FLAG_PREFIX + r'random_seed=.*' + FLAG_PREFIX + r'color=.*' + FLAG_PREFIX + r'print_time.*' + FLAG_PREFIX + r'output=.*' + FLAG_PREFIX + r'break_on_failure.*' + FLAG_PREFIX + r'throw_on_failure.*' + FLAG_PREFIX + r'catch_exceptions=0.*', re.DOTALL) def RunWithFlag(flag): """Runs gtest_help_test_ with the given flag. Returns: the exit code and the text output as a tuple. Args: flag: the command-line flag to pass to gtest_help_test_, or None. """ if flag is None: command = [PROGRAM_PATH] else: command = [PROGRAM_PATH, flag] child = gtest_test_utils.Subprocess(command) return child.exit_code, child.output class GTestHelpTest(gtest_test_utils.TestCase): """Tests the --help flag and its equivalent forms.""" def TestHelpFlag(self, flag): """Verifies correct behavior when help flag is specified. The right message must be printed and the tests must skipped when the given flag is specified. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assertEquals(0, exit_code) self.assert_(HELP_REGEX.search(output), output) if IS_LINUX: self.assert_(STREAM_RESULT_TO_FLAG in output, output) else: self.assert_(STREAM_RESULT_TO_FLAG not in output, output) if SUPPORTS_DEATH_TESTS and not IS_WINDOWS: self.assert_(DEATH_TEST_STYLE_FLAG in output, output) else: self.assert_(DEATH_TEST_STYLE_FLAG not in output, output) def TestNonHelpFlag(self, flag): """Verifies correct behavior when no help flag is specified. Verifies that when no help flag is specified, the tests are run and the help message is not printed. Args: flag: A flag to pass to the binary or None. """ exit_code, output = RunWithFlag(flag) self.assert_(exit_code != 0) self.assert_(not HELP_REGEX.search(output), output) def testPrintsHelpWithFullFlag(self): self.TestHelpFlag('--help') def testPrintsHelpWithShortFlag(self): self.TestHelpFlag('-h') def testPrintsHelpWithQuestionFlag(self): self.TestHelpFlag('-?') def testPrintsHelpWithWindowsStyleQuestionFlag(self): self.TestHelpFlag('/?') def testPrintsHelpWithUnrecognizedGoogleTestFlag(self): self.TestHelpFlag(UNKNOWN_FLAG) def testPrintsHelpWithIncorrectFlagStyle(self): for incorrect_flag in INCORRECT_FLAG_VARIANTS: self.TestHelpFlag(incorrect_flag) def testRunsTestsWithoutHelpFlag(self): """Verifies that when no help flag is specified, the tests are run and the help message is not printed.""" self.TestNonHelpFlag(None) def testRunsTestsWithGtestInternalFlag(self): """Verifies that the tests are run and no help message is printed when a flag starting with Google Test prefix and 'internal_' is supplied.""" self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING) if __name__ == '__main__': gtest_test_utils.Main()
bsd-3-clause
jmehnle/ansible
lib/ansible/modules/system/openwrt_init.py
58
6912
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Andrew Gaffney <andrew@agaffney.org> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: openwrt_init author: - "Andrew Gaffney (@agaffney)" version_added: "2.3" short_description: Manage services on OpenWrt. description: - Controls OpenWrt services on remote hosts. options: name: required: true description: - Name of the service. aliases: ['service'] state: required: false default: null choices: [ 'started', 'stopped', 'restarted', 'reloaded' ] description: - C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload. enabled: required: false choices: [ "yes", "no" ] default: null description: - Whether the service should start on boot. B(At least one of state and enabled are required.) pattern: required: false description: - If the service does not respond to the 'running' command, name a substring to look for as would be found in the output of the I(ps) command as a stand-in for a 'running' result. If the string is found, the service will be assumed to be running. notes: - One option other than name is required. requirements: - An OpenWrt system ''' EXAMPLES = ''' # Example action to start service httpd, if not running - openwrt_init: state: started name: httpd # Example action to stop service cron, if running - openwrt_init: name: cron state: stopped # Example action to reload service httpd, in all cases - openwrt_init: name: httpd state: reloaded # Example action to enable service httpd - openwrt_init: name: httpd enabled: yes ''' RETURN = ''' ''' import os import glob from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native module = None init_script = None # =============================== # Check if service is enabled def is_enabled(): (rc, out, err) = module.run_command("%s enabled" % init_script) if rc == 0: return True return False # =========================================== # Main control flow def main(): global module, init_script # init module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['service']), state = dict(choices=['started', 'stopped', 'restarted', 'reloaded'], type='str'), enabled = dict(type='bool'), pattern = dict(required=False, default=None), ), supports_check_mode=True, required_one_of=[['state', 'enabled']], ) # initialize service = module.params['name'] init_script = '/etc/init.d/' + service rc = 0 out = err = '' result = { 'name': service, 'changed': False, } # check if service exists if not os.path.exists(init_script): module.fail_json(msg='service %s does not exist' % service) # Enable/disable service startup at boot if requested if module.params['enabled'] is not None: # do we need to enable the service? enabled = is_enabled() # default to current state result['enabled'] = enabled # Change enable/disable if needed if enabled != module.params['enabled']: result['changed'] = True if module.params['enabled']: action = 'enable' else: action = 'disable' if not module.check_mode: (rc, out, err) = module.run_command("%s %s" % (init_script, action)) # openwrt init scripts can return a non-zero exit code on a successful 'enable' # command if the init script doesn't contain a STOP value, so we ignore the exit # code and explicitly check if the service is now in the desired state if is_enabled() != module.params['enabled']: module.fail_json(msg="Unable to %s service %s: %s" % (action, service, err)) result['enabled'] = not enabled if module.params['state'] is not None: running = False # check if service is currently running if module.params['pattern']: # Find ps binary psbin = module.get_bin_path('ps', True) # this should be busybox ps, so we only want/need to the 'w' option (rc, psout, pserr) = module.run_command('%s w' % psbin) # If rc is 0, set running as appropriate if rc == 0: lines = psout.split("\n") for line in lines: if module.params['pattern'] in line and not "pattern=" in line: # so as to not confuse ./hacking/test-module running = True break else: (rc, out, err) = module.run_command("%s running" % init_script) if rc == 0: running = True # default to desired state result['state'] = module.params['state'] # determine action, if any action = None if module.params['state'] == 'started': if not running: action = 'start' result['changed'] = True elif module.params['state'] == 'stopped': if running: action = 'stop' result['changed'] = True else: action = module.params['state'][:-2] # remove 'ed' from restarted/reloaded result['state'] = 'started' result['changed'] = True if action: if not module.check_mode: (rc, out, err) = module.run_command("%s %s" % (init_script, action)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, service, err)) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
Motorhead1991/android_kernel_samsung_s5pv210
scripts/rt-tester/rt-tester.py
1094
5362
#!/usr/bin/python # # rt-mutex tester # # (C) 2006 Thomas Gleixner <tglx@linutronix.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # import os import sys import getopt import shutil import string # Globals quiet = 0 test = 0 comments = 0 sysfsprefix = "/sys/devices/system/rttest/rttest" statusfile = "/status" commandfile = "/command" # Command opcodes cmd_opcodes = { "schedother" : "1", "schedfifo" : "2", "lock" : "3", "locknowait" : "4", "lockint" : "5", "lockintnowait" : "6", "lockcont" : "7", "unlock" : "8", "lockbkl" : "9", "unlockbkl" : "10", "signal" : "11", "resetevent" : "98", "reset" : "99", } test_opcodes = { "prioeq" : ["P" , "eq" , None], "priolt" : ["P" , "lt" , None], "priogt" : ["P" , "gt" , None], "nprioeq" : ["N" , "eq" , None], "npriolt" : ["N" , "lt" , None], "npriogt" : ["N" , "gt" , None], "unlocked" : ["M" , "eq" , 0], "trylock" : ["M" , "eq" , 1], "blocked" : ["M" , "eq" , 2], "blockedwake" : ["M" , "eq" , 3], "locked" : ["M" , "eq" , 4], "opcodeeq" : ["O" , "eq" , None], "opcodelt" : ["O" , "lt" , None], "opcodegt" : ["O" , "gt" , None], "eventeq" : ["E" , "eq" , None], "eventlt" : ["E" , "lt" , None], "eventgt" : ["E" , "gt" , None], } # Print usage information def usage(): print "rt-tester.py <-c -h -q -t> <testfile>" print " -c display comments after first command" print " -h help" print " -q quiet mode" print " -t test mode (syntax check)" print " testfile: read test specification from testfile" print " otherwise from stdin" return # Print progress when not in quiet mode def progress(str): if not quiet: print str # Analyse a status value def analyse(val, top, arg): intval = int(val) if top[0] == "M": intval = intval / (10 ** int(arg)) intval = intval % 10 argval = top[2] elif top[0] == "O": argval = int(cmd_opcodes.get(arg, arg)) else: argval = int(arg) # progress("%d %s %d" %(intval, top[1], argval)) if top[1] == "eq" and intval == argval: return 1 if top[1] == "lt" and intval < argval: return 1 if top[1] == "gt" and intval > argval: return 1 return 0 # Parse the commandline try: (options, arguments) = getopt.getopt(sys.argv[1:],'chqt') except getopt.GetoptError, ex: usage() sys.exit(1) # Parse commandline options for option, value in options: if option == "-c": comments = 1 elif option == "-q": quiet = 1 elif option == "-t": test = 1 elif option == '-h': usage() sys.exit(0) # Select the input source if arguments: try: fd = open(arguments[0]) except Exception,ex: sys.stderr.write("File not found %s\n" %(arguments[0])) sys.exit(1) else: fd = sys.stdin linenr = 0 # Read the test patterns while 1: linenr = linenr + 1 line = fd.readline() if not len(line): break line = line.strip() parts = line.split(":") if not parts or len(parts) < 1: continue if len(parts[0]) == 0: continue if parts[0].startswith("#"): if comments > 1: progress(line) continue if comments == 1: comments = 2 progress(line) cmd = parts[0].strip().lower() opc = parts[1].strip().lower() tid = parts[2].strip() dat = parts[3].strip() try: # Test or wait for a status value if cmd == "t" or cmd == "w": testop = test_opcodes[opc] fname = "%s%s%s" %(sysfsprefix, tid, statusfile) if test: print fname continue while 1: query = 1 fsta = open(fname, 'r') status = fsta.readline().strip() fsta.close() stat = status.split(",") for s in stat: s = s.strip() if s.startswith(testop[0]): # Seperate status value val = s[2:].strip() query = analyse(val, testop, dat) break if query or cmd == "t": break progress(" " + status) if not query: sys.stderr.write("Test failed in line %d\n" %(linenr)) sys.exit(1) # Issue a command to the tester elif cmd == "c": cmdnr = cmd_opcodes[opc] # Build command string and sys filename cmdstr = "%s:%s" %(cmdnr, dat) fname = "%s%s%s" %(sysfsprefix, tid, commandfile) if test: print fname continue fcmd = open(fname, 'w') fcmd.write(cmdstr) fcmd.close() except Exception,ex: sys.stderr.write(str(ex)) sys.stderr.write("\nSyntax error in line %d\n" %(linenr)) if not test: fd.close() sys.exit(1) # Normal exit pass print "Pass" sys.exit(0)
gpl-2.0
MERegistro/meregistro
django/core/management/commands/compilemessages.py
373
2824
import codecs import os import sys from optparse import make_option from django.core.management.base import BaseCommand, CommandError def has_bom(fn): f = open(fn, 'r') sample = f.read(4) return sample[:3] == '\xef\xbb\xbf' or \ sample.startswith(codecs.BOM_UTF16_LE) or \ sample.startswith(codecs.BOM_UTF16_BE) def compile_messages(stderr, locale=None): basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified.") for basedir in basedirs: if locale: basedir = os.path.join(basedir, locale, 'LC_MESSAGES') for dirpath, dirnames, filenames in os.walk(basedir): for f in filenames: if f.endswith('.po'): stderr.write('processing file %s in %s\n' % (f, dirpath)) fn = os.path.join(dirpath, f) if has_bom(fn): raise CommandError("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM." % fn) pf = os.path.splitext(fn)[0] # Store the names of the .mo and .po files in an environment # variable, rather than doing a string replacement into the # command, so that we can take advantage of shell quoting, to # quote any malicious characters/escaping. # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html os.environ['djangocompilemo'] = pf + '.mo' os.environ['djangocompilepo'] = pf + '.po' if sys.platform == 'win32': # Different shell-variable syntax cmd = 'msgfmt --check-format -o "%djangocompilemo%" "%djangocompilepo%"' else: cmd = 'msgfmt --check-format -o "$djangocompilemo" "$djangocompilepo"' os.system(cmd) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--locale', '-l', dest='locale', help='The locale to process. Default is to process all.'), ) help = 'Compiles .po files to .mo files for use with builtin gettext support.' requires_model_validation = False can_import_settings = False def handle(self, **options): locale = options.get('locale') compile_messages(self.stderr, locale=locale)
bsd-3-clause
getsentry/fabric
fabric/contrib/project.py
4
7932
""" Useful non-core functionality, e.g. functions composing multiple operations. """ from __future__ import with_statement from os import getcwd, sep import os.path from datetime import datetime from tempfile import mkdtemp from fabric.network import needs_host, key_filenames, normalize from fabric.operations import local, run, sudo, put from fabric.state import env, output from fabric.context_managers import cd __all__ = ['rsync_project', 'upload_project'] @needs_host def rsync_project(remote_dir, local_dir=None, exclude=(), delete=False, extra_opts='', ssh_opts='', capture=False, upload=True): """ Synchronize a remote directory with the current project directory via rsync. Where ``upload_project()`` makes use of ``scp`` to copy one's entire project every time it is invoked, ``rsync_project()`` uses the ``rsync`` command-line utility, which only transfers files newer than those on the remote end. ``rsync_project()`` is thus a simple wrapper around ``rsync``; for details on how ``rsync`` works, please see its manpage. ``rsync`` must be installed on both your local and remote systems in order for this operation to work correctly. This function makes use of Fabric's ``local()`` operation, and returns the output of that function call; thus it will return the stdout, if any, of the resultant ``rsync`` call. ``rsync_project()`` takes the following parameters: * ``remote_dir``: the only required parameter, this is the path to the directory on the remote server. Due to how ``rsync`` is implemented, the exact behavior depends on the value of ``local_dir``: * If ``local_dir`` ends with a trailing slash, the files will be dropped inside of ``remote_dir``. E.g. ``rsync_project("/home/username/project", "foldername/")`` will drop the contents of ``foldername`` inside of ``/home/username/project``. * If ``local_dir`` does **not** end with a trailing slash (and this includes the default scenario, when ``local_dir`` is not specified), ``remote_dir`` is effectively the "parent" directory, and a new directory named after ``local_dir`` will be created inside of it. So ``rsync_project("/home/username", "foldername")`` would create a new directory ``/home/username/foldername`` (if needed) and place the files there. * ``local_dir``: by default, ``rsync_project`` uses your current working directory as the source directory. This may be overridden by specifying ``local_dir``, which is a string passed verbatim to ``rsync``, and thus may be a single directory (``"my_directory"``) or multiple directories (``"dir1 dir2"``). See the ``rsync`` documentation for details. * ``exclude``: optional, may be a single string, or an iterable of strings, and is used to pass one or more ``--exclude`` options to ``rsync``. * ``delete``: a boolean controlling whether ``rsync``'s ``--delete`` option is used. If True, instructs ``rsync`` to remove remote files that no longer exist locally. Defaults to False. * ``extra_opts``: an optional, arbitrary string which you may use to pass custom arguments or options to ``rsync``. * ``ssh_opts``: Like ``extra_opts`` but specifically for the SSH options string (rsync's ``--rsh`` flag.) * ``capture``: Sent directly into an inner `~fabric.operations.local` call. * ``upload``: a boolean controlling whether file synchronization is performed up or downstream. Upstream by default. Furthermore, this function transparently honors Fabric's port and SSH key settings. Calling this function when the current host string contains a nonstandard port, or when ``env.key_filename`` is non-empty, will use the specified port and/or SSH key filename(s). For reference, the approximate ``rsync`` command-line call that is constructed by this function is the following:: rsync [--delete] [--exclude exclude[0][, --exclude[1][, ...]]] \\ -pthrvz [extra_opts] <local_dir> <host_string>:<remote_dir> .. versionadded:: 1.4.0 The ``ssh_opts`` keyword argument. .. versionadded:: 1.4.1 The ``capture`` keyword argument. """ # Turn single-string exclude into a one-item list for consistency if not hasattr(exclude, '__iter__'): exclude = (exclude,) # Create --exclude options from exclude list exclude_opts = ' --exclude "%s"' * len(exclude) # Double-backslash-escape exclusions = tuple([str(s).replace('"', '\\\\"') for s in exclude]) # Honor SSH key(s) key_string = "" keys = key_filenames() if keys: key_string = "-i " + " -i ".join(keys) # Port user, host, port = normalize(env.host_string) port_string = "-p %s" % port # RSH rsh_string = "" rsh_parts = [key_string, port_string, ssh_opts] if any(rsh_parts): rsh_string = "--rsh='ssh %s'" % " ".join(rsh_parts) # Set up options part of string options_map = { 'delete': '--delete' if delete else '', 'exclude': exclude_opts % exclusions, 'rsh': rsh_string, 'extra': extra_opts } options = "%(delete)s%(exclude)s -pthrvz %(extra)s %(rsh)s" % options_map # Get local directory if local_dir is None: local_dir = '../' + getcwd().split(sep)[-1] # Create and run final command string if host.count(':') > 1: # Square brackets are mandatory for IPv6 rsync address, # even if port number is not specified remote_prefix = "[%s@%s]" % (user, host) else: remote_prefix = "%s@%s" % (user, host) if upload: cmd = "rsync %s %s %s:%s" % (options, local_dir, remote_prefix, remote_dir) else: cmd = "rsync %s %s:%s %s" % (options, remote_prefix, remote_dir, local_dir) if output.running: print("[%s] rsync_project: %s" % (env.host_string, cmd)) return local(cmd, capture=capture) def upload_project(local_dir=None, remote_dir="", use_sudo=False): """ Upload the current project to a remote system via ``tar``/``gzip``. ``local_dir`` specifies the local project directory to upload, and defaults to the current working directory. ``remote_dir`` specifies the target directory to upload into (meaning that a copy of ``local_dir`` will appear as a subdirectory of ``remote_dir``) and defaults to the remote user's home directory. ``use_sudo`` specifies which method should be used when executing commands remotely. ``sudo`` will be used if use_sudo is True, otherwise ``run`` will be used. This function makes use of the ``tar`` and ``gzip`` programs/libraries, thus it will not work too well on Win32 systems unless one is using Cygwin or something similar. It will attempt to clean up the local and remote tarfiles when it finishes executing, even in the event of a failure. .. versionchanged:: 1.1 Added the ``local_dir`` and ``remote_dir`` kwargs. .. versionchanged:: 1.7 Added the ``use_sudo`` kwarg. """ runner = use_sudo and sudo or run local_dir = local_dir or os.getcwd() # Remove final '/' in local_dir so that basename() works local_dir = local_dir.rstrip(os.sep) local_path, local_name = os.path.split(local_dir) tar_file = "%s.tar.gz" % local_name target_tar = os.path.join(remote_dir, tar_file) tmp_folder = mkdtemp() try: tar_path = os.path.join(tmp_folder, tar_file) local("tar -czf %s -C %s %s" % (tar_path, local_path, local_name)) put(tar_path, target_tar, use_sudo=use_sudo) with cd(remote_dir): try: runner("tar -xzf %s" % tar_file) finally: runner("rm -f %s" % tar_file) finally: local("rm -rf %s" % tmp_folder)
bsd-2-clause
hectord/lettuce
tests/integration/lib/Django-1.3/django/contrib/gis/tests/geo3d/tests.py
155
11305
import os import re from django.utils.unittest import TestCase from django.contrib.gis.db.models import Union, Extent3D from django.contrib.gis.geos import GEOSGeometry, Point, Polygon from django.contrib.gis.utils import LayerMapping, LayerMapError from models import City3D, Interstate2D, Interstate3D, \ InterstateProj2D, InterstateProj3D, \ Point2D, Point3D, MultiPoint3D, Polygon2D, Polygon3D data_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data')) city_file = os.path.join(data_path, 'cities', 'cities.shp') vrt_file = os.path.join(data_path, 'test_vrt', 'test_vrt.vrt') # The coordinates of each city, with Z values corresponding to their # altitude in meters. city_data = ( ('Houston', (-95.363151, 29.763374, 18)), ('Dallas', (-96.801611, 32.782057, 147)), ('Oklahoma City', (-97.521157, 34.464642, 380)), ('Wellington', (174.783117, -41.315268, 14)), ('Pueblo', (-104.609252, 38.255001, 1433)), ('Lawrence', (-95.235060, 38.971823, 251)), ('Chicago', (-87.650175, 41.850385, 181)), ('Victoria', (-123.305196, 48.462611, 15)), ) # Reference mapping of city name to its altitude (Z value). city_dict = dict((name, coords) for name, coords in city_data) # 3D freeway data derived from the National Elevation Dataset: # http://seamless.usgs.gov/products/9arc.php interstate_data = ( ('I-45', 'LINESTRING(-95.3708481 29.7765870 11.339,-95.3694580 29.7787980 4.536,-95.3690305 29.7797359 9.762,-95.3691886 29.7812450 12.448,-95.3696447 29.7850144 10.457,-95.3702511 29.7868518 9.418,-95.3706724 29.7881286 14.858,-95.3711632 29.7896157 15.386,-95.3714525 29.7936267 13.168,-95.3717848 29.7955007 15.104,-95.3717719 29.7969804 16.516,-95.3717305 29.7982117 13.923,-95.3717254 29.8000778 14.385,-95.3719875 29.8013539 15.160,-95.3720575 29.8026785 15.544,-95.3721321 29.8040912 14.975,-95.3722074 29.8050998 15.688,-95.3722779 29.8060430 16.099,-95.3733818 29.8076750 15.197,-95.3741563 29.8103686 17.268,-95.3749458 29.8129927 19.857,-95.3763564 29.8144557 15.435)', ( 11.339, 4.536, 9.762, 12.448, 10.457, 9.418, 14.858, 15.386, 13.168, 15.104, 16.516, 13.923, 14.385, 15.16 , 15.544, 14.975, 15.688, 16.099, 15.197, 17.268, 19.857, 15.435), ), ) # Bounding box polygon for inner-loop of Houston (in projected coordinate # system 32140), with elevation values from the National Elevation Dataset # (see above). bbox_wkt = 'POLYGON((941527.97 4225693.20,962596.48 4226349.75,963152.57 4209023.95,942051.75 4208366.38,941527.97 4225693.20))' bbox_z = (21.71, 13.21, 9.12, 16.40, 21.71) def gen_bbox(): bbox_2d = GEOSGeometry(bbox_wkt, srid=32140) bbox_3d = Polygon(tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140) return bbox_2d, bbox_3d class Geo3DTest(TestCase): """ Only a subset of the PostGIS routines are 3D-enabled, and this TestCase tries to test the features that can handle 3D and that are also available within GeoDjango. For more information, see the PostGIS docs on the routines that support 3D: http://postgis.refractions.net/documentation/manual-1.4/ch08.html#PostGIS_3D_Functions """ def test01_3d(self): "Test the creation of 3D models." # 3D models for the rest of the tests will be populated in here. # For each 3D data set create model (and 2D version if necessary), # retrieve, and assert geometry is in 3D and contains the expected # 3D values. for name, pnt_data in city_data: x, y, z = pnt_data pnt = Point(x, y, z, srid=4326) City3D.objects.create(name=name, point=pnt) city = City3D.objects.get(name=name) self.assertTrue(city.point.hasz) self.assertEqual(z, city.point.z) # Interstate (2D / 3D and Geographic/Projected variants) for name, line, exp_z in interstate_data: line_3d = GEOSGeometry(line, srid=4269) # Using `hex` attribute because it omits 3D. line_2d = GEOSGeometry(line_3d.hex, srid=4269) # Creating a geographic and projected version of the # interstate in both 2D and 3D. Interstate3D.objects.create(name=name, line=line_3d) InterstateProj3D.objects.create(name=name, line=line_3d) Interstate2D.objects.create(name=name, line=line_2d) InterstateProj2D.objects.create(name=name, line=line_2d) # Retrieving and making sure it's 3D and has expected # Z values -- shouldn't change because of coordinate system. interstate = Interstate3D.objects.get(name=name) interstate_proj = InterstateProj3D.objects.get(name=name) for i in [interstate, interstate_proj]: self.assertTrue(i.line.hasz) self.assertEqual(exp_z, tuple(i.line.z)) # Creating 3D Polygon. bbox2d, bbox3d = gen_bbox() Polygon2D.objects.create(name='2D BBox', poly=bbox2d) Polygon3D.objects.create(name='3D BBox', poly=bbox3d) p3d = Polygon3D.objects.get(name='3D BBox') self.assertTrue(p3d.poly.hasz) self.assertEqual(bbox3d, p3d.poly) def test01a_3d_layermapping(self): "Testing LayerMapping on 3D models." from models import Point2D, Point3D point_mapping = {'point' : 'POINT'} mpoint_mapping = {'mpoint' : 'MULTIPOINT'} # The VRT is 3D, but should still be able to map sans the Z. lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point2D.objects.count()) # The city shapefile is 2D, and won't be able to fill the coordinates # in the 3D model -- thus, a LayerMapError is raised. self.assertRaises(LayerMapError, LayerMapping, Point3D, city_file, point_mapping, transform=False) # 3D model should take 3D data just fine. lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point3D.objects.count()) # Making sure LayerMapping.make_multi works right, by converting # a Point25D into a MultiPoint25D. lm = LayerMapping(MultiPoint3D, vrt_file, mpoint_mapping, transform=False) lm.save() self.assertEqual(3, MultiPoint3D.objects.count()) def test02a_kml(self): "Test GeoQuerySet.kml() with Z values." h = City3D.objects.kml(precision=6).get(name='Houston') # KML should be 3D. # `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';` ref_kml_regex = re.compile(r'^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$') self.assertTrue(ref_kml_regex.match(h.kml)) def test02b_geojson(self): "Test GeoQuerySet.geojson() with Z values." h = City3D.objects.geojson(precision=6).get(name='Houston') # GeoJSON should be 3D # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';` ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$') self.assertTrue(ref_json_regex.match(h.geojson)) def test03a_union(self): "Testing the Union aggregate of 3D models." # PostGIS query that returned the reference EWKT for this test: # `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;` ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)' ref_union = GEOSGeometry(ref_ewkt) union = City3D.objects.aggregate(Union('point'))['point__union'] self.assertTrue(union.hasz) self.assertEqual(ref_union, union) def test03b_extent(self): "Testing the Extent3D aggregate for 3D models." # `SELECT ST_Extent3D(point) FROM geo3d_city3d;` ref_extent3d = (-123.305196, -41.315268, 14,174.783117, 48.462611, 1433) extent1 = City3D.objects.aggregate(Extent3D('point'))['point__extent3d'] extent2 = City3D.objects.extent3d() def check_extent3d(extent3d, tol=6): for ref_val, ext_val in zip(ref_extent3d, extent3d): self.assertAlmostEqual(ref_val, ext_val, tol) for e3d in [extent1, extent2]: check_extent3d(e3d) def test04_perimeter(self): "Testing GeoQuerySet.perimeter() on 3D fields." # Reference query for values below: # `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) FROM geo3d_polygon3d;` ref_perim_3d = 76859.2620451 ref_perim_2d = 76859.2577803 tol = 6 self.assertAlmostEqual(ref_perim_2d, Polygon2D.objects.perimeter().get(name='2D BBox').perimeter.m, tol) self.assertAlmostEqual(ref_perim_3d, Polygon3D.objects.perimeter().get(name='3D BBox').perimeter.m, tol) def test05_length(self): "Testing GeoQuerySet.length() on 3D fields." # ST_Length_Spheroid Z-aware, and thus does not need to use # a separate function internally. # `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]') # FROM geo3d_interstate[2d|3d];` tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 self.assertAlmostEqual(ref_length_2d, Interstate2D.objects.length().get(name='I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, Interstate3D.objects.length().get(name='I-45').length.m, tol) # Making sure `ST_Length3D` is used on for a projected # and 3D model rather than `ST_Length`. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;` ref_length_2d = 4367.71564892392 # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;` ref_length_3d = 4368.16897234101 self.assertAlmostEqual(ref_length_2d, InterstateProj2D.objects.length().get(name='I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, InterstateProj3D.objects.length().get(name='I-45').length.m, tol) def test06_scale(self): "Testing GeoQuerySet.scale() on Z values." # Mapping of City name to reference Z values. zscales = (-3, 4, 23) for zscale in zscales: for city in City3D.objects.scale(1.0, 1.0, zscale): self.assertEqual(city_dict[city.name][2] * zscale, city.scale.z) def test07_translate(self): "Testing GeoQuerySet.translate() on Z values." ztranslations = (5.23, 23, -17) for ztrans in ztranslations: for city in City3D.objects.translate(0, 0, ztrans): self.assertEqual(city_dict[city.name][2] + ztrans, city.translate.z)
gpl-3.0
0jpq0/kbengine
kbe/src/lib/python/Lib/imaplib.py
74
50338
"""IMAP4 client. Based on RFC 2060. Public class: IMAP4 Public variable: Debug Public functions: Internaldate2tuple Int2AP ParseFlags Time2Internaldate """ # Author: Piers Lauder <piers@cs.su.oz.au> December 1997. # # Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998. # String method conversion by ESR, February 2001. # GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001. # IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002. # GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002. # PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002. # GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005. __version__ = "2.58" import binascii, errno, random, re, socket, subprocess, sys, time, calendar from datetime import datetime, timezone, timedelta from io import DEFAULT_BUFFER_SIZE try: import ssl HAVE_SSL = True except ImportError: HAVE_SSL = False __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate"] # Globals CRLF = b'\r\n' Debug = 0 IMAP4_PORT = 143 IMAP4_SSL_PORT = 993 AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first # Maximal line length when calling readline(). This is to prevent # reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1) # don't specify a line length. RFC 2683 however suggests limiting client # command lines to 1000 octets and server command lines to 8000 octets. # We have selected 10000 for some extra margin and since that is supposedly # also what UW and Panda IMAP does. _MAXLINE = 10000 # Commands Commands = { # name valid states 'APPEND': ('AUTH', 'SELECTED'), 'AUTHENTICATE': ('NONAUTH',), 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'CHECK': ('SELECTED',), 'CLOSE': ('SELECTED',), 'COPY': ('SELECTED',), 'CREATE': ('AUTH', 'SELECTED'), 'DELETE': ('AUTH', 'SELECTED'), 'DELETEACL': ('AUTH', 'SELECTED'), 'EXAMINE': ('AUTH', 'SELECTED'), 'EXPUNGE': ('SELECTED',), 'FETCH': ('SELECTED',), 'GETACL': ('AUTH', 'SELECTED'), 'GETANNOTATION':('AUTH', 'SELECTED'), 'GETQUOTA': ('AUTH', 'SELECTED'), 'GETQUOTAROOT': ('AUTH', 'SELECTED'), 'MYRIGHTS': ('AUTH', 'SELECTED'), 'LIST': ('AUTH', 'SELECTED'), 'LOGIN': ('NONAUTH',), 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'LSUB': ('AUTH', 'SELECTED'), 'NAMESPACE': ('AUTH', 'SELECTED'), 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), 'PARTIAL': ('SELECTED',), # NB: obsolete 'PROXYAUTH': ('AUTH',), 'RENAME': ('AUTH', 'SELECTED'), 'SEARCH': ('SELECTED',), 'SELECT': ('AUTH', 'SELECTED'), 'SETACL': ('AUTH', 'SELECTED'), 'SETANNOTATION':('AUTH', 'SELECTED'), 'SETQUOTA': ('AUTH', 'SELECTED'), 'SORT': ('SELECTED',), 'STARTTLS': ('NONAUTH',), 'STATUS': ('AUTH', 'SELECTED'), 'STORE': ('SELECTED',), 'SUBSCRIBE': ('AUTH', 'SELECTED'), 'THREAD': ('SELECTED',), 'UID': ('SELECTED',), 'UNSUBSCRIBE': ('AUTH', 'SELECTED'), } # Patterns to match server responses Continuation = re.compile(br'\+( (?P<data>.*))?') Flags = re.compile(br'.*FLAGS \((?P<flags>[^\)]*)\)') InternalDate = re.compile(br'.*INTERNALDATE "' br'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])' br' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])' br' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' br'"') Literal = re.compile(br'.*{(?P<size>\d+)}$', re.ASCII) MapCRLF = re.compile(br'\r\n|\r|\n') Response_code = re.compile(br'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]') Untagged_response = re.compile(br'\* (?P<type>[A-Z-]+)( (?P<data>.*))?') Untagged_status = re.compile( br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?', re.ASCII) class IMAP4: """IMAP4 client class. Instantiate with: IMAP4([host[, port]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 port). All IMAP4rev1 commands are supported by methods of the same name (in lower-case). All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. If necessary (the string contains any non-printing characters or white-space and isn't enclosed with either parentheses or double quotes) each string is quoted. However, the 'password' argument to the LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the 'flags' argument to STORE) then enclose the string in parentheses (eg: "(\Deleted)"). Each command returns a tuple: (type, [data, ...]) where 'type' is usually 'OK' or 'NO', and 'data' is either the text from the tagged response, or untagged results from command. Each 'data' is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: 'literal' value). Errors raise the exception class <instance>.error("<reason>"). IMAP4 server errors raise <instance>.abort("<reason>"), which is a sub-class of 'error'. Mailbox status changes from READ-WRITE to READ-ONLY raise the exception class <instance>.readonly("<reason>"), which is a sub-class of 'abort'. "error" exceptions imply a program error. "abort" exceptions imply the connection should be reset, and the command re-tried. "readonly" exceptions imply the command should be re-tried. Note: to use this module, you must read the RFCs pertaining to the IMAP4 protocol, as the semantics of the arguments to each IMAP4 command are left to the invoker, not to mention the results. Also, most IMAP servers implement a sub-set of the commands available here. """ class error(Exception): pass # Logical errors - debug required class abort(error): pass # Service errors - close and retry class readonly(abort): pass # Mailbox status changed to READ-ONLY def __init__(self, host = '', port = IMAP4_PORT): self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.is_readonly = False # READ-ONLY desired state self.tagnum = 0 self._tls_established = False # Open socket to server. self.open(host, port) try: self._connect() except Exception: try: self.shutdown() except OSError: pass raise def _connect(self): # Create unique tag for this session, # and compile tagged response matcher. self.tagpre = Int2AP(random.randint(4096, 65535)) self.tagre = re.compile(br'(?P<tag>' + self.tagpre + br'\d+) (?P<type>[A-Z]+) (?P<data>.*)', re.ASCII) # Get server welcome message, # request and store CAPABILITY response. if __debug__: self._cmd_log_len = 10 self._cmd_log_idx = 0 self._cmd_log = {} # Last `_cmd_log_len' interactions if self.debug >= 1: self._mesg('imaplib version %s' % __version__) self._mesg('new IMAP4 connection, tag=%s' % self.tagpre) self.welcome = self._get_response() if 'PREAUTH' in self.untagged_responses: self.state = 'AUTH' elif 'OK' in self.untagged_responses: self.state = 'NONAUTH' else: raise self.error(self.welcome) self._get_capabilities() if __debug__: if self.debug >= 3: self._mesg('CAPABILITIES: %r' % (self.capabilities,)) for version in AllowedVersions: if not version in self.capabilities: continue self.PROTOCOL_VERSION = version return raise self.error('server not IMAP4 compliant') def __getattr__(self, attr): # Allow UPPERCASE variants of IMAP4 command methods. if attr in Commands: return getattr(self, attr.lower()) raise AttributeError("Unknown IMAP4 command: '%s'" % attr) # Overridable methods def _create_socket(self): return socket.create_connection((self.host, self.port)) def open(self, host = '', port = IMAP4_PORT): """Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown. """ self.host = host self.port = port self.sock = self._create_socket() self.file = self.sock.makefile('rb') def read(self, size): """Read 'size' bytes from remote.""" return self.file.read(size) def readline(self): """Read line from remote.""" line = self.file.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise self.error("got more than %d bytes" % _MAXLINE) return line def send(self, data): """Send data to remote.""" self.sock.sendall(data) def shutdown(self): """Close I/O established in "open".""" self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: # The server might already have closed the connection if e.errno != errno.ENOTCONN: raise finally: self.sock.close() def socket(self): """Return socket instance used to connect to IMAP4 server. socket = <instance>.socket() """ return self.sock # Utility methods def recent(self): """Return most recent 'RECENT' responses if any exist, else prompt server for an update using the 'NOOP' command. (typ, [data]) = <instance>.recent() 'data' is None if no new messages, else list of RECENT responses, most recent last. """ name = 'RECENT' typ, dat = self._untagged_response('OK', [None], name) if dat[-1]: return typ, dat typ, dat = self.noop() # Prod server for response return self._untagged_response(typ, dat, name) def response(self, code): """Return data for response 'code' if received, or None. Old value for response 'code' is cleared. (code, [data]) = <instance>.response(code) """ return self._untagged_response(code, [None], code.upper()) # IMAP4 commands def append(self, mailbox, flags, date_time, message): """Append message to named mailbox. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message) All args except `message' can be None. """ name = 'APPEND' if not mailbox: mailbox = 'INBOX' if flags: if (flags[0],flags[-1]) != ('(',')'): flags = '(%s)' % flags else: flags = None if date_time: date_time = Time2Internaldate(date_time) else: date_time = None self.literal = MapCRLF.sub(CRLF, message) return self._simple_command(name, mailbox, flags, date_time) def authenticate(self, mechanism, authobject): """Authenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. 'authobject' must be a callable object: data = authobject(response) It will be called to process server continuation responses; the response argument it is passed will be a bytes. It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response '*' should be sent instead. """ mech = mechanism.upper() # XXX: shouldn't this code be removed, not commented out? #cap = 'AUTH=%s' % mech #if not cap in self.capabilities: # Let the server decide! # raise self.error("Server doesn't allow %s authentication." % mech) self.literal = _Authenticator(authobject).process typ, dat = self._simple_command('AUTHENTICATE', mech) if typ != 'OK': raise self.error(dat[-1]) self.state = 'AUTH' return typ, dat def capability(self): """(typ, [data]) = <instance>.capability() Fetch capabilities list from server.""" name = 'CAPABILITY' typ, dat = self._simple_command(name) return self._untagged_response(typ, dat, name) def check(self): """Checkpoint mailbox on server. (typ, [data]) = <instance>.check() """ return self._simple_command('CHECK') def close(self): """Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'. (typ, [data]) = <instance>.close() """ try: typ, dat = self._simple_command('CLOSE') finally: self.state = 'AUTH' return typ, dat def copy(self, message_set, new_mailbox): """Copy 'message_set' messages onto end of 'new_mailbox'. (typ, [data]) = <instance>.copy(message_set, new_mailbox) """ return self._simple_command('COPY', message_set, new_mailbox) def create(self, mailbox): """Create new mailbox. (typ, [data]) = <instance>.create(mailbox) """ return self._simple_command('CREATE', mailbox) def delete(self, mailbox): """Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox) """ return self._simple_command('DELETE', mailbox) def deleteacl(self, mailbox, who): """Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who) """ return self._simple_command('DELETEACL', mailbox, who) def expunge(self): """Permanently remove deleted items from selected mailbox. Generates 'EXPUNGE' response for each deleted message. (typ, [data]) = <instance>.expunge() 'data' is list of 'EXPUNGE'd message numbers in order received. """ name = 'EXPUNGE' typ, dat = self._simple_command(name) return self._untagged_response(typ, dat, name) def fetch(self, message_set, message_parts): """Fetch (parts of) messages. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts) 'message_parts' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". 'data' are tuples of message part envelope and data. """ name = 'FETCH' typ, dat = self._simple_command(name, message_set, message_parts) return self._untagged_response(typ, dat, name) def getacl(self, mailbox): """Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox) """ typ, dat = self._simple_command('GETACL', mailbox) return self._untagged_response(typ, dat, 'ACL') def getannotation(self, mailbox, entry, attribute): """(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.""" typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute) return self._untagged_response(typ, dat, 'ANNOTATION') def getquota(self, root): """Get the quota root's resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = <instance>.getquota(root) """ typ, dat = self._simple_command('GETQUOTA', root) return self._untagged_response(typ, dat, 'QUOTA') def getquotaroot(self, mailbox): """Get the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox) """ typ, dat = self._simple_command('GETQUOTAROOT', mailbox) typ, quota = self._untagged_response(typ, dat, 'QUOTA') typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT') return typ, [quotaroot, quota] def list(self, directory='""', pattern='*'): """List mailbox names in directory matching pattern. (typ, [data]) = <instance>.list(directory='""', pattern='*') 'data' is list of LIST responses. """ name = 'LIST' typ, dat = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name) def login(self, user, password): """Identify client using plaintext password. (typ, [data]) = <instance>.login(user, password) NB: 'password' will be quoted. """ typ, dat = self._simple_command('LOGIN', user, self._quote(password)) if typ != 'OK': raise self.error(dat[-1]) self.state = 'AUTH' return typ, dat def login_cram_md5(self, user, password): """ Force use of CRAM-MD5 authentication. (typ, [data]) = <instance>.login_cram_md5(user, password) """ self.user, self.password = user, password return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH) def _CRAM_MD5_AUTH(self, challenge): """ Authobject to use with CRAM-MD5 authentication. """ import hmac pwd = (self.password.encode('ASCII') if isinstance(self.password, str) else self.password) return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest() def logout(self): """Shutdown connection to server. (typ, [data]) = <instance>.logout() Returns server 'BYE' response. """ self.state = 'LOGOUT' try: typ, dat = self._simple_command('LOGOUT') except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]] self.shutdown() if 'BYE' in self.untagged_responses: return 'BYE', self.untagged_responses['BYE'] return typ, dat def lsub(self, directory='""', pattern='*'): """List 'subscribed' mailbox names in directory matching pattern. (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*') 'data' are tuples of message part envelope and data. """ name = 'LSUB' typ, dat = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name) def myrights(self, mailbox): """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = <instance>.myrights(mailbox) """ typ,dat = self._simple_command('MYRIGHTS', mailbox) return self._untagged_response(typ, dat, 'MYRIGHTS') def namespace(self): """ Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = <instance>.namespace() """ name = 'NAMESPACE' typ, dat = self._simple_command(name) return self._untagged_response(typ, dat, name) def noop(self): """Send NOOP command. (typ, [data]) = <instance>.noop() """ if __debug__: if self.debug >= 3: self._dump_ur(self.untagged_responses) return self._simple_command('NOOP') def partial(self, message_num, message_part, start, length): """Fetch truncated part of a message. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length) 'data' is tuple of message part envelope and data. """ name = 'PARTIAL' typ, dat = self._simple_command(name, message_num, message_part, start, length) return self._untagged_response(typ, dat, 'FETCH') def proxyauth(self, user): """Assume authentication as "user". Allows an authorised administrator to proxy into any user's mailbox. (typ, [data]) = <instance>.proxyauth(user) """ name = 'PROXYAUTH' return self._simple_command('PROXYAUTH', user) def rename(self, oldmailbox, newmailbox): """Rename old mailbox name to new. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox) """ return self._simple_command('RENAME', oldmailbox, newmailbox) def search(self, charset, *criteria): """Search mailbox for matching messages. (typ, [data]) = <instance>.search(charset, criterion, ...) 'data' is space separated list of matching message numbers. """ name = 'SEARCH' if charset: typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria) else: typ, dat = self._simple_command(name, *criteria) return self._untagged_response(typ, dat, name) def select(self, mailbox='INBOX', readonly=False): """Select a mailbox. Flush all untagged responses. (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False) 'data' is count of messages in mailbox ('EXISTS' response). Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so other responses should be obtained via <instance>.response('FLAGS') etc. """ self.untagged_responses = {} # Flush old responses. self.is_readonly = readonly if readonly: name = 'EXAMINE' else: name = 'SELECT' typ, dat = self._simple_command(name, mailbox) if typ != 'OK': self.state = 'AUTH' # Might have been 'SELECTED' return typ, dat self.state = 'SELECTED' if 'READ-ONLY' in self.untagged_responses \ and not readonly: if __debug__: if self.debug >= 1: self._dump_ur(self.untagged_responses) raise self.readonly('%s is not writable' % mailbox) return typ, self.untagged_responses.get('EXISTS', [None]) def setacl(self, mailbox, who, what): """Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what) """ return self._simple_command('SETACL', mailbox, who, what) def setannotation(self, *args): """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.""" typ, dat = self._simple_command('SETANNOTATION', *args) return self._untagged_response(typ, dat, 'ANNOTATION') def setquota(self, root, limits): """Set the quota root's resource limits. (typ, [data]) = <instance>.setquota(root, limits) """ typ, dat = self._simple_command('SETQUOTA', root, limits) return self._untagged_response(typ, dat, 'QUOTA') def sort(self, sort_criteria, charset, *search_criteria): """IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...) """ name = 'SORT' #if not name in self.capabilities: # Let the server decide! # raise self.error('unimplemented extension command: %s' % name) if (sort_criteria[0],sort_criteria[-1]) != ('(',')'): sort_criteria = '(%s)' % sort_criteria typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name) def starttls(self, ssl_context=None): name = 'STARTTLS' if not HAVE_SSL: raise self.error('SSL support missing') if self._tls_established: raise self.abort('TLS session already established') if name not in self.capabilities: raise self.abort('TLS not supported by server') # Generate a default SSL context if none was passed. if ssl_context is None: ssl_context = ssl._create_stdlib_context() typ, dat = self._simple_command(name) if typ == 'OK': server_hostname = self.host if ssl.HAS_SNI else None self.sock = ssl_context.wrap_socket(self.sock, server_hostname=server_hostname) self.file = self.sock.makefile('rb') self._tls_established = True self._get_capabilities() else: raise self.error("Couldn't establish TLS session") return self._untagged_response(typ, dat, name) def status(self, mailbox, names): """Request named status conditions for mailbox. (typ, [data]) = <instance>.status(mailbox, names) """ name = 'STATUS' #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide! # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name) typ, dat = self._simple_command(name, mailbox, names) return self._untagged_response(typ, dat, name) def store(self, message_set, command, flags): """Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags) """ if (flags[0],flags[-1]) != ('(',')'): flags = '(%s)' % flags # Avoid quoting the flags typ, dat = self._simple_command('STORE', message_set, command, flags) return self._untagged_response(typ, dat, 'FETCH') def subscribe(self, mailbox): """Subscribe to new mailbox. (typ, [data]) = <instance>.subscribe(mailbox) """ return self._simple_command('SUBSCRIBE', mailbox) def thread(self, threading_algorithm, charset, *search_criteria): """IMAPrev1 extension THREAD command. (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...) """ name = 'THREAD' typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria) return self._untagged_response(typ, dat, name) def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...) Returns response appropriate to 'command'. """ command = command.upper() if not command in Commands: raise self.error("Unknown IMAP4 UID command: %s" % command) if self.state not in Commands[command]: raise self.error("command %s illegal in state %s, " "only allowed in states %s" % (command, self.state, ', '.join(Commands[command]))) name = 'UID' typ, dat = self._simple_command(name, command, *args) if command in ('SEARCH', 'SORT', 'THREAD'): name = command else: name = 'FETCH' return self._untagged_response(typ, dat, name) def unsubscribe(self, mailbox): """Unsubscribe from old mailbox. (typ, [data]) = <instance>.unsubscribe(mailbox) """ return self._simple_command('UNSUBSCRIBE', mailbox) def xatom(self, name, *args): """Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. (typ, [data]) = <instance>.xatom(name, arg, ...) Returns response appropriate to extension command `name'. """ name = name.upper() #if not name in self.capabilities: # Let the server decide! # raise self.error('unknown extension command: %s' % name) if not name in Commands: Commands[name] = (self.state,) return self._simple_command(name, *args) # Private methods def _append_untagged(self, typ, dat): if dat is None: dat = b'' ur = self.untagged_responses if __debug__: if self.debug >= 5: self._mesg('untagged_responses[%s] %s += ["%r"]' % (typ, len(ur.get(typ,'')), dat)) if typ in ur: ur[typ].append(dat) else: ur[typ] = [dat] def _check_bye(self): bye = self.untagged_responses.get('BYE') if bye: raise self.abort(bye[-1].decode('ascii', 'replace')) def _command(self, name, *args): if self.state not in Commands[name]: self.literal = None raise self.error("command %s illegal in state %s, " "only allowed in states %s" % (name, self.state, ', '.join(Commands[name]))) for typ in ('OK', 'NO', 'BAD'): if typ in self.untagged_responses: del self.untagged_responses[typ] if 'READ-ONLY' in self.untagged_responses \ and not self.is_readonly: raise self.readonly('mailbox status changed to READ-ONLY') tag = self._new_tag() name = bytes(name, 'ASCII') data = tag + b' ' + name for arg in args: if arg is None: continue if isinstance(arg, str): arg = bytes(arg, "ASCII") data = data + b' ' + arg literal = self.literal if literal is not None: self.literal = None if type(literal) is type(self._command): literator = literal else: literator = None data = data + bytes(' {%s}' % len(literal), 'ASCII') if __debug__: if self.debug >= 4: self._mesg('> %r' % data) else: self._log('> %r' % data) try: self.send(data + CRLF) except OSError as val: raise self.abort('socket error: %s' % val) if literal is None: return tag while 1: # Wait for continuation response while self._get_response(): if self.tagged_commands[tag]: # BAD/NO? return tag # Send literal if literator: literal = literator(self.continuation_response) if __debug__: if self.debug >= 4: self._mesg('write literal size %s' % len(literal)) try: self.send(literal) self.send(CRLF) except OSError as val: raise self.abort('socket error: %s' % val) if not literator: break return tag def _command_complete(self, name, tag): # BYE is expected after LOGOUT if name != 'LOGOUT': self._check_bye() try: typ, data = self._get_tagged_response(tag) except self.abort as val: raise self.abort('command: %s => %s' % (name, val)) except self.error as val: raise self.error('command: %s => %s' % (name, val)) if name != 'LOGOUT': self._check_bye() if typ == 'BAD': raise self.error('%s command error: %s %s' % (name, typ, data)) return typ, data def _get_capabilities(self): typ, dat = self.capability() if dat == [None]: raise self.error('no CAPABILITY response from server') dat = str(dat[-1], "ASCII") dat = dat.upper() self.capabilities = tuple(dat.split()) def _get_response(self): # Read response and store. # # Returns None for continuation responses, # otherwise first response line received. resp = self._get_line() # Command completion response? if self._match(self.tagre, resp): tag = self.mo.group('tag') if not tag in self.tagged_commands: raise self.abort('unexpected tagged response: %s' % resp) typ = self.mo.group('type') typ = str(typ, 'ASCII') dat = self.mo.group('data') self.tagged_commands[tag] = (typ, [dat]) else: dat2 = None # '*' (untagged) responses? if not self._match(Untagged_response, resp): if self._match(Untagged_status, resp): dat2 = self.mo.group('data2') if self.mo is None: # Only other possibility is '+' (continuation) response... if self._match(Continuation, resp): self.continuation_response = self.mo.group('data') return None # NB: indicates continuation raise self.abort("unexpected response: '%s'" % resp) typ = self.mo.group('type') typ = str(typ, 'ascii') dat = self.mo.group('data') if dat is None: dat = b'' # Null untagged response if dat2: dat = dat + b' ' + dat2 # Is there a literal to come? while self._match(Literal, dat): # Read literal direct from connection. size = int(self.mo.group('size')) if __debug__: if self.debug >= 4: self._mesg('read literal size %s' % size) data = self.read(size) # Store response with literal as tuple self._append_untagged(typ, (dat, data)) # Read trailer - possibly containing another literal dat = self._get_line() self._append_untagged(typ, dat) # Bracketed response information? if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat): typ = self.mo.group('type') typ = str(typ, "ASCII") self._append_untagged(typ, self.mo.group('data')) if __debug__: if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'): self._mesg('%s response: %r' % (typ, dat)) return resp def _get_tagged_response(self, tag): while 1: result = self.tagged_commands[tag] if result is not None: del self.tagged_commands[tag] return result # If we've seen a BYE at this point, the socket will be # closed, so report the BYE now. self._check_bye() # Some have reported "unexpected response" exceptions. # Note that ignoring them here causes loops. # Instead, send me details of the unexpected response and # I'll update the code in `_get_response()'. try: self._get_response() except self.abort as val: if __debug__: if self.debug >= 1: self.print_log() raise def _get_line(self): line = self.readline() if not line: raise self.abort('socket error: EOF') # Protocol mandates all lines terminated by CRLF if not line.endswith(b'\r\n'): raise self.abort('socket error: unterminated line: %r' % line) line = line[:-2] if __debug__: if self.debug >= 4: self._mesg('< %r' % line) else: self._log('< %r' % line) return line def _match(self, cre, s): # Run compiled regular expression match method on 's'. # Save result, return success. self.mo = cre.match(s) if __debug__: if self.mo is not None and self.debug >= 5: self._mesg("\tmatched r'%r' => %r" % (cre.pattern, self.mo.groups())) return self.mo is not None def _new_tag(self): tag = self.tagpre + bytes(str(self.tagnum), 'ASCII') self.tagnum = self.tagnum + 1 self.tagged_commands[tag] = None return tag def _quote(self, arg): arg = arg.replace('\\', '\\\\') arg = arg.replace('"', '\\"') return '"' + arg + '"' def _simple_command(self, name, *args): return self._command_complete(name, self._command(name, *args)) def _untagged_response(self, typ, dat, name): if typ == 'NO': return typ, dat if not name in self.untagged_responses: return typ, [None] data = self.untagged_responses.pop(name) if __debug__: if self.debug >= 5: self._mesg('untagged_responses[%s] => %s' % (name, data)) return typ, data if __debug__: def _mesg(self, s, secs=None): if secs is None: secs = time.time() tm = time.strftime('%M:%S', time.localtime(secs)) sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s)) sys.stderr.flush() def _dump_ur(self, dict): # Dump untagged responses (in `dict'). l = dict.items() if not l: return t = '\n\t\t' l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) self._mesg('untagged responses dump:%s%s' % (t, t.join(l))) def _log(self, line): # Keep log of last `_cmd_log_len' interactions for debugging. self._cmd_log[self._cmd_log_idx] = (line, time.time()) self._cmd_log_idx += 1 if self._cmd_log_idx >= self._cmd_log_len: self._cmd_log_idx = 0 def print_log(self): self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log)) i, n = self._cmd_log_idx, self._cmd_log_len while n: try: self._mesg(*self._cmd_log[i]) except: pass i += 1 if i >= self._cmd_log_len: i = 0 n -= 1 if HAVE_SSL: class IMAP4_SSL(IMAP4): """IMAP4 client class over SSL connection Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context]]]]]) host - host's name (default: localhost); port - port number (default: standard IMAP4 SSL port); keyfile - PEM formatted file that contains your private key (default: None); certfile - PEM formatted certificate chain file (default: None); ssl_context - a SSLContext object that contains your certificate chain and private key (default: None) Note: if ssl_context is provided, then parameters keyfile or certfile should not be set otherwise ValueError is raised. for more documentation see the docstring of the parent class IMAP4. """ def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None): if ssl_context is not None and keyfile is not None: raise ValueError("ssl_context and keyfile arguments are mutually " "exclusive") if ssl_context is not None and certfile is not None: raise ValueError("ssl_context and certfile arguments are mutually " "exclusive") self.keyfile = keyfile self.certfile = certfile if ssl_context is None: ssl_context = ssl._create_stdlib_context(certfile=certfile, keyfile=keyfile) self.ssl_context = ssl_context IMAP4.__init__(self, host, port) def _create_socket(self): sock = IMAP4._create_socket(self) server_hostname = self.host if ssl.HAS_SNI else None return self.ssl_context.wrap_socket(sock, server_hostname=server_hostname) def open(self, host='', port=IMAP4_SSL_PORT): """Setup connection to remote server on "host:port". (default: localhost:standard IMAP4 SSL port). This connection will be used by the routines: read, readline, send, shutdown. """ IMAP4.open(self, host, port) __all__.append("IMAP4_SSL") class IMAP4_stream(IMAP4): """IMAP4 client class over a stream Instantiate with: IMAP4_stream(command) where "command" is a string that can be passed to subprocess.Popen() for more documentation see the docstring of the parent class IMAP4. """ def __init__(self, command): self.command = command IMAP4.__init__(self) def open(self, host = None, port = None): """Setup a stream connection. This connection will be used by the routines: read, readline, send, shutdown. """ self.host = None # For compatibility with parent class self.port = None self.sock = None self.file = None self.process = subprocess.Popen(self.command, bufsize=DEFAULT_BUFFER_SIZE, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, close_fds=True) self.writefile = self.process.stdin self.readfile = self.process.stdout def read(self, size): """Read 'size' bytes from remote.""" return self.readfile.read(size) def readline(self): """Read line from remote.""" return self.readfile.readline() def send(self, data): """Send data to remote.""" self.writefile.write(data) self.writefile.flush() def shutdown(self): """Close I/O established in "open".""" self.readfile.close() self.writefile.close() self.process.wait() class _Authenticator: """Private class to provide en/decoding for base64-based authentication conversation. """ def __init__(self, mechinst): self.mech = mechinst # Callable object to provide/process data def process(self, data): ret = self.mech(self.decode(data)) if ret is None: return '*' # Abort conversation return self.encode(ret) def encode(self, inp): # # Invoke binascii.b2a_base64 iteratively with # short even length buffers, strip the trailing # line feed from the result and append. "Even" # means a number that factors to both 6 and 8, # so when it gets to the end of the 8-bit input # there's no partial 6-bit output. # oup = b'' if isinstance(inp, str): inp = inp.encode('ASCII') while inp: if len(inp) > 48: t = inp[:48] inp = inp[48:] else: t = inp inp = b'' e = binascii.b2a_base64(t) if e: oup = oup + e[:-1] return oup def decode(self, inp): if not inp: return b'' return binascii.a2b_base64(inp) Months = ' Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ') Mon2num = {s.encode():n+1 for n, s in enumerate(Months[1:])} def Internaldate2tuple(resp): """Parse an IMAP4 INTERNALDATE string. Return corresponding local time. The return value is a time.struct_time tuple or None if the string has wrong format. """ mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.group('sec')) zoneh = int(mo.group('zoneh')) zonem = int(mo.group('zonem')) # INTERNALDATE timezone must be subtracted to get UT zone = (zoneh*60 + zonem)*60 if zonen == b'-': zone = -zone tt = (year, mon, day, hour, min, sec, -1, -1, -1) utc = calendar.timegm(tt) - zone return time.localtime(utc) def Int2AP(num): """Convert integer to A-P string representation.""" val = b''; AP = b'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val = AP[mod:mod+1] + val return val def ParseFlags(resp): """Convert IMAP4 flags response to python tuple.""" mo = Flags.match(resp) if not mo: return () return tuple(mo.group('flags').split()) def Time2Internaldate(date_time): """Convert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time, an instance of time.struct_time (as returned by time.localtime()), an aware datetime instance or a double-quoted string. In the last case, it is assumed to already be in the correct format. """ if isinstance(date_time, (int, float)): dt = datetime.fromtimestamp(date_time, timezone.utc).astimezone() elif isinstance(date_time, tuple): try: gmtoff = date_time.tm_gmtoff except AttributeError: if time.daylight: dst = date_time[8] if dst == -1: dst = time.localtime(time.mktime(date_time))[8] gmtoff = -(time.timezone, time.altzone)[dst] else: gmtoff = -time.timezone delta = timedelta(seconds=gmtoff) dt = datetime(*date_time[:6], tzinfo=timezone(delta)) elif isinstance(date_time, datetime): if date_time.tzinfo is None: raise ValueError("date_time must be aware") dt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(Months[dt.month]) return dt.strftime(fmt) if __name__ == '__main__': # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]' # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"' # to test the IMAP4_stream class import getopt, getpass try: optlist, args = getopt.getopt(sys.argv[1:], 'd:s:') except getopt.error as val: optlist, args = (), () stream_command = None for opt,val in optlist: if opt == '-d': Debug = int(val) elif opt == '-s': stream_command = val if not args: args = (stream_command,) if not args: args = ('',) host = args[0] USER = getpass.getuser() PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost")) test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'} test_seq1 = ( ('login', (USER, PASSWD)), ('create', ('/tmp/xxx 1',)), ('rename', ('/tmp/xxx 1', '/tmp/yyy')), ('CREATE', ('/tmp/yyz 2',)), ('append', ('/tmp/yyz 2', None, None, test_mesg)), ('list', ('/tmp', 'yy*')), ('select', ('/tmp/yyz 2',)), ('search', (None, 'SUBJECT', 'test')), ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')), ('store', ('1', 'FLAGS', '(\Deleted)')), ('namespace', ()), ('expunge', ()), ('recent', ()), ('close', ()), ) test_seq2 = ( ('select', ()), ('response',('UIDVALIDITY',)), ('uid', ('SEARCH', 'ALL')), ('response', ('EXISTS',)), ('append', (None, None, None, test_mesg)), ('recent', ()), ('logout', ()), ) def run(cmd, args): M._mesg('%s %s' % (cmd, args)) typ, dat = getattr(M, cmd)(*args) M._mesg('%s => %s %s' % (cmd, typ, dat)) if typ == 'NO': raise dat[0] return dat try: if stream_command: M = IMAP4_stream(stream_command) else: M = IMAP4(host) if M.state == 'AUTH': test_seq1 = test_seq1[1:] # Login not needed M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) M._mesg('CAPABILITIES = %r' % (M.capabilities,)) for cmd,args in test_seq1: run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): mo = re.match(r'.*"([^"]+)"$', ml) if mo: path = mo.group(1) else: path = ml.split()[-1] run('delete', (path,)) for cmd,args in test_seq2: dat = run(cmd, args) if (cmd,args) != ('uid', ('SEARCH', 'ALL')): continue uid = dat[-1].split() if not uid: continue run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)')) print('\nAll tests OK.') except: print('\nTests failed.') if not Debug: print(''' If you would like to see debugging output, try: %s -d5 ''' % sys.argv[0]) raise
lgpl-3.0
kmdouglass/garg
garg.py
1
10495
"""GUI-based function argument assignment in pure Python. GARG reads a callable's signature and creates a GUI that allows users to interactively assign values to the callable's arguments. For security reasons, only positional-or-keyword and keyword-only parameters that accept basic Python datatypes are supported; all other parameters must be bound in the traditional way. Authors : Kyle M. Douglass Felix Schaber E-mail : kyle.m.douglass@gmail.com Year : 2017 License : MIT """ import inspect import sys import tkinter as tk from collections import OrderedDict from ast import literal_eval class Garg(): """Reads function parameters and assigns argument values using a GUI. Parameters ---------- func : function The function for which the parameter signature will be extracted. ignore_errors : bool Decides whether the program raises an error if arguments are not syntactically correct. If True, the program skips missing arguments and returns a partially bound argument list. Attributes ---------- ba : BoundArguments Argument values bound to the parameters specified in the GUI. model : Signature The input function's call signature. This is a Signature object from the standard library's inspect module and serves as the Model in the Model-View-Controller pattern. view : Frame The GUI presented to the user. ignore_syntax_errors : bool Decides whether the program raises an error if arguments are not syntactically correct. If True, the program skips incorrect arguments and returns a partially bound argument list. ignore_positional_only : bool Decides whether parameters that are POSITIONAL_ONLY are ignored by Garg. If True, the program skips these parameters and returns a partially bound argument list. """ _ARG_TYPES = ( inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY ) def __init__(self, func, ignore_syntax_errors=False, ignore_positional_only=False): self.root = tk.Tk() self.model = inspect.signature(func) self.view = View(self.root, self.on_ok_button, self.on_cancel_button) self.ba = None self.ignore_syntax_errors = ignore_syntax_errors self.ignore_positional_only = ignore_positional_only def get_arguments(self): """Returns the values of the arguments set in the GUI. Returns ------- params : OrderedDict Name/value pairs of parameter names and argument values in the same order as the input function's signature. """ view_params = self.view.get_args_dict() params = OrderedDict({}) # Build the parameter list to bind to arguments; assumes the parameter # list in the model is in the same order as the function signature. for param in self.model.parameters.values(): try: params[param.name] = literal_eval(view_params[param.name]) except SyntaxError: # Skip adding parameter to params if ignore_errors is True if not self.ignore_syntax_errors: raise(SyntaxError(('Parameter \"%s\"\'s argument %s is ' 'either not a valid Python literal or ' 'is unspecified.' % (param.name, view_params[param.name])))) except KeyError: # Skip parameters that are in the signature but not set by Garg if not self.ignore_positional_only: raise(KeyError(('Parameter \"%s\" is required by the ' 'callable but not capable of assignment ' 'by Garg.' % param.name))) except: print("Unexpected error:", sys.exc_info()[0]) raise return params def run(self): """Launches the main GUI window. """ self.root.title('GARG: GUI-Based Argument Assignment') self.root.deiconify() self.unpack_params() self.root.mainloop() def on_cancel_button(self): """Callback for the Cancel button. """ self.root.destroy() def on_ok_button(self): """Callback for the OK button. """ args = self.get_arguments() self.ba = self.model.bind_partial(**args) self.root.destroy() def unpack_params(self): """Extracts parameters from the signature and places them in the GUI. """ # TODO: Clean this up for arg_type in self._ARG_TYPES: group_exists = False for param in self.model.parameters.values(): if param.kind == arg_type: # Create new LabelFrame for this type if it doesn't exist if not group_exists: group = self.view.add_parameter_group( text=arg_type.name) group_exists = True # Add Label and Entry for this argument self.view.add_parameter_entry(group, param) class View(tk.Frame): """Displays a GUI interface for assigning values to function parameters. Parameters ---------- master : Tk The master Tk instance. on_ok : method OK button callback. on_cancel : method Cancel button callback. """ def __init__(self, master, on_ok, on_cancel): super().__init__(master) self._argdict = {} tk.Grid.rowconfigure(self.master, 0, weight=1) tk.Grid.rowconfigure(self.master, 1, weight=0) tk.Grid.columnconfigure(self.master, 0, weight=1) tk.Grid.columnconfigure(self.master, 1, weight=0) self._vsb = tk.Scrollbar(self.master, orient='vertical') self._canvas = tk.Canvas( self.master, width=400, height=300) self._buttonFrame = self.ButtonFrame(self.master,on_ok,on_cancel) # _group_frame is a single frame that is drawn onto the canvas. # It contains (possibly) multiple LabelFrames vertically stacked. self._group_frame = tk.Frame(self._canvas) self._canvas.create_window( (0, 0), window=self._group_frame, anchor='nw', tags=('frame')) self._canvas.configure(yscrollcommand=self._vsb.set) self._canvas.bind('<Configure>', self._on_canvas_resize) self._vsb.config(command=self._canvas.yview) self._canvas.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W) self._vsb.grid(row=0, column=1, sticky=tk.N+tk.S) self._buttonFrame.grid(row=1, columnspan=2) # Keeps track of the row number in a parameter group self._currRow = 0 def _on_canvas_resize(self, event=None): """Resizes the group frame when the canvas is resized. Parameters ---------- event : Event """ width = self._canvas.winfo_width() self._canvas.itemconfigure('frame', width=width) self._canvas.config(scrollregion=self._canvas.bbox('all')) def add_parameter_group(self, **kwargs): """Creates a LabelFrame to hold widgets for a single parameter type. Parameters ---------- **kwargs : dict Key/value pairs to pass to the LabelFrame constructor. Returns ------- lf : LabelFrame The container of Label and Entry widgets to set argument values. """ self._currRow = 0 lf = tk.LabelFrame(self._group_frame, **kwargs) lf.pack(fill=tk.BOTH, expand=1) return lf def add_parameter_entry(self, master, param): """Creates a Label and Entry for a single parameter. Parameters ---------- master : LabelFrame The parent frame containing the Label + Entry widgets. param : Parameter Parameter containing the information for populating the Entry and Label widgets. """ tk.Grid.columnconfigure(master, 0, weight=0) tk.Grid.columnconfigure(master, 1, weight=1) lb = tk.Label(master, text=param.name) box = tk.Entry(master) if param.default is not param.empty: # __repr__() ensures a Python literal is printed box.insert(0,param.default.__repr__()) # Keep a reference to get content of box later self._argdict[param.name] = box lb.grid(row=self._currRow, column=0, padx=10) box.grid(row=self._currRow, column=1, sticky=tk.E+tk.W) self._currRow += 1 def get_args_dict(self): """Creates a dict containing argument values specified in the GUI. Returns ------- args : dict Key/value pairs of parameter names and assigned argument values. """ args = {name : entry.get() for name, entry in self._argdict.items()} return args class ButtonFrame(tk.Frame): """Contains the OK and Cancel buttons. Parameters ---------- master : Tk The master Tk instance. on_ok : method OK button callback. on_cancel : method Cancel button callback. """ def __init__(self, master, on_ok, on_cancel): super().__init__(master) ok_button = tk.Button(master=self, text='OK' ,command=on_ok) cancel_button = tk.Button(master=self, text='Cancel',command=on_cancel) ok_button.pack(side=tk.LEFT) cancel_button.pack(side=tk.RIGHT) if __name__ == '__main__': def test(a, b, *, c, d=10, e='hello', f=[1, 2, 'hello', {'a': 2}], g=None): pass c = Garg(test) c.run() print(c.ba) print(c.ba.args) print(c.ba.kwargs)
mit
cvvnx1/nagweb
www/static/metronic1.4/admin/template_content_rtl/assets/plugins/jquery-file-upload/server/gae-python/main.py
223
5173
# -*- coding: utf-8 -*- # # jQuery File Upload Plugin GAE Python Example 2.0 # https://github.com/blueimp/jQuery-File-Upload # # Copyright 2011, Sebastian Tschan # https://blueimp.net # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # from __future__ import with_statement from google.appengine.api import files, images from google.appengine.ext import blobstore, deferred from google.appengine.ext.webapp import blobstore_handlers import json, re, urllib, webapp2 WEBSITE = 'http://blueimp.github.com/jQuery-File-Upload/' MIN_FILE_SIZE = 1 # bytes MAX_FILE_SIZE = 5000000 # bytes IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)') ACCEPT_FILE_TYPES = IMAGE_TYPES THUMBNAIL_MODIFICATOR = '=s80' # max width / height EXPIRATION_TIME = 300 # seconds def cleanup(blob_keys): blobstore.delete(blob_keys) class UploadHandler(webapp2.RequestHandler): def initialize(self, request, response): super(UploadHandler, self).initialize(request, response) self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers[ 'Access-Control-Allow-Methods' ] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE' def validate(self, file): if file['size'] < MIN_FILE_SIZE: file['error'] = 'File is too small' elif file['size'] > MAX_FILE_SIZE: file['error'] = 'File is too big' elif not ACCEPT_FILE_TYPES.match(file['type']): file['error'] = 'Filetype not allowed' else: return True return False def get_file_size(self, file): file.seek(0, 2) # Seek to the end of the file size = file.tell() # Get the position of EOF file.seek(0) # Reset the file position to the beginning return size def write_blob(self, data, info): blob = files.blobstore.create( mime_type=info['type'], _blobinfo_uploaded_filename=info['name'] ) with files.open(blob, 'a') as f: f.write(data) files.finalize(blob) return files.blobstore.get_blob_key(blob) def handle_upload(self): results = [] blob_keys = [] for name, fieldStorage in self.request.POST.items(): if type(fieldStorage) is unicode: continue result = {} result['name'] = re.sub(r'^.*\\', '', fieldStorage.filename) result['type'] = fieldStorage.type result['size'] = self.get_file_size(fieldStorage.file) if self.validate(result): blob_key = str( self.write_blob(fieldStorage.value, result) ) blob_keys.append(blob_key) result['delete_type'] = 'DELETE' result['delete_url'] = self.request.host_url +\ '/?key=' + urllib.quote(blob_key, '') if (IMAGE_TYPES.match(result['type'])): try: result['url'] = images.get_serving_url( blob_key, secure_url=self.request.host_url\ .startswith('https') ) result['thumbnail_url'] = result['url'] +\ THUMBNAIL_MODIFICATOR except: # Could not get an image serving url pass if not 'url' in result: result['url'] = self.request.host_url +\ '/' + blob_key + '/' + urllib.quote( result['name'].encode('utf-8'), '') results.append(result) deferred.defer( cleanup, blob_keys, _countdown=EXPIRATION_TIME ) return results def options(self): pass def head(self): pass def get(self): self.redirect(WEBSITE) def post(self): if (self.request.get('_method') == 'DELETE'): return self.delete() result = {'files': self.handle_upload()} s = json.dumps(result, separators=(',',':')) redirect = self.request.get('redirect') if redirect: return self.redirect(str( redirect.replace('%s', urllib.quote(s, ''), 1) )) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s) def delete(self): blobstore.delete(self.request.get('key') or '') class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, key, filename): if not blobstore.get(key): self.error(404) else: # Cache for the expiration time: self.response.headers['Cache-Control'] =\ 'public,max-age=%d' % EXPIRATION_TIME self.send_blob(key, save_as=filename) app = webapp2.WSGIApplication( [ ('/', UploadHandler), ('/([^/]+)/([^/]+)', DownloadHandler) ], debug=True )
gpl-2.0
kpcyrd/cjdns
node_build/dependencies/libuv/build/gyp/test/win/gyptest-link-enable-uac.py
242
3382
#!/usr/bin/env python # Copyright 2013 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. """ Verifies that embedding UAC information into the manifest works. """ import TestGyp import sys from xml.dom.minidom import parseString if sys.platform == 'win32': import pywintypes import win32api import winerror RT_MANIFEST = 24 class LoadLibrary(object): """Context manager for loading and releasing binaries in Windows. Yields the handle of the binary loaded.""" def __init__(self, path): self._path = path self._handle = None def __enter__(self): self._handle = win32api.LoadLibrary(self._path) return self._handle def __exit__(self, type, value, traceback): win32api.FreeLibrary(self._handle) def extract_manifest(path, resource_name): """Reads manifest from |path| and returns it as a string. Returns None is there is no such manifest.""" with LoadLibrary(path) as handle: try: return win32api.LoadResource(handle, RT_MANIFEST, resource_name) except pywintypes.error as error: if error.args[0] == winerror.ERROR_RESOURCE_DATA_NOT_FOUND: return None else: raise test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('enable-uac.gyp', chdir=CHDIR) test.build('enable-uac.gyp', test.ALL, chdir=CHDIR) # The following binaries must contain a manifest embedded. test.fail_test(not extract_manifest(test.built_file_path( 'enable_uac.exe', chdir=CHDIR), 1)) test.fail_test(not extract_manifest(test.built_file_path( 'enable_uac_no.exe', chdir=CHDIR), 1)) test.fail_test(not extract_manifest(test.built_file_path( 'enable_uac_admin.exe', chdir=CHDIR), 1)) # Verify that <requestedExecutionLevel level="asInvoker" uiAccess="false" /> # is present. manifest = parseString(extract_manifest( test.built_file_path('enable_uac.exe', chdir=CHDIR), 1)) execution_level = manifest.getElementsByTagName('requestedExecutionLevel') test.fail_test(len(execution_level) != 1) execution_level = execution_level[0].attributes test.fail_test(not ( execution_level.has_key('level') and execution_level.has_key('uiAccess') and execution_level['level'].nodeValue == 'asInvoker' and execution_level['uiAccess'].nodeValue == 'false')) # Verify that <requestedExecutionLevel> is not in the menifest. manifest = parseString(extract_manifest( test.built_file_path('enable_uac_no.exe', chdir=CHDIR), 1)) execution_level = manifest.getElementsByTagName('requestedExecutionLevel') test.fail_test(len(execution_level) != 0) # Verify that <requestedExecutionLevel level="requireAdministrator" # uiAccess="true" /> is present. manifest = parseString(extract_manifest( test.built_file_path('enable_uac_admin.exe', chdir=CHDIR), 1)) execution_level = manifest.getElementsByTagName('requestedExecutionLevel') test.fail_test(len(execution_level) != 1) execution_level = execution_level[0].attributes test.fail_test(not ( execution_level.has_key('level') and execution_level.has_key('uiAccess') and execution_level['level'].nodeValue == 'requireAdministrator' and execution_level['uiAccess'].nodeValue == 'true')) test.pass_test()
gpl-3.0
thomas1206/WALinuxAgent
tests/azure_test.py
10
27548
#!/usr/bin/env python import os import sys import imp import json import time import pwd # waagent has no '.py' therefore create waagent module import manually. waagent=imp.load_source('waagent','waagent') from waagent import RunGetOutput, Run, LoggerInit """ Test waagent in azure using azure-cli Usage: ./azure_test.py --stable_vm_image b4590d9e3ed742e4a1d46e5424aa335e__openSUSE-12.3-v120 --source_disk "http://mystorage.blob.core.windows.net/vhds/my-suse2.vhd" --acct "<storage acct key>" --testname my-osuse --mount_point /mnt/disk --agent_path ../waagent --stable_vm_acct_name MyUserName --stable_vm_acct_pass 'myp455wd' --test_vm_acct_name MyUserName --test_vm_acct_pass 'myp455wd' --azure_location "East US" --part_num 1 --retries 20 --fstype scsi --test_vm_acct_cert /root/.ssh/myCert.pem --stable_vm_acct_cert /root/.ssh/myCert.pem --keep_test_vm_vhd no --teardown_test_vm always --prompt no azure_test --vm <stable vm name> --testname <testname> [--acct <storage account>] [--disk <vhd url to use as initial disk image>] If --disk is specified, use this vhd as starting point, otherwise use a copy of the stable vm as the starting vhd. Starting VHD is attached to stable vm and the sources are copied to it. Spin up a new VM using the VHD. Loop waiting for provisioned. If not provisioned: Destroy vm and attach the disk to the stable vm. Copy the logs to the localhost. Destroy all created objects except the starting vhd. Exit(1) If Provosioned: Copy the logs to the local host. Exit(0) EXAMPLE: sudo ./azure_test.py --vm my-stable-vm-name --disk "http://mystorageaccount.blob.core.windows.net/myvhds/my-new-os.vhd" --acct mylong-unquoted-starage-account-id --testname my-vm-test --mount_point /my-stablevm-mountpoint --agent_path ../waagent --vm_acct_name root --testvm_acct_name azureuser --testvm_acct_pass 'azureuserpassword' --location "East US" --part_num 2 --retry 20 --fstype bsd --testvm_acct_cert /home/azureuser/.ssh/myCert.pem --keep_vhd "once" --teardown "always" --prompt "no" """ def makeDiskImage(di_name,vhd_url,location,copy=False): """ Create new data disk image of the VHD. If 'copy' is set to True, then create a new VHD in the form of myvhd-di.vhd based on the VHD source name. If 'copy is set to False, re-use the vhd. Returns return code and diskimageVHD path. Code is 0 on success or the azure-cli error code upon error. """ if copy : target = os.path.dirname(vhd_url) target = target+ '/' + di_name + '.vhd' else : target = vhd_url cmd='azure vm disk create --json ' + di_name + ' --blob-url ' + target + ' ' + vhd_url print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log(output) waagent.Log(str(code)) return target,code def makeVMImage(vmi_name,vhd_url,copy=False): """ Create new VM Image based on Disk Image. Returns 0 on success or error code upon error. """ if copy : target = os.path.dirname(vhd_url) target = target+ '/' + vmi_name + '.vhd' else : target = vhd_url cmd='azure vm image create --json ' + vmi_name + ' --base-vhd ' + target + ' --os Linux --blob-url ' + vhd_url print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log(str(code)) waagent.Log(output) return code def makeVM(vm_name,vmi_name,vhd_url,test_name,location,vmuser_name,vmuser_pass,vmuser_cert,copy=False): """ Create new VM from the VM Image. Returns 0 on success or error code upon error. """ target=os.path.dirname(vhd_url) target = target + '/' + test_name + '.vhd' cmd='azure vm create --json ' if copy : cmd += ' --blob-url "' + target + '"' else : target=vhd_url cmd += ' --location "' + location + '"' if os.path.exists(vmuser_cert): cmd += ' -t "' + vmuser_cert + '"' cmd += ' -e 22 ' + vm_name + ' ' + vmi_name + ' ' + vmuser_name + ' \'' +vmuser_pass + '\'' print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log(str(code)) waagent.Log(output) retry=3 while code !=0 and retry > 0 : time.sleep(5) code,output=RunGetOutput(cmd,False) retry -=1 return target def flushDiskImage(di_name,dele=True): """ Delete the VM Image. On error we asume the VM disk image is deleted """ cmd='azure vm disk delete --json ' if dele : cmd += '--blob-delete ' cmd+= di_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def flushVMImage(vmi_name): """ Delete the VM Image. Always delete the underlying blob. On error we asume the VM image is deleted. """ cmd='azure vm image delete --blob-delete --json ' + vmi_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def flushVM(vm_name,dele=False): """ Delete the VM. On error we asume the VM is deleted """ cmd='azure vm delete --json ' if dele : cmd += ' --blob-delete ' cmd += vm_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def createStableVMFromVMImage(vm_image,vhd_url): """ Create a new stable vm, provisioned with acct and certificate from the VMImage, using the basepath of vhd_url for the new VM's vhd. """ stableVM=testname+'-stable-vm' return makeVM(stableVM,vm_image,vhd_url,testname+'-stable',location,stableVMaccount,stableVMpass,stableVMCert,copy=True) def createStableVMFromVHD(vmi_name,vhd_url): """ Create a new stable vm, provisioned with acct and certificate from the VHD, using the basepath of vhd_url for the new VM's vhd. """ makeVMImage(vmi_name,vhd_url,False) return createStableVMFromVMImage(vmi_name,vhd_url) def createDiskImageFromStableVMDisk(vm_name): """ Determine the media link for the os disk of the stable vm. Create vhd disk image copy. <vm_name>-<testname>-di Return new disk_image_media_path or None on error. """ cmd='azure vm disk list --json' print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) if code: print 'Error is ' + str(code) waagent.Log( 'Error is ' + str(code)) return None j=json.loads(output) source_media_link=None for i in j : if i.has_key('AttachedTo'): if i['AttachedTo']['RoleName'] == vm_name: source_media_link=i['MediaLink'] break if not source_media_link: print 'Unable to locate OS disk for ' + vm_name waagent.Log( 'Unable to locate OS disk for ' + vm_name ) return None target_name= testname + '-di' makeDiskImage(target_name,source_media_link,location,copy=True) target_media_link=os.path.dirname(source_media_link) + '/' + target_name + '.vhd' return target_media_link def addDiskImageToVM(vm_name,di_name): """ Attach the disk image to the 'stableVM'. Returns the LUN if successful otherwise returns None NOTE: azure vm show may return json matching the disk image name yet missing the LUN. When this occurs, the LUN is '0'. """ cmd='azure vm disk attach --json ' + vm_name + ' ' + di_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log(str(code)) waagent.Log(output) cmd='azure vm show --json ' + vm_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) retries=3 while code != 0 and retries: retries-=1 print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) if code == 0: jsn=json.loads(output) for i in jsn['DataDisks']: if i['DiskName'] == di_name: if 'Lun' in i : return i['Lun'] else : return u'0' return None def dropDiskImageFromVM(vm_name,lun): """ Detach the disk image from the 'stableVM'. On Error we assume the disk is no longer attached. """ cmd='azure vm disk detach --json ' + vm_name + ' ' + lun print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def checkVMProvisioned(vm_name): cmd='azure vm show --json ' + vm_name print cmd waagent.Log( cmd) code,output=RunGetOutput(cmd,False) print output,code waagent.Log( str(code)) waagent.Log(output) if code ==0 : j=json.loads(output) print vm_name+' instance status: ', j['InstanceStatus'] waagent.Log( vm_name+' instance status: ' + j['InstanceStatus']) if j['InstanceStatus'] == 'ReadyRole': return True, j['InstanceStatus'] else : print 'Error: ' + output , code waagent.Log( 'Error: ' + output + str(code)) return False, j['InstanceStatus'] def updateAgent(agent_path,vm_name,account,cert,disk_mountpoint,mnt_opts,lun,partnum,provisioned_account): """ Copy the agent specified in 'agent' to the Disk using the 'stableVM'. """ retries=30 retry=0 cmd='uptime' while ssh_command(vm_name,account,cmd)[1] != 0 and retry < retries : time.sleep(10) retry+=1 #setup sudo NOPASSWD pss=stableVMpass.replace('$','\$') cmd='echo \'' + pss + '\' > /home/' + account + '/pswd ' ssh_command(vm_name,account,cmd) cmd='echo \'#!/bin/bash\ncat /home/' + account + '/pswd\n\' > /home/' + account + '/pw.sh' ssh_command(vm_name,account,cmd) cmd='chmod +x /home/' + account + '/pw.sh' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A mkdir -p ' + disk_mountpoint ssh_command(vm_name,account,cmd) retries=3 # TODO retires here for the mount #mount cmd='export SUDO_ASKPASS=./pw.sh && sudo -A mount ' +mnt_opts + ' ' + lunToDiskName(lun,partnum) + ' ' +disk_mountpoint waagent.Log( cmd) retry=0 while ssh_command(vm_name,account,cmd)[1] not in (0,32) and retry < retries : if retry == 0: if 'bsd' in fstype: fcmd = "export SUDO_ASKPASS=./pw.sh && sudo -A fsck_ffs -y " else : fcmd = "export SUDO_ASKPASS=./pw.sh && sudo -A fsck -y " fcmd += lunToDiskName(lun,partnum) ssh_command(vm_name,account,fcmd) time.sleep(2) retry+=1 # remove packaged agent service if present. cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' dpkg -r walinuxagent' ssh_command(vm_name,account,cmd) # remove Ubuntu walinuxagent agent service if present. cmd='export SUDO_ASKPASS=./pw.sh && sudo -A rm '+ disk_mountpoint+'/etc/default/walinuxagent' ssh_command(vm_name,account,cmd) # remove Ubuntu walinuxagent agent service if present. cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' rpm -e WALinuxAgent' ssh_command(vm_name,account,cmd) #copy agent remote_path='/tmp' print 'scp ' + agent_path + ' to ' + vm_name + ' ' + account + ':' + remote_path waagent.Log( 'scp ' + agent_path + ' to ' + vm_name + ' ' + account + ':' + remote_path) retry=0 while scp_to_host_command(account,vm_name,remote_path,agent_path)[1] != 0 and retry < retries : time.sleep(2) retry+=1 # move agent to /usr/sbin cmd= 'export SUDO_ASKPASS=./pw.sh && sudo -A cp ' + remote_path +'/waagent '+ disk_mountpoint+'/usr/sbin/waagent' ssh_command(vm_name,account,cmd) cmd= 'export SUDO_ASKPASS=./pw.sh && sudo -A chmod 755 '+ disk_mountpoint+'/usr/sbin/waagent' ssh_command(vm_name,account,cmd) # Fix the password file if 'bsd' in fstype: cmd='export SUDO_ASKPASS=./pw.sh && sudo -A cp /etc/master.passwd ' + disk_mountpoint + '/etc/master.passwd' ssh_command(vm_name,account,cmd) else : cmd='export SUDO_ASKPASS=./pw.sh && sudo -A cp /etc/passwd ' + disk_mountpoint + '/etc/passwd' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A cp /etc/shadow ' + disk_mountpoint + '/etc/shadow' ssh_command(vm_name,account,cmd) #remove /var/lib/waagent cmd='export SUDO_ASKPASS=./pw.sh && sudo -A rm -rf ' + disk_mountpoint + '/var/lib/waagent' ssh_command(vm_name,account,cmd) #remove /var/log/waagent* cmd='export SUDO_ASKPASS=./pw.sh && sudo -A rm -rf ' + disk_mountpoint + '/var/log/waagent*' ssh_command(vm_name,account,cmd) #delete the provisioning user if 'bsd' in fstype: cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' rmuser -y ' + provisioned_account ssh_command(vm_name,account,cmd) else : cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' userdel -f ' + provisioned_account ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' groupdel ' + provisioned_account ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A rm -rf ' + disk_mountpoint + '/home/' + provisioned_account ssh_command(vm_name,account,cmd) # install agent cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chroot '+ disk_mountpoint+' /usr/sbin/waagent verbose install ' ssh_command(vm_name,account,cmd) cmd="export SUDO_ASKPASS=./pw.sh && sudo -A sed -i 's/Verbose=n/Verbose=y/' " + disk_mountpoint+"/etc/waagent.conf" ssh_command(vm_name,account,cmd) #umount cmd='export SUDO_ASKPASS=./pw.sh && sudo -A umount ' + lunToDiskName(lun,partnum) ssh_command(vm_name,account,cmd) def gatherAgentInfo(localpath,vm_name,account,cert,disk_mountpoint,mnt_opts,lun,partnum): """ Copy the /var/lib/waagent, and /var/log directories to localhost:localpath. """ retries=30 retry=0 cmd='uptime' while ssh_command(vm_name,account,cmd)[1] != 0 and retry < retries : time.sleep(10) retry+=1 #mount cmd='export SUDO_ASKPASS=./pw.sh && sudo -A mount ' +mnt_opts + ' ' + lunToDiskName(lun,partnum) + ' ' +disk_mountpoint print cmd waagent.Log( cmd) ssh_command(vm_name,account,cmd) #copy info Run("mkdir -p "+ localpath) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A mkdir -p /tmp/results' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A cp -r ' + disk_mountpoint + '/var/log /tmp/results/' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A cp -r ' + disk_mountpoint + '/var/lib/waagent /tmp/results/' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chmod -R 777 /tmp/results' ssh_command(vm_name,account,cmd) cmd='export SUDO_ASKPASS=./pw.sh && sudo -A chown -R ' + account + ' /tmp/results' ssh_command(vm_name,account,cmd) scp_from_host_command(account,vm_name,'/tmp/results/*',localpath) #umount cmd='export SUDO_ASKPASS=./pw.sh && sudo -A umount ' + lunToDiskName(lun,partnum) print cmd waagent.Log( cmd) ssh_command(vm_name,account,cmd) def lunToDiskName(lun,partnum): if 'bsd' in fstype : return lunToFreeBSDDiskName(lun,partnum) else : return lunToScsiDiskName(lun,partnum) def lunToScsiDiskName(lun,partnum): """ Convert lun to '/dev/sd[chr(ord('c')+lun)]partnum' """ return str('/dev/sd'+chr( (ord('c')+int(lun)) ) +str(partnum)) def lunToFreeBSDDiskName(lun,partnum): """ Convert lun to '/dev/da' + str(lun) + 'p' + partnum """ return '/dev/da'+ str(int(lun)) + 'p' + str(partnum) def ssh_command(host,account,cmd): """ Wrapper for an ssh operation. """ if stableVMCert == None: if not os.path.exists('./pw.sh'): with open('./pw.sh','w') as F: F.write('#!/bin/bash\ncat ./pswd\n') os.system('chmod +x ./pw.sh') with open('./pswd','w') as F: F.write(stableVMpass) req = "export SSH_ASKPASS=./pw.sh && setsid ssh -T -o StrictHostKeyChecking='no' " + account + "@" + host.lower() + ".cloudapp.net \"" + cmd + "\"" else : req = "ssh -t -o StrictHostKeyChecking='no' " + account + "@" + host.lower() + ".cloudapp.net \"" + cmd + "\"" print req waagent.Log(req) code,output=RunGetOutput(req,False) print output,code waagent.Log(str(code)) waagent.Log(output.encode('ascii','ignore')) return output,code def scp_to_host_command(account,host,remote_path,local_path): """ Wrapper for an scp operation. Always uses -r. Requires key authentication configured. """ req="scp -o StrictHostKeyChecking='no' -r " + local_path + " " + account + "@" + host.lower() + ".cloudapp.net:" + remote_path print req waagent.Log( req) code,output=RunGetOutput(req,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def scp_from_host_command(account,host,remote_path,local_path): """ Wrapper for an scp operation. Always uses -r. Requires key authentication configured. """ req="scp -r " + account + "@" + host.lower() + ".cloudapp.net:" + remote_path + " " + local_path print req waagent.Log( req) code,output=RunGetOutput(req,False) print output,code waagent.Log( str(code)) waagent.Log(output) return output,code def teardown(name): diskImageName=os.path.splitext(os.path.basename(sourceVHD))[0]+'-di' while makeDiskImage(diskImageName,sourceVHD,location,True)[1] !=0 : time.sleep(20) lun=addDiskImageToVM(stableVM,diskImageName) while lun == None : time.sleep(2) lun=addDiskImageToVM(stableVM,diskImageName) out,code=flushVM(vmName,True) if code != 0 : vmDisk=out[out.find('disk with name ')+len('disk with name '):out.find(' is currently in use')] while flushDiskImage(vmDisk,True)[1] != 0 : time.sleep(5) out,code=flushVMImage(vmImageName) if code != 0 : vmDisk=out[out.find('disk with name ')+len('disk with name '):out.find(' is currently in use')] while flushDiskImage(vmDisk,True)[1] != 0 : time.sleep(5) gatherAgentInfo(localInfo+'/'+name,stableVM,stableVMaccount,stableVMCert,stableVMMountpoint,mountOptions,lun,partNum) print 'Logs for ' + vmName + ' copied to ' + localInfo + '/' + name waagent.Log( 'Logs for ' + vmName + ' copied to ' + localInfo + '/' + name) # detach and delete the disk image while dropDiskImageFromVM(stableVM,lun)[1] != 0 : time.sleep(2) while flushDiskImage(diskImageName,('no' in keep_vhd))[1] != 0 : time.sleep(2) out,code=flushVM(stableVM,True) if code != 0 : stableVMDisk=out[out.find('disk with name ')+len('disk with name '):out.find(' is currently in use')] while flushDiskImage(stableVMDisk,True)[1] != 0 : time.sleep(5) if stableVMImageName: while flushVMImage(stableVMImageName,True)[1] != 0 : time.sleep(2) def doPrompt() : if prompt in ('yes','on'): raw_input('Press enter to continue:') if __name__ == '__main__' : """ Create a disk image and attach it to StableVM. Copy the current sources to it. Detach and delete the disk image container Delete the vm image container and the VM. Create a vm image container, and the VM. Check the VM for provision succedded: if so, exit if provisioning failed: delete the vm, delete the vm image, create a disk image from the VM's vhd, attach the disk to the stable VM, copy /var/log and /var/lib/waagent to the localhost. """ stableVM='' mountOptions='' stableVMMountpoint='/mnt/disk' # need to ensure this is created if not existing. sourceVHD='' location="" localAgent='/home/ericg/Public/git_repos/private/WALinuxAgent-Private/waagent_freebsd' localInfo='./logs' stableVMaccount='' # Need to ensure root permissions for this to work stableVMpass='' stableVMCert='' provisionedVMaccount='' provisionedVMpass='' provisionedVMCert='' account='' testname='azuretest' partNum=1 provision_retries=1 fstype='scsi' keep_vhd='no' teardown_test_vm='fail' teardown_stable_vm='fail' prompt = 'yes' stable_vm_vhd=None stableVMImageName=None stable_vm_image=None logfile='azure_test.log' """ We need to create a disk image container and attach it to a stable vm in order to copy the current sources to it. Then we detach it, delete the disk image container, create a vm image container, and the VM. """ for i in range(len(sys.argv)) : if '--stable_vm' == sys.argv[i] : stableVM=sys.argv[i+1] elif '--source_disk' == sys.argv[i]: sourceVHD=sys.argv[i+1] elif '--storage_acct' == sys.argv[i]: account=sys.argv[i+1] elif '--testname' == sys.argv[i] : testname=sys.argv[i+1] elif '--stable_vm_mount_point' == sys.argv[i] : stableVMMountpoint=sys.argv[i+1] elif '--agent_path' == sys.argv[i] : localAgent=sys.argv[i+1] elif '--stable_vm_acct_name' == sys.argv[i] : stableVMaccount=sys.argv[i+1] elif '--stable_vm_acct_pass' == sys.argv[i] : stableVMpass=sys.argv[i+1] elif '--stable_vm_acct_cert' == sys.argv[i] : stableVMCert=sys.argv[i+1] elif '--test_vm_acct_name' == sys.argv[i] : provisionedVMaccount=sys.argv[i+1] elif '--test_vm_acct_pass' == sys.argv[i] : provisionedVMpass=sys.argv[i+1] elif '--test_vm_acct_cert' == sys.argv[i] : provisionedVMCert=sys.argv[i+1] elif '--azure_location' == sys.argv[i] : location=sys.argv[i+1] elif '--mount_opts' == sys.argv[i] : mountOptions=sys.argv[i+1] elif '--part_num' == sys.argv[i] : partNum=sys.argv[i+1] elif '--retries' == sys.argv[i] : provision_retries=int(sys.argv[i+1]) elif '--fs_type' == sys.argv[i] : fstype=sys.argv[i+1] elif '--keep_test_vm_vhd' == sys.argv[i] : keep_vhd=sys.argv[i+1] elif '--teardown_test_vm' == sys.argv[i] : teardown_test_vm=sys.argv[i+1] elif '--teardown_stable_vm' == sys.argv[i] : teardown_stable_vm=sys.argv[i+1] elif '--prompt' == sys.argv[i] : prompt=sys.argv[i+1] elif '--stable_vm_image' == sys.argv[i] : stable_vm_image=sys.argv[i+1] elif '--stable_vm_vhd' == sys.argv[i] : stable_vm_vhd=sys.argv[i+1] elif '--logfile' == sys.argv[i] : logfile=sys.argv[i+1] LoggerInit(logfile,'') waagent.Log("User: "+ pwd.getpwuid(os.geteuid()).pw_name +" Running Command :\n" + reduce(lambda x, y: x+' '+y,sys.argv)) if len(stableVM) == 0 and not ( stable_vm_image or stable_vm_vhd ): print '--vm <stable vm> must be provided unless --stable_vm_image or --stable_vm_vhd' waagent.Log( '--vm <stable vm> must be provided!') sys.exit(1) else: if stable_vm_image: sourceVHD=createStableVMFromVMImage(stable_vm_image,sourceVHD) stableVM=testname+'-stable-vm' elif stable_vm_vhd: stableVMImageName=testname+'-stable-vi' sourceVHD=createStableVMFromVHD(stableVMImageName,stable_vm_vhd) stableVM=testname+'-stable-vm' p = False retries = provision_retries while not p and retries > 0: p,out = checkVMProvisioned(stableVM) if not p: if 'Failed' in out or 'Timeout' in out : break print stableVM + ' Not Provisioned - sleeping on retry:' + str( provision_retries - retries ) waagent.Log( stableVM + ' Not Provisioned - sleeping on retry:' + str( provision_retries - retries ) ) time.sleep(30) retries -= 1 else : print stableVM + ' Provision SUCCEEDED.' waagent.Log( stableVM + ' Provision SUCCEEDED.') # done creating the stable vm vmImageName=os.path.splitext(os.path.basename(sourceVHD))[0]+'-vi' #flushVMImage(vmImageName) # if no disk image name is provided we want to clone the stable vm disk. if not sourceVHD: sourceVHD=createDiskImageFromStableVMDisk(stableVM) if not sourceVHD: print 'Errors - unable to create disk image - assuming created' waagent.Log( 'Errors - unable to create disk image - assuming created') diskImageName=os.path.splitext(os.path.basename(sourceVHD))[0] else : diskImageName=os.path.splitext(os.path.basename(sourceVHD))[0]+'-di' diskImageVHD,code=makeDiskImage(diskImageName,sourceVHD,location,True) if code: print 'Error - unable to make ' + diskImageName waagent.Log( 'Error - unable to make ' + diskImageName) lun=addDiskImageToVM(stableVM,diskImageName) while lun == None : time.sleep(2) lun=addDiskImageToVM(stableVM,diskImageName) doPrompt() updateAgent(localAgent,stableVM,stableVMaccount,stableVMCert,stableVMMountpoint,mountOptions,lun,partNum,provisionedVMaccount) doPrompt() #reboot to prevent stale mount bugs cmd= 'export SUDO_ASKPASS=./pw.sh && sudo -A reboot' ssh_command(stableVM,stableVMaccount,cmd) while dropDiskImageFromVM(stableVM,lun)[1] != 0 : time.sleep(2) while flushDiskImage(diskImageName,False)[1] != 0 : time.sleep(2) vmImageName=os.path.splitext(os.path.basename(sourceVHD))[0]+'-vi' flushVMImage(vmImageName) vmName=testname+'-vm' flushVM(vmName) makeVMImage(vmImageName,diskImageVHD,True) sourceVHD=makeVM(vmName,vmImageName,sourceVHD,testname,location,provisionedVMaccount,provisionedVMpass,provisionedVMCert,True) print 'The new source vhd is ' + sourceVHD waagent.Log( 'The new source vhd is ' + sourceVHD) p = False retries = provision_retries while not p and retries > 0: p,out = checkVMProvisioned(vmName) if not p: if 'Failed' in out or 'Timeout' in out : break print vmName + ' Not Provisioned - sleeping on retry:' + str( provision_retries - retries ) waagent.Log( vmName + ' Not Provisioned - sleeping on retry:' + str( provision_retries - retries ) ) time.sleep(30) else : print vmName + ' Provision SUCCEEDED.' waagent.Log( vmName + ' Provision SUCCEEDED.') doPrompt() if teardown_test_vm in ('success','always'): teardown(testname+'_pass') sys.exit(0) retries -= 1 print vmName + ' Provision FAILED.' waagent.Log( vmName + ' Provision FAILED.') doPrompt() if teardown_test_vm in ('fail','always'): teardown(testname+'_fail') sys.exit(1)
apache-2.0
Chilledheart/vbox
src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/Ecc/Ecc.py
11
17434
## @file # This file is used to be the main entrance of ECC tool # # Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # import os, time, glob, sys import Common.EdkLogger as EdkLogger import Database import EccGlobalData from MetaDataParser import * from optparse import OptionParser from Configuration import Configuration from Check import Check import Common.GlobalData as GlobalData from Common.String import NormPath from Common.BuildVersion import gBUILD_VERSION from Common import BuildToolError from Common.Misc import PathClass from Common.Misc import DirCache from MetaFileWorkspace.MetaFileParser import DscParser from MetaFileWorkspace.MetaFileParser import DecParser from MetaFileWorkspace.MetaFileParser import InfParser from MetaFileWorkspace.MetaFileParser import Fdf from MetaFileWorkspace.MetaFileTable import MetaFileStorage import c import re, string from Exception import * ## Ecc # # This class is used to define Ecc main entrance # # @param object: Inherited from object class # class Ecc(object): def __init__(self): # Version and Copyright self.VersionNumber = ("0.01" + " " + gBUILD_VERSION) self.Version = "%prog Version " + self.VersionNumber self.Copyright = "Copyright (c) 2009 - 2010, Intel Corporation All rights reserved." self.InitDefaultConfigIni() self.OutputFile = 'output.txt' self.ReportFile = 'Report.csv' self.ExceptionFile = 'exception.xml' self.IsInit = True self.ScanSourceCode = True self.ScanMetaData = True self.MetaFile = '' # Parse the options and args self.ParseOption() # # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP # WorkspaceDir = os.path.normcase(os.path.normpath(os.environ["WORKSPACE"])) os.environ["WORKSPACE"] = WorkspaceDir if "ECP_SOURCE" not in os.environ: os.environ["ECP_SOURCE"] = os.path.join(WorkspaceDir, GlobalData.gEdkCompatibilityPkg) if "EFI_SOURCE" not in os.environ: os.environ["EFI_SOURCE"] = os.environ["ECP_SOURCE"] if "EDK_SOURCE" not in os.environ: os.environ["EDK_SOURCE"] = os.environ["ECP_SOURCE"] # # Unify case of characters on case-insensitive systems # EfiSourceDir = os.path.normcase(os.path.normpath(os.environ["EFI_SOURCE"])) EdkSourceDir = os.path.normcase(os.path.normpath(os.environ["EDK_SOURCE"])) EcpSourceDir = os.path.normcase(os.path.normpath(os.environ["ECP_SOURCE"])) os.environ["EFI_SOURCE"] = EfiSourceDir os.environ["EDK_SOURCE"] = EdkSourceDir os.environ["ECP_SOURCE"] = EcpSourceDir GlobalData.gWorkspace = WorkspaceDir GlobalData.gEfiSource = EfiSourceDir GlobalData.gEdkSource = EdkSourceDir GlobalData.gEcpSource = EcpSourceDir GlobalData.gGlobalDefines["WORKSPACE"] = WorkspaceDir GlobalData.gGlobalDefines["EFI_SOURCE"] = EfiSourceDir GlobalData.gGlobalDefines["EDK_SOURCE"] = EdkSourceDir GlobalData.gGlobalDefines["ECP_SOURCE"] = EcpSourceDir # Generate checkpoints list EccGlobalData.gConfig = Configuration(self.ConfigFile) # Generate exception list EccGlobalData.gException = ExceptionCheck(self.ExceptionFile) # Init Ecc database EccGlobalData.gDb = Database.Database(Database.DATABASE_PATH) EccGlobalData.gDb.InitDatabase(self.IsInit) # # Get files real name in workspace dir # GlobalData.gAllFiles = DirCache(GlobalData.gWorkspace) # Build ECC database self.BuildDatabase() # Start to check self.Check() # Show report self.GenReport() # Close Database EccGlobalData.gDb.Close() def InitDefaultConfigIni(self): paths = map(lambda p: os.path.join(p, 'Ecc', 'config.ini'), sys.path) paths = (os.path.realpath('config.ini'),) + tuple(paths) for path in paths: if os.path.exists(path): self.ConfigFile = path return self.ConfigFile = 'config.ini' ## BuildDatabase # # Build the database for target # def BuildDatabase(self): # Clean report table EccGlobalData.gDb.TblReport.Drop() EccGlobalData.gDb.TblReport.Create() # Build database if self.IsInit: if self.ScanMetaData: EdkLogger.quiet("Building database for Meta Data File ...") self.BuildMetaDataFileDatabase() if self.ScanSourceCode: EdkLogger.quiet("Building database for Meta Data File Done!") c.CollectSourceCodeDataIntoDB(EccGlobalData.gTarget) EccGlobalData.gIdentifierTableList = GetTableList((MODEL_FILE_C, MODEL_FILE_H), 'Identifier', EccGlobalData.gDb) EccGlobalData.gCFileList = GetFileList(MODEL_FILE_C, EccGlobalData.gDb) EccGlobalData.gHFileList = GetFileList(MODEL_FILE_H, EccGlobalData.gDb) ## BuildMetaDataFileDatabase # # Build the database for meta data files # def BuildMetaDataFileDatabase(self): EdkLogger.quiet("Building database for meta data files ...") Op = open(EccGlobalData.gConfig.MetaDataFileCheckPathOfGenerateFileList, 'w+') #SkipDirs = Read from config file SkipDirs = EccGlobalData.gConfig.SkipDirList SkipDirString = string.join(SkipDirs, '|') p = re.compile(r'.*[\\/](?:%s)[\\/]?.*' % SkipDirString) for Root, Dirs, Files in os.walk(EccGlobalData.gTarget): if p.match(Root.upper()): continue for Dir in Dirs: Dirname = os.path.join(Root, Dir) if os.path.islink(Dirname): Dirname = os.path.realpath(Dirname) if os.path.isdir(Dirname): # symlinks to directories are treated as directories Dirs.remove(Dir) Dirs.append(Dirname) for File in Files: if len(File) > 4 and File[-4:].upper() == ".DEC": Filename = os.path.normpath(os.path.join(Root, File)) EdkLogger.quiet("Parsing %s" % Filename) Op.write("%s\r" % Filename) #Dec(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb) self.MetaFile = DecParser(Filename, MODEL_FILE_DEC, EccGlobalData.gDb.TblDec) self.MetaFile.Start() continue if len(File) > 4 and File[-4:].upper() == ".DSC": Filename = os.path.normpath(os.path.join(Root, File)) EdkLogger.quiet("Parsing %s" % Filename) Op.write("%s\r" % Filename) #Dsc(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb) self.MetaFile = DscParser(PathClass(Filename, Root), MODEL_FILE_DSC, MetaFileStorage(EccGlobalData.gDb.TblDsc.Cur, Filename, MODEL_FILE_DSC, True)) # alwasy do post-process, in case of macros change self.MetaFile.DoPostProcess() self.MetaFile.Start() self.MetaFile._PostProcess() continue if len(File) > 4 and File[-4:].upper() == ".INF": Filename = os.path.normpath(os.path.join(Root, File)) EdkLogger.quiet("Parsing %s" % Filename) Op.write("%s\r" % Filename) #Inf(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb) self.MetaFile = InfParser(Filename, MODEL_FILE_INF, EccGlobalData.gDb.TblInf) self.MetaFile.Start() continue if len(File) > 4 and File[-4:].upper() == ".FDF": Filename = os.path.normpath(os.path.join(Root, File)) EdkLogger.quiet("Parsing %s" % Filename) Op.write("%s\r" % Filename) Fdf(Filename, True, EccGlobalData.gWorkspace, EccGlobalData.gDb) continue Op.close() # Commit to database EccGlobalData.gDb.Conn.commit() EdkLogger.quiet("Building database for meta data files done!") ## # # Check each checkpoint # def Check(self): EdkLogger.quiet("Checking ...") EccCheck = Check() EccCheck.Check() EdkLogger.quiet("Checking done!") ## # # Generate the scan report # def GenReport(self): EdkLogger.quiet("Generating report ...") EccGlobalData.gDb.TblReport.ToCSV(self.ReportFile) EdkLogger.quiet("Generating report done!") def GetRealPathCase(self, path): TmpPath = path.rstrip(os.sep) PathParts = TmpPath.split(os.sep) if len(PathParts) == 0: return path if len(PathParts) == 1: if PathParts[0].strip().endswith(':'): return PathParts[0].upper() # Relative dir, list . current dir Dirs = os.listdir('.') for Dir in Dirs: if Dir.upper() == PathParts[0].upper(): return Dir if PathParts[0].strip().endswith(':'): PathParts[0] = PathParts[0].upper() ParentDir = PathParts[0] RealPath = ParentDir if PathParts[0] == '': RealPath = os.sep ParentDir = os.sep PathParts.remove(PathParts[0]) # need to remove the parent for Part in PathParts: Dirs = os.listdir(ParentDir + os.sep) for Dir in Dirs: if Dir.upper() == Part.upper(): RealPath += os.sep RealPath += Dir break ParentDir += os.sep ParentDir += Dir return RealPath ## ParseOption # # Parse options # def ParseOption(self): EdkLogger.quiet("Loading ECC configuration ... done") (Options, Target) = self.EccOptionParser() if Options.Workspace: os.environ["WORKSPACE"] = Options.Workspace # Check workspace envirnoment if "WORKSPACE" not in os.environ: EdkLogger.error("ECC", BuildToolError.ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found", ExtraData="WORKSPACE") else: EccGlobalData.gWorkspace = os.path.normpath(os.getenv("WORKSPACE")) if not os.path.exists(EccGlobalData.gWorkspace): EdkLogger.error("ECC", BuildToolError.FILE_NOT_FOUND, ExtraData="WORKSPACE = %s" % EccGlobalData.gWorkspace) os.environ["WORKSPACE"] = EccGlobalData.gWorkspace # Set log level self.SetLogLevel(Options) # Set other options if Options.ConfigFile != None: self.ConfigFile = Options.ConfigFile if Options.OutputFile != None: self.OutputFile = Options.OutputFile if Options.ReportFile != None: self.ReportFile = Options.ReportFile if Options.ExceptionFile != None: self.ExceptionFile = Options.ExceptionFile if Options.Target != None: if not os.path.isdir(Options.Target): EdkLogger.error("ECC", BuildToolError.OPTION_VALUE_INVALID, ExtraData="Target [%s] does NOT exist" % Options.Target) else: EccGlobalData.gTarget = self.GetRealPathCase(os.path.normpath(Options.Target)) else: EdkLogger.warn("Ecc", EdkLogger.ECC_ERROR, "The target source tree was not specified, using current WORKSPACE instead!") EccGlobalData.gTarget = os.path.normpath(os.getenv("WORKSPACE")) if Options.keepdatabase != None: self.IsInit = False if Options.metadata != None and Options.sourcecode != None: EdkLogger.error("ECC", BuildToolError.OPTION_CONFLICT, ExtraData="-m and -s can't be specified at one time") if Options.metadata != None: self.ScanSourceCode = False if Options.sourcecode != None: self.ScanMetaData = False ## SetLogLevel # # Set current log level of the tool based on args # # @param Option: The option list including log level setting # def SetLogLevel(self, Option): if Option.verbose != None: EdkLogger.SetLevel(EdkLogger.VERBOSE) elif Option.quiet != None: EdkLogger.SetLevel(EdkLogger.QUIET) elif Option.debug != None: EdkLogger.SetLevel(Option.debug + 1) else: EdkLogger.SetLevel(EdkLogger.INFO) ## Parse command line options # # Using standard Python module optparse to parse command line option of this tool. # # @retval Opt A optparse.Values object containing the parsed options # @retval Args Target of build command # def EccOptionParser(self): Parser = OptionParser(description = self.Copyright, version = self.Version, prog = "Ecc.exe", usage = "%prog [options]") Parser.add_option("-t", "--target sourcepath", action="store", type="string", dest='Target', help="Check all files under the target workspace.") Parser.add_option("-c", "--config filename", action="store", type="string", dest="ConfigFile", help="Specify a configuration file. Defaultly use config.ini under ECC tool directory.") Parser.add_option("-o", "--outfile filename", action="store", type="string", dest="OutputFile", help="Specify the name of an output file, if and only if one filename was specified.") Parser.add_option("-r", "--reportfile filename", action="store", type="string", dest="ReportFile", help="Specify the name of an report file, if and only if one filename was specified.") Parser.add_option("-e", "--exceptionfile filename", action="store", type="string", dest="ExceptionFile", help="Specify the name of an exception file, if and only if one filename was specified.") Parser.add_option("-m", "--metadata", action="store_true", type=None, help="Only scan meta-data files information if this option is specified.") Parser.add_option("-s", "--sourcecode", action="store_true", type=None, help="Only scan source code files information if this option is specified.") Parser.add_option("-k", "--keepdatabase", action="store_true", type=None, help="The existing Ecc database will not be cleaned except report information if this option is specified.") Parser.add_option("-l", "--log filename", action="store", dest="LogFile", help="""If specified, the tool should emit the changes that were made by the tool after printing the result message. If filename, the emit to the file, otherwise emit to standard output. If no modifications were made, then do not create a log file, or output a log message.""") Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.") Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\ "including library instances selected, final dependency expression, "\ "and warning messages, etc.") Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.") Parser.add_option("-w", "--workspace", action="store", type="string", dest='Workspace', help="Specify workspace.") (Opt, Args)=Parser.parse_args() return (Opt, Args) ## # # This acts like the main() function for the script, unless it is 'import'ed into another # script. # if __name__ == '__main__': # Initialize log system EdkLogger.Initialize() EdkLogger.IsRaiseError = False EdkLogger.quiet(time.strftime("%H:%M:%S, %b.%d %Y ", time.localtime()) + "[00:00]" + "\n") StartTime = time.clock() Ecc = Ecc() FinishTime = time.clock() BuildDuration = time.strftime("%M:%S", time.gmtime(int(round(FinishTime - StartTime)))) EdkLogger.quiet("\n%s [%s]" % (time.strftime("%H:%M:%S, %b.%d %Y", time.localtime()), BuildDuration))
gpl-2.0
ruibarreira/linuxtrail
usr/lib/python2.7/dist-packages/reportlab/platypus/tableofcontents.py
3
20696
#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/platypus/tableofcontents.py __version__=''' $Id$ ''' __doc__="""Experimental class to generate Tables of Contents easily This module defines a single TableOfContents() class that can be used to create automatically a table of tontents for Platypus documents like this: story = [] toc = TableOfContents() story.append(toc) # some heading paragraphs here... doc = MyTemplate(path) doc.multiBuild(story) The data needed to create the table is a list of (level, text, pageNum) triplets, plus some paragraph styles for each level of the table itself. The triplets will usually be created in a document template's method like afterFlowable(), making notification calls using the notify() method with appropriate data like this: (level, text, pageNum) = ... self.notify('TOCEntry', (level, text, pageNum)) Optionally the list can contain four items in which case the last item is a destination key which the entry should point to. A bookmark with this key needs to be created first like this: key = 'ch%s' % self.seq.nextf('chapter') self.canv.bookmarkPage(key) self.notify('TOCEntry', (level, text, pageNum, key)) As the table of contents need at least two passes over the Platypus story which is why the moultiBuild0() method must be called. The level<NUMBER>ParaStyle variables are the paragraph styles used to format the entries in the table of contents. Their indentation is calculated like this: each entry starts at a multiple of some constant named delta. If one entry spans more than one line, all lines after the first are indented by the same constant named epsilon. """ from reportlab.lib import enums from reportlab.lib.units import cm from reportlab.lib.utils import commasplit, escapeOnce, encode_label, decode_label, strTypes from reportlab.lib.styles import ParagraphStyle, _baseFontName from reportlab.platypus.paragraph import Paragraph from reportlab.platypus.doctemplate import IndexingFlowable from reportlab.platypus.tables import TableStyle, Table from reportlab.platypus.flowables import Spacer, Flowable from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.pdfgen import canvas def unquote(txt): from xml.sax.saxutils import unescape return unescape(txt, {"&apos;": "'", "&quot;": '"'}) try: set except: class set(list): def add(self,x): if x not in self: list.append(self,x) def drawPageNumbers(canvas, style, pages, availWidth, availHeight, dot=' . '): ''' Draws pagestr on the canvas using the given style. If dot is None, pagestr is drawn at the current position in the canvas. If dot is a string, pagestr is drawn right-aligned. If the string is not empty, the gap is filled with it. ''' pages.sort() pagestr = ', '.join([str(p) for p, _ in pages]) x, y = canvas._curr_tx_info['cur_x'], canvas._curr_tx_info['cur_y'] fontSize = style.fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) #if it's too long to fit, we need to shrink to fit in 10% increments. #it would be very hard to output multiline entries. #however, we impose a minimum size of 1 point as we don't want an #infinite loop. Ultimately we should allow a TOC entry to spill #over onto a second line if needed. freeWidth = availWidth-x while pagestrw > freeWidth and fontSize >= 1.0: fontSize = 0.9 * fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) if isinstance(dot, strTypes): if dot: dotw = stringWidth(dot, style.fontName, fontSize) dotsn = int((availWidth-x-pagestrw)/dotw) else: dotsn = dotw = 0 text = '%s%s' % (dotsn * dot, pagestr) newx = availWidth - dotsn*dotw - pagestrw pagex = availWidth - pagestrw elif dot is None: text = ', ' + pagestr newx = x pagex = newx else: raise TypeError('Argument dot should either be None or an instance of basestring.') tx = canvas.beginText(newx, y) tx.setFont(style.fontName, fontSize) tx.setFillColor(style.textColor) tx.textLine(text) canvas.drawText(tx) commaw = stringWidth(', ', style.fontName, fontSize) for p, key in pages: if not key: continue w = stringWidth(str(p), style.fontName, fontSize) canvas.linkRect('', key, (pagex, y, pagex+w, y+style.leading), relative=1) pagex += w + commaw # Default paragraph styles for tables of contents. # (This could also be generated automatically or even # on-demand if it is not known how many levels the # TOC will finally need to display...) delta = 1*cm epsilon = 0.5*cm defaultLevelStyles = [ ParagraphStyle( name='Level 0', fontName=_baseFontName, fontSize=10, leading=11, firstLineIndent = 0, leftIndent = epsilon)] defaultTableStyle = \ TableStyle([ ('VALIGN', (0,0), (-1,-1), 'TOP'), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('LEFTPADDING', (0,0), (-1,-1), 0), ]) class TableOfContents(IndexingFlowable): """This creates a formatted table of contents. It presumes a correct block of data is passed in. The data block contains a list of (level, text, pageNumber) triplets. You can supply a paragraph style for each level (starting at zero). Set dotsMinLevel to determine from which level on a line of dots should be drawn between the text and the page number. If dotsMinLevel is set to a negative value, no dotted lines are drawn. """ def __init__(self): self.rightColumnWidth = 72 self.levelStyles = defaultLevelStyles self.tableStyle = defaultTableStyle self.dotsMinLevel = 1 self._table = None self._entries = [] self._lastEntries = [] def beforeBuild(self): # keep track of the last run self._lastEntries = self._entries[:] self.clearEntries() def isIndexing(self): return 1 def isSatisfied(self): return (self._entries == self._lastEntries) def notify(self, kind, stuff): """The notification hook called to register all kinds of events. Here we are interested in 'TOCEntry' events only. """ if kind == 'TOCEntry': self.addEntry(*stuff) def clearEntries(self): self._entries = [] def getLevelStyle(self, n): '''Returns the style for level n, generating and caching styles on demand if not present.''' try: return self.levelStyles[n] except IndexError: prevstyle = self.getLevelStyle(n-1) self.levelStyles.append(ParagraphStyle( name='%s-%d-indented' % (prevstyle.name, n), parent=prevstyle, firstLineIndent = prevstyle.firstLineIndent+delta, leftIndent = prevstyle.leftIndent+delta)) return self.levelStyles[n] def addEntry(self, level, text, pageNum, key=None): """Adds one entry to the table of contents. This allows incremental buildup by a doctemplate. Requires that enough styles are defined.""" assert type(level) == type(1), "Level must be an integer" self._entries.append((level, text, pageNum, key)) def addEntries(self, listOfEntries): """Bulk creation of entries in the table of contents. If you knew the titles but not the page numbers, you could supply them to get sensible output on the first run.""" for entryargs in listOfEntries: self.addEntry(*entryargs) def wrap(self, availWidth, availHeight): "All table properties should be known by now." # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0,'Placeholder for table of contents',0,None)] else: _tempEntries = self._lastEntries def drawTOCEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' label = label.split(',') page, level, key = int(label[0]), int(label[1]), eval(label[2],{}) style = self.getLevelStyle(level) if self.dotsMinLevel >= 0 and level >= self.dotsMinLevel: dot = ' . ' else: dot = '' drawPageNumbers(canvas, style, [(page, key)], availWidth, availHeight, dot) self.canv.drawTOCEntryEnd = drawTOCEntryEnd tableData = [] for (level, text, pageNum, key) in _tempEntries: style = self.getLevelStyle(level) if key: text = '<a href="#%s">%s</a>' % (key, text) keyVal = repr(key).replace(',','\\x2c').replace('"','\\x2c') else: keyVal = None para = Paragraph('%s<onDraw name="drawTOCEntryEnd" label="%d,%d,%s"/>' % (text, pageNum, level, keyVal), style) if style.spaceBefore: tableData.append([Spacer(1, style.spaceBefore),]) tableData.append([para,]) self._table = Table(tableData, colWidths=(availWidth,), style=self.tableStyle) self.width, self.height = self._table.wrapOn(self.canv,availWidth, availHeight) return (self.width, self.height) def split(self, availWidth, availHeight): """At this stage we do not care about splitting the entries, we will just return a list of platypus tables. Presumably the calling app has a pointer to the original TableOfContents object; Platypus just sees tables. """ return self._table.splitOn(self.canv,availWidth, availHeight) def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object. """ self._table.drawOn(canvas, x, y, _sW) def makeTuple(x): if hasattr(x, '__iter__'): return tuple(x) return (x,) class SimpleIndex(IndexingFlowable): """Creates multi level indexes. The styling can be cutomized and alphabetic headers turned on and off. """ def __init__(self, **kwargs): """ Constructor of SimpleIndex. Accepts the same arguments as the setup method. """ #keep stuff in a dictionary while building self._entries = {} self._lastEntries = {} self._flowable = None self.setup(**kwargs) def getFormatFunc(self,format): try: D = {} exec('from reportlab.lib.sequencer import _format_%s as formatFunc' % format, D) return D['formatFunc'] except ImportError: raise ValueError('Unknown format %r' % format) def setup(self, style=None, dot=None, tableStyle=None, headers=True, name=None, format='123', offset=0): """ This method makes it possible to change styling and other parameters on an existing object. style is the paragraph style to use for index entries. dot can either be None or a string. If it's None, entries are immediatly followed by their corresponding page numbers. If it's a string, page numbers are aligned on the right side of the document and the gap filled with a repeating sequence of the string. tableStyle is the style used by the table which the index uses to draw itself. Use this to change properties like spacing between elements. headers is a boolean. If it is True, alphabetic headers are displayed in the Index when the first letter changes. If False, we just output some extra space before the next item name makes it possible to use several indexes in one document. If you want this use this parameter to give each index a unique name. You can then index a term by refering to the name of the index which it should appear in: <index item="term" name="myindex" /> format can be 'I', 'i', '123', 'ABC', 'abc' """ if style is None: style = ParagraphStyle(name='index', fontName=_baseFontName, fontSize=11) self.textStyle = style self.tableStyle = tableStyle or defaultTableStyle self.dot = dot self.headers = headers if name is None: from reportlab.platypus.paraparser import DEFAULT_INDEX_NAME as name self.name = name self.formatFunc = self.getFormatFunc(format) self.offset = offset def __call__(self,canv,kind,label): try: terms, format, offset = decode_label(label) except: terms = label format = offset = None if format is None: formatFunc = self.formatFunc else: formatFunc = self.getFormatFunc(format) if offset is None: offset = self.offset terms = commasplit(terms) pns = formatFunc(canv.getPageNumber()-offset) key = 'ix_%s_%s_p_%s' % (self.name, label, pns) info = canv._curr_tx_info canv.bookmarkHorizontal(key, info['cur_x'], info['cur_y'] + info['leading']) self.addEntry(terms, pns, key) def getCanvasMaker(self, canvasmaker=canvas.Canvas): def newcanvasmaker(*args, **kwargs): from reportlab.pdfgen import canvas c = canvasmaker(*args, **kwargs) setattr(c,self.name,self) return c return newcanvasmaker def isIndexing(self): return 1 def isSatisfied(self): return (self._entries == self._lastEntries) def beforeBuild(self): # keep track of the last run self._lastEntries = self._entries.copy() self.clearEntries() def clearEntries(self): self._entries = {} def notify(self, kind, stuff): """The notification hook called to register all kinds of events. Here we are interested in 'IndexEntry' events only. """ if kind == 'IndexEntry': (text, pageNum) = stuff self.addEntry(text, pageNum) def addEntry(self, text, pageNum, key=None): """Allows incremental buildup""" self._entries.setdefault(makeTuple(text),set([])).add((pageNum, key)) def split(self, availWidth, availHeight): """At this stage we do not care about splitting the entries, we will just return a list of platypus tables. Presumably the calling app has a pointer to the original TableOfContents object; Platypus just sees tables. """ return self._flowable.splitOn(self.canv,availWidth, availHeight) def _getlastEntries(self, dummy=[(['Placeholder for index'],enumerate((None,)*3))]): '''Return the last run's entries! If there are none, returns dummy.''' if not self._lastEntries: if self._entries: return list(self._entries.items()) return dummy return list(self._lastEntries.items()) def _build(self,availWidth,availHeight): _tempEntries = self._getlastEntries() def getkey(seq): return [x.upper() for x in seq[0]] _tempEntries.sort(key=getkey) leveloffset = self.headers and 1 or 0 def drawIndexEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' style = self.getLevelStyle(leveloffset) pages = decode_label(label) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot) self.canv.drawIndexEntryEnd = drawIndexEntryEnd alpha = '' tableData = [] lastTexts = [] alphaStyle = self.getLevelStyle(0) for texts, pageNumbers in _tempEntries: texts = list(texts) #track when the first character changes; either output some extra #space, or the first letter on a row of its own. We cannot do #widow/orphan control, sadly. nalpha = texts[0][0].upper() if alpha != nalpha: alpha = nalpha if self.headers: header = alpha else: header = ' ' tableData.append([Spacer(1, alphaStyle.spaceBefore),]) tableData.append([Paragraph(header, alphaStyle),]) tableData.append([Spacer(1, alphaStyle.spaceAfter),]) i, diff = listdiff(lastTexts, texts) if diff: lastTexts = texts texts = texts[i:] label = encode_label(list(pageNumbers)) texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (texts[-1], label) for text in texts: #Platypus and RML differ on how parsed XML attributes are escaped. #e.g. <index item="M&S"/>. The only place this seems to bite us is in #the index entries so work around it here. text = escapeOnce(text) style = self.getLevelStyle(i+leveloffset) para = Paragraph(text, style) if style.spaceBefore: tableData.append([Spacer(1, style.spaceBefore),]) tableData.append([para,]) i += 1 self._flowable = Table(tableData, colWidths=[availWidth], style=self.tableStyle) def wrap(self, availWidth, availHeight): "All table properties should be known by now." self._build(availWidth,availHeight) self.width, self.height = self._flowable.wrapOn(self.canv,availWidth, availHeight) return self.width, self.height def drawOn(self, canvas, x, y, _sW=0): """Don't do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object. """ self._flowable.drawOn(canvas, x, y, _sW) def draw(self): t = self._flowable ocanv = getattr(t,'canv',None) if not ocanv: t.canv = self.canv try: t.draw() finally: if not ocanv: del t.canv def getLevelStyle(self, n): '''Returns the style for level n, generating and caching styles on demand if not present.''' if not hasattr(self.textStyle, '__iter__'): self.textStyle = [self.textStyle] try: return self.textStyle[n] except IndexError: self.textStyle = list(self.textStyle) prevstyle = self.getLevelStyle(n-1) self.textStyle.append(ParagraphStyle( name='%s-%d-indented' % (prevstyle.name, n), parent=prevstyle, firstLineIndent = prevstyle.firstLineIndent+.2*cm, leftIndent = prevstyle.leftIndent+.2*cm)) return self.textStyle[n] AlphabeticIndex = SimpleIndex def listdiff(l1, l2): m = min(len(l1), len(l2)) for i in range(m): if l1[i] != l2[i]: return i, l2[i:] return m, l2[m:] class ReferenceText(IndexingFlowable): """Fakery to illustrate how a reference would work if we could put it in a paragraph.""" def __init__(self, textPattern, targetKey): self.textPattern = textPattern self.target = targetKey self.paraStyle = ParagraphStyle('tmp') self._lastPageNum = None self._pageNum = -999 self._para = None def beforeBuild(self): self._lastPageNum = self._pageNum def notify(self, kind, stuff): if kind == 'Target': (key, pageNum) = stuff if key == self.target: self._pageNum = pageNum def wrap(self, availWidth, availHeight): text = self.textPattern % self._lastPageNum self._para = Paragraph(text, self.paraStyle) return self._para.wrap(availWidth, availHeight) def drawOn(self, canvas, x, y, _sW=0): self._para.drawOn(canvas, x, y, _sW)
gpl-3.0
bbc/kamaelia
Sketches/MPS/BugReports/FixTests/Kamaelia/Examples/OpenGL/MiniExamples/SkyGrassBackground.py
6
1159
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # 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 Axon from Kamaelia.UI.OpenGL.SkyGrassBackground import SkyGrassBackground SkyGrassBackground(size=(5000,5000,0), position=(0,0,-100)).activate() Axon.Scheduler.scheduler.run.runThreads() # Licensed to the BBC under a Contributor Agreement: THF
apache-2.0
ryancanhelpyou/servo
tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_request.py
299
2987
import os import unittest import urllib2 import json import time import wptserve from base import TestUsingServer, doc_root class TestInputFile(TestUsingServer): def test_seek(self): @wptserve.handlers.handler def handler(request, response): rv = [] f = request.raw_input f.seek(5) rv.append(f.read(2)) rv.append(f.tell()) f.seek(0) rv.append(f.readline()) rv.append(f.tell()) rv.append(f.read(-1)) rv.append(f.tell()) f.seek(0) rv.append(f.read()) f.seek(0) rv.extend(f.readlines()) return " ".join(str(item) for item in rv) route = ("POST", "/test/test_seek", handler) self.server.router.register(*route) resp = self.request(route[1], method="POST", body="12345ab\ncdef") self.assertEquals(200, resp.getcode()) self.assertEquals(["ab", "7", "12345ab\n", "8", "cdef", "12", "12345ab\ncdef", "12345ab\n", "cdef"], resp.read().split(" ")) def test_iter(self): @wptserve.handlers.handler def handler(request, response): f = request.raw_input return " ".join(line for line in f) route = ("POST", "/test/test_iter", handler) self.server.router.register(*route) resp = self.request(route[1], method="POST", body="12345\nabcdef\r\nzyxwv") self.assertEquals(200, resp.getcode()) self.assertEquals(["12345\n", "abcdef\r\n", "zyxwv"], resp.read().split(" ")) class TestRequest(TestUsingServer): def test_body(self): @wptserve.handlers.handler def handler(request, response): request.raw_input.seek(5) return request.body route = ("POST", "/test/test_body", handler) self.server.router.register(*route) resp = self.request(route[1], method="POST", body="12345ab\ncdef") self.assertEquals("12345ab\ncdef", resp.read()) def test_route_match(self): @wptserve.handlers.handler def handler(request, response): return request.route_match["match"] + " " + request.route_match["*"] route = ("GET", "/test/{match}_*", handler) self.server.router.register(*route) resp = self.request("/test/some_route") self.assertEquals("some route", resp.read()) class TestAuth(TestUsingServer): def test_auth(self): @wptserve.handlers.handler def handler(request, response): return " ".join((request.auth.username, request.auth.password)) route = ("GET", "/test/test_auth", handler) self.server.router.register(*route) resp = self.request(route[1], auth=("test", "PASS")) self.assertEquals(200, resp.getcode()) self.assertEquals(["test", "PASS"], resp.read().split(" ")) if __name__ == '__main__': unittest.main()
mpl-2.0
jotes/ansible
lib/ansible/runner/connection_plugins/paramiko_ssh.py
31
14915
# (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/>. # --- # The paramiko transport is provided because many distributions, in particular EL6 and before # do not support ControlPersist in their SSH implementations. This is needed on the Ansible # control machine to be reasonably efficient with connections. Thus paramiko is faster # for most users on these platforms. Users with ControlPersist capability can consider # using -c ssh or configuring the transport in ansible.cfg. import warnings import os import pipes import socket import random import logging import tempfile import traceback import fcntl import re import sys from termios import tcflush, TCIFLUSH from binascii import hexlify from ansible.callbacks import vvv from ansible import errors from ansible import utils from ansible import constants as C AUTHENTICITY_MSG=""" paramiko: The authenticity of host '%s' can't be established. The %s key fingerprint is %s. Are you sure you want to continue connecting (yes/no)? """ # prevent paramiko warning noise -- see http://stackoverflow.com/questions/3920502/ HAVE_PARAMIKO=False with warnings.catch_warnings(): warnings.simplefilter("ignore") try: import paramiko HAVE_PARAMIKO=True logging.getLogger("paramiko").setLevel(logging.WARNING) except ImportError: pass class MyAddPolicy(object): """ Based on AutoAddPolicy in paramiko so we can determine when keys are added and also prompt for input. Policy for automatically adding the hostname and new host key to the local L{HostKeys} object, and saving it. This is used by L{SSHClient}. """ def __init__(self, runner): self.runner = runner def missing_host_key(self, client, hostname, key): if C.HOST_KEY_CHECKING: fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX) fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX) old_stdin = sys.stdin sys.stdin = self.runner._new_stdin fingerprint = hexlify(key.get_fingerprint()) ktype = key.get_name() # clear out any premature input on sys.stdin tcflush(sys.stdin, TCIFLUSH) inp = raw_input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint)) sys.stdin = old_stdin if inp not in ['yes','y','']: fcntl.flock(self.runner.output_lockfile, fcntl.LOCK_UN) fcntl.flock(self.runner.process_lockfile, fcntl.LOCK_UN) raise errors.AnsibleError("host connection rejected by user") fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN) fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN) key._added_by_ansible_this_time = True # existing implementation below: client._host_keys.add(hostname, key.get_name(), key) # host keys are actually saved in close() function below # in order to control ordering. # keep connection objects on a per host basis to avoid repeated attempts to reconnect SSH_CONNECTION_CACHE = {} SFTP_CONNECTION_CACHE = {} class Connection(object): ''' SSH based connections with Paramiko ''' def __init__(self, runner, host, port, user, password, private_key_file, *args, **kwargs): self.ssh = None self.sftp = None self.runner = runner self.host = host self.port = port or 22 self.user = user self.password = password self.private_key_file = private_key_file self.has_pipelining = False def _cache_key(self): return "%s__%s__" % (self.host, self.user) def connect(self): cache_key = self._cache_key() if cache_key in SSH_CONNECTION_CACHE: self.ssh = SSH_CONNECTION_CACHE[cache_key] else: self.ssh = SSH_CONNECTION_CACHE[cache_key] = self._connect_uncached() return self def _connect_uncached(self): ''' activates the connection object ''' if not HAVE_PARAMIKO: raise errors.AnsibleError("paramiko is not installed") vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (self.user, self.port, self.host), host=self.host) ssh = paramiko.SSHClient() self.keyfile = os.path.expanduser("~/.ssh/known_hosts") if C.HOST_KEY_CHECKING: ssh.load_system_host_keys() ssh.set_missing_host_key_policy(MyAddPolicy(self.runner)) allow_agent = True if self.password is not None: allow_agent = False try: if self.private_key_file: key_filename = os.path.expanduser(self.private_key_file) elif self.runner.private_key_file: key_filename = os.path.expanduser(self.runner.private_key_file) else: key_filename = None ssh.connect(self.host, username=self.user, allow_agent=allow_agent, look_for_keys=True, key_filename=key_filename, password=self.password, timeout=self.runner.timeout, port=self.port) except Exception, e: msg = str(e) if "PID check failed" in msg: raise errors.AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible") elif "Private key file is encrypted" in msg: msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % ( self.user, self.host, self.port, msg) raise errors.AnsibleConnectionFailed(msg) else: raise errors.AnsibleConnectionFailed(msg) return ssh def exec_command(self, cmd, tmp_path, sudo_user=None, sudoable=False, executable='/bin/sh', in_data=None, su=None, su_user=None): ''' run a command on the remote host ''' if in_data: raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining") bufsize = 4096 try: self.ssh.get_transport().set_keepalive(5) chan = self.ssh.get_transport().open_session() except Exception, e: msg = "Failed to open session" if len(str(e)) > 0: msg += ": %s" % str(e) raise errors.AnsibleConnectionFailed(msg) no_prompt_out = '' no_prompt_err = '' if not (self.runner.sudo and sudoable) and not (self.runner.su and su): if executable: quoted_command = executable + ' -c ' + pipes.quote(cmd) else: quoted_command = cmd vvv("EXEC %s" % quoted_command, host=self.host) chan.exec_command(quoted_command) else: # sudo usually requires a PTY (cf. requiretty option), therefore # we give it one by default (pty=True in ansble.cfg), and we try # to initialise from the calling environment if C.PARAMIKO_PTY: chan.get_pty(term=os.getenv('TERM', 'vt100'), width=int(os.getenv('COLUMNS', 0)), height=int(os.getenv('LINES', 0))) if self.runner.sudo or sudoable: shcmd, prompt, success_key = utils.make_sudo_cmd(self.runner.sudo_exe, sudo_user, executable, cmd) elif self.runner.su or su: shcmd, prompt, success_key = utils.make_su_cmd(su_user, executable, cmd) vvv("EXEC %s" % shcmd, host=self.host) sudo_output = '' try: chan.exec_command(shcmd) if self.runner.sudo_pass or self.runner.su_pass: while True: if success_key in sudo_output or \ (self.runner.sudo_pass and sudo_output.endswith(prompt)) or \ (self.runner.su_pass and utils.su_prompts.check_su_prompt(sudo_output)): break chunk = chan.recv(bufsize) if not chunk: if 'unknown user' in sudo_output: raise errors.AnsibleError( 'user %s does not exist' % sudo_user) else: raise errors.AnsibleError('ssh connection ' + 'closed waiting for password prompt') sudo_output += chunk if success_key not in sudo_output: if sudoable: chan.sendall(self.runner.sudo_pass + '\n') elif su: chan.sendall(self.runner.su_pass + '\n') else: no_prompt_out += sudo_output no_prompt_err += sudo_output except socket.timeout: raise errors.AnsibleError('ssh timed out waiting for sudo.\n' + sudo_output) stdout = ''.join(chan.makefile('rb', bufsize)) stderr = ''.join(chan.makefile_stderr('rb', bufsize)) return (chan.recv_exit_status(), '', no_prompt_out + stdout, no_prompt_out + stderr) def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: self.sftp = self.ssh.open_sftp() except Exception, e: raise errors.AnsibleError("failed to open a SFTP connection (%s)" % e) try: self.sftp.put(in_path, out_path) except IOError: raise errors.AnsibleError("failed to transfer file to %s" % out_path) def _connect_sftp(self): cache_key = "%s__%s__" % (self.host, self.user) if cache_key in SFTP_CONNECTION_CACHE: return SFTP_CONNECTION_CACHE[cache_key] else: result = SFTP_CONNECTION_CACHE[cache_key] = self.connect().ssh.open_sftp() return result def fetch_file(self, in_path, out_path): ''' save a remote file to the specified path ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host) try: self.sftp = self._connect_sftp() except Exception, e: raise errors.AnsibleError("failed to open a SFTP connection (%s)", e) try: self.sftp.get(in_path, out_path) except IOError: raise errors.AnsibleError("failed to transfer file from %s" % in_path) def _any_keys_added(self): added_any = False for hostname, keys in self.ssh._host_keys.iteritems(): for keytype, key in keys.iteritems(): added_this_time = getattr(key, '_added_by_ansible_this_time', False) if added_this_time: return True return False def _save_ssh_host_keys(self, filename): ''' not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks don't complain about it :) ''' if not self._any_keys_added(): return False path = os.path.expanduser("~/.ssh") if not os.path.exists(path): os.makedirs(path) f = open(filename, 'w') for hostname, keys in self.ssh._host_keys.iteritems(): for keytype, key in keys.iteritems(): # was f.write added_this_time = getattr(key, '_added_by_ansible_this_time', False) if not added_this_time: f.write("%s %s %s\n" % (hostname, keytype, key.get_base64())) for hostname, keys in self.ssh._host_keys.iteritems(): for keytype, key in keys.iteritems(): added_this_time = getattr(key, '_added_by_ansible_this_time', False) if added_this_time: f.write("%s %s %s\n" % (hostname, keytype, key.get_base64())) f.close() def close(self): ''' terminate the connection ''' cache_key = self._cache_key() SSH_CONNECTION_CACHE.pop(cache_key, None) SFTP_CONNECTION_CACHE.pop(cache_key, None) if self.sftp is not None: self.sftp.close() if C.HOST_KEY_CHECKING and C.PARAMIKO_RECORD_HOST_KEYS and self._any_keys_added(): # add any new SSH host keys -- warning -- this could be slow lockfile = self.keyfile.replace("known_hosts",".known_hosts.lock") dirname = os.path.dirname(self.keyfile) if not os.path.exists(dirname): os.makedirs(dirname) KEY_LOCK = open(lockfile, 'w') fcntl.lockf(KEY_LOCK, fcntl.LOCK_EX) try: # just in case any were added recently self.ssh.load_system_host_keys() self.ssh._host_keys.update(self.ssh._system_host_keys) # gather information about the current key file, so # we can ensure the new file has the correct mode/owner key_dir = os.path.dirname(self.keyfile) key_stat = os.stat(self.keyfile) # Save the new keys to a temporary file and move it into place # rather than rewriting the file. We set delete=False because # the file will be moved into place rather than cleaned up. tmp_keyfile = tempfile.NamedTemporaryFile(dir=key_dir, delete=False) os.chmod(tmp_keyfile.name, key_stat.st_mode & 07777) os.chown(tmp_keyfile.name, key_stat.st_uid, key_stat.st_gid) self._save_ssh_host_keys(tmp_keyfile.name) tmp_keyfile.close() os.rename(tmp_keyfile.name, self.keyfile) except: # unable to save keys, including scenario when key was invalid # and caught earlier traceback.print_exc() pass fcntl.lockf(KEY_LOCK, fcntl.LOCK_UN) self.ssh.close()
gpl-3.0
albertomurillo/ansible
lib/ansible/modules/cloud/vmware/vmware_category.py
7
9346
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_category short_description: Manage VMware categories description: - This module can be used to create / delete / update VMware categories. - Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere. - All variables and VMware object names are case sensitive. version_added: '2.7' author: - Abhijeet Kasurde (@Akasurde) notes: - Tested on vSphere 6.5 requirements: - python >= 2.6 - PyVmomi - vSphere Automation SDK options: category_name: description: - The name of category to manage. required: True category_description: description: - The category description. - This is required only if C(state) is set to C(present). - This parameter is ignored, when C(state) is set to C(absent). default: '' category_cardinality: description: - The category cardinality. - This parameter is ignored, when updating existing category. choices: ['multiple', 'single'] default: 'multiple' new_category_name: description: - The new name for an existing category. - This value is used while updating an existing category. state: description: - The state of category. - If set to C(present) and category does not exists, then category is created. - If set to C(present) and category exists, then category is updated. - If set to C(absent) and category exists, then category is deleted. - If set to C(absent) and category does not exists, no action is taken. - Process of updating category only allows name, description change. default: 'present' choices: [ 'present', 'absent' ] extends_documentation_fragment: vmware_rest_client.documentation ''' EXAMPLES = r''' - name: Create a category vmware_category: hostname: "{{ vcenter_server }}" username: "{{ vcenter_user }}" password: "{{ vcenter_pass }}" category_name: Sample_Cat_0001 category_description: Sample Description category_cardinality: 'multiple' state: present - name: Rename category vmware_category: hostname: "{{ vcenter_server }}" username: "{{ vcenter_user }}" password: "{{ vcenter_pass }}" category_name: Sample_Category_0001 new_category_name: Sample_Category_0002 state: present - name: Update category description vmware_category: hostname: "{{ vcenter_server }}" username: "{{ vcenter_user }}" password: "{{ vcenter_pass }}" category_name: Sample_Category_0001 category_description: Some fancy description state: present - name: Delete category vmware_category: hostname: "{{ vcenter_server }}" username: "{{ vcenter_user }}" password: "{{ vcenter_pass }}" category_name: Sample_Category_0002 state: absent ''' RETURN = r''' category_results: description: dictionary of category metadata returned: on success type: dict sample: { "category_id": "urn:vmomi:InventoryServiceCategory:d7120bda-9fa5-4f92-9d71-aa1acff2e5a8:GLOBAL", "msg": "Category NewCat_0001 updated." } ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vmware_rest_client import VmwareRestClient try: from com.vmware.cis.tagging_client import CategoryModel except ImportError: pass class VmwareCategory(VmwareRestClient): def __init__(self, module): super(VmwareCategory, self).__init__(module) self.category_service = self.api_client.tagging.Category self.global_categories = dict() self.category_name = self.params.get('category_name') self.get_all_categories() def ensure_state(self): """Manage internal states of categories. """ desired_state = self.params.get('state') states = { 'present': { 'present': self.state_update_category, 'absent': self.state_create_category, }, 'absent': { 'present': self.state_delete_category, 'absent': self.state_unchanged, } } states[desired_state][self.check_category_status()]() def state_create_category(self): """Create category.""" category_spec = self.category_service.CreateSpec() category_spec.name = self.category_name category_spec.description = self.params.get('category_description') if self.params.get('category_cardinality') == 'single': category_spec.cardinality = CategoryModel.Cardinality.SINGLE else: category_spec.cardinality = CategoryModel.Cardinality.MULTIPLE category_spec.associable_types = set() category_id = self.category_service.create(category_spec) if category_id: self.module.exit_json(changed=True, category_results=dict(msg="Category '%s' created." % category_spec.name, category_id=category_id)) self.module.exit_json(changed=False, category_results=dict(msg="No category created", category_id='')) def state_unchanged(self): """Return unchanged state.""" self.module.exit_json(changed=False) def state_update_category(self): """Update category.""" category_id = self.global_categories[self.category_name]['category_id'] changed = False results = dict(msg="Category %s is unchanged." % self.category_name, category_id=category_id) category_update_spec = self.category_service.UpdateSpec() change_list = [] old_cat_desc = self.global_categories[self.category_name]['category_description'] new_cat_desc = self.params.get('category_description') if new_cat_desc and new_cat_desc != old_cat_desc: category_update_spec.description = new_cat_desc results['msg'] = 'Category %s updated.' % self.category_name change_list.append(True) new_cat_name = self.params.get('new_category_name') if new_cat_name in self.global_categories: self.module.fail_json(msg="Unable to rename %s as %s already" " exists in configuration." % (self.category_name, new_cat_name)) old_cat_name = self.global_categories[self.category_name]['category_name'] if new_cat_name and new_cat_name != old_cat_name: category_update_spec.name = new_cat_name results['msg'] = 'Category %s updated.' % self.category_name change_list.append(True) if any(change_list): self.category_service.update(category_id, category_update_spec) changed = True self.module.exit_json(changed=changed, category_results=results) def state_delete_category(self): """Delete category.""" category_id = self.global_categories[self.category_name]['category_id'] self.category_service.delete(category_id=category_id) self.module.exit_json(changed=True, category_results=dict(msg="Category '%s' deleted." % self.category_name, category_id=category_id)) def check_category_status(self): """ Check if category exists or not Returns: 'present' if category found, else 'absent' """ if self.category_name in self.global_categories: return 'present' else: return 'absent' def get_all_categories(self): """Retrieve all category information.""" for category in self.category_service.list(): category_obj = self.category_service.get(category) self.global_categories[category_obj.name] = dict( category_description=category_obj.description, category_used_by=category_obj.used_by, category_cardinality=str(category_obj.cardinality), category_associable_types=category_obj.associable_types, category_id=category_obj.id, category_name=category_obj.name, ) def main(): argument_spec = VmwareRestClient.vmware_client_argument_spec() argument_spec.update( category_name=dict(type='str', required=True), category_description=dict(type='str', default='', required=False), category_cardinality=dict(type='str', choices=["multiple", "single"], default="multiple"), new_category_name=dict(type='str'), state=dict(type='str', choices=['present', 'absent'], default='present'), ) module = AnsibleModule(argument_spec=argument_spec) vmware_category = VmwareCategory(module) vmware_category.ensure_state() if __name__ == '__main__': main()
gpl-3.0
lateminer/bitcoin
test/functional/rpc_invalid_address_message.py
16
3689
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test error messages for 'getaddressinfo' and 'validateaddress' RPC commands.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) BECH32_VALID = 'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv' BECH32_INVALID_BECH32 = 'bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqdmchcc' BECH32_INVALID_BECH32M = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7k35mrzd' BECH32_INVALID_VERSION = 'bcrt130xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqynjegk' BECH32_INVALID_SIZE = 'bcrt1s0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav25430mtr' BECH32_INVALID_V0_SIZE = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kqqq5k3my' BECH32_INVALID_PREFIX = 'bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx' BASE58_VALID = 'mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn' BASE58_INVALID_PREFIX = '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem' INVALID_ADDRESS = 'asfah14i8fajz0123f' class InvalidAddressErrorMessageTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def test_validateaddress(self): node = self.nodes[0] # Bech32 info = node.validateaddress(BECH32_INVALID_SIZE) assert not info['isvalid'] assert_equal(info['error'], 'Invalid Bech32 address data size') info = node.validateaddress(BECH32_INVALID_PREFIX) assert not info['isvalid'] assert_equal(info['error'], 'Invalid prefix for Bech32 address') info = node.validateaddress(BECH32_INVALID_BECH32) assert not info['isvalid'] assert_equal(info['error'], 'Version 1+ witness address must use Bech32m checksum') info = node.validateaddress(BECH32_INVALID_BECH32M) assert not info['isvalid'] assert_equal(info['error'], 'Version 0 witness address must use Bech32 checksum') info = node.validateaddress(BECH32_INVALID_V0_SIZE) assert not info['isvalid'] assert_equal(info['error'], 'Invalid Bech32 v0 address data size') info = node.validateaddress(BECH32_VALID) assert info['isvalid'] assert 'error' not in info # Base58 info = node.validateaddress(BASE58_INVALID_PREFIX) assert not info['isvalid'] assert_equal(info['error'], 'Invalid prefix for Base58-encoded address') info = node.validateaddress(BASE58_VALID) assert info['isvalid'] assert 'error' not in info # Invalid address format info = node.validateaddress(INVALID_ADDRESS) assert not info['isvalid'] assert_equal(info['error'], 'Invalid address format') def test_getaddressinfo(self): node = self.nodes[0] assert_raises_rpc_error(-5, "Invalid Bech32 address data size", node.getaddressinfo, BECH32_INVALID_SIZE) assert_raises_rpc_error(-5, "Invalid prefix for Bech32 address", node.getaddressinfo, BECH32_INVALID_PREFIX) assert_raises_rpc_error(-5, "Invalid prefix for Base58-encoded address", node.getaddressinfo, BASE58_INVALID_PREFIX) assert_raises_rpc_error(-5, "Invalid address format", node.getaddressinfo, INVALID_ADDRESS) def run_test(self): self.test_validateaddress() self.test_getaddressinfo() if __name__ == '__main__': InvalidAddressErrorMessageTest().main()
mit
solarjoe/numpy
numpy/distutils/fcompiler/sun.py
167
1690
from __future__ import division, absolute_import, print_function from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler compilers = ['SunFCompiler'] class SunFCompiler(FCompiler): compiler_type = 'sun' description = 'Sun or Forte Fortran 95 Compiler' # ex: # f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 111690-10 2003/08/28 version_match = simple_version_match( start=r'f9[05]: (Sun|Forte|WorkShop).*Fortran 95') executables = { 'version_cmd' : ["<F90>", "-V"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90", "-fixed"], 'compiler_f90' : ["f90"], 'linker_so' : ["<F90>", "-Bdynamic", "-G"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = '-moddir=' module_include_switch = '-M' pic_flags = ['-xcode=pic32'] def get_flags_f77(self): ret = ["-ftrap=%none"] if (self.get_version() or '') >= '7': ret.append("-f77") else: ret.append("-fixed") return ret def get_opt(self): return ['-fast', '-dalign'] def get_arch(self): return ['-xtarget=generic'] def get_libraries(self): opt = [] opt.extend(['fsu', 'sunmath', 'mvec']) return opt def runtime_library_dir_option(self, dir): return '-R"%s"' % dir if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='sun') compiler.customize() print(compiler.get_version())
bsd-3-clause
fiber-space/pip
pip/_vendor/requests/packages/chardet/sbcsgroupprober.py
2936
3291
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # 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 ######################### from .charsetgroupprober import CharSetGroupProber from .sbcharsetprober import SingleByteCharSetProber from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model) from .langgreekmodel import Latin7GreekModel, Win1253GreekModel from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel from .langthaimodel import TIS620ThaiModel from .langhebrewmodel import Win1255HebrewModel from .hebrewprober import HebrewProber class SBCSGroupProber(CharSetGroupProber): def __init__(self): CharSetGroupProber.__init__(self) self._mProbers = [ SingleByteCharSetProber(Win1251CyrillicModel), SingleByteCharSetProber(Koi8rModel), SingleByteCharSetProber(Latin5CyrillicModel), SingleByteCharSetProber(MacCyrillicModel), SingleByteCharSetProber(Ibm866Model), SingleByteCharSetProber(Ibm855Model), SingleByteCharSetProber(Latin7GreekModel), SingleByteCharSetProber(Win1253GreekModel), SingleByteCharSetProber(Latin5BulgarianModel), SingleByteCharSetProber(Win1251BulgarianModel), SingleByteCharSetProber(Latin2HungarianModel), SingleByteCharSetProber(Win1250HungarianModel), SingleByteCharSetProber(TIS620ThaiModel), ] hebrewProber = HebrewProber() logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, False, hebrewProber) visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True, hebrewProber) hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber) self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber]) self.reset()
mit
openthread/openthread
tools/harness-automation/cases_R140/reed_5_2_4.py
18
1874
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # 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. # 3. Neither the name of the copyright holder 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 HOLDER 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. # import unittest from autothreadharness.harness_case import HarnessCase class REED_5_2_4(HarnessCase): role = HarnessCase.ROLE_REED case = '5 2 4' golden_devices_required = 17 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
bsd-3-clause
vsajip/django
django/contrib/localflavor/sk/sk_districts.py
543
2453
""" Slovak districts according to http://sk.wikipedia.org/wiki/Administrat%C3%ADvne_%C4%8Dlenenie_Slovenska """ from django.utils.translation import ugettext_lazy as _ DISTRICT_CHOICES = ( ('BB', _('Banska Bystrica')), ('BS', _('Banska Stiavnica')), ('BJ', _('Bardejov')), ('BN', _('Banovce nad Bebravou')), ('BR', _('Brezno')), ('BA1', _('Bratislava I')), ('BA2', _('Bratislava II')), ('BA3', _('Bratislava III')), ('BA4', _('Bratislava IV')), ('BA5', _('Bratislava V')), ('BY', _('Bytca')), ('CA', _('Cadca')), ('DT', _('Detva')), ('DK', _('Dolny Kubin')), ('DS', _('Dunajska Streda')), ('GA', _('Galanta')), ('GL', _('Gelnica')), ('HC', _('Hlohovec')), ('HE', _('Humenne')), ('IL', _('Ilava')), ('KK', _('Kezmarok')), ('KN', _('Komarno')), ('KE1', _('Kosice I')), ('KE2', _('Kosice II')), ('KE3', _('Kosice III')), ('KE4', _('Kosice IV')), ('KEO', _('Kosice - okolie')), ('KA', _('Krupina')), ('KM', _('Kysucke Nove Mesto')), ('LV', _('Levice')), ('LE', _('Levoca')), ('LM', _('Liptovsky Mikulas')), ('LC', _('Lucenec')), ('MA', _('Malacky')), ('MT', _('Martin')), ('ML', _('Medzilaborce')), ('MI', _('Michalovce')), ('MY', _('Myjava')), ('NO', _('Namestovo')), ('NR', _('Nitra')), ('NM', _('Nove Mesto nad Vahom')), ('NZ', _('Nove Zamky')), ('PE', _('Partizanske')), ('PK', _('Pezinok')), ('PN', _('Piestany')), ('PT', _('Poltar')), ('PP', _('Poprad')), ('PB', _('Povazska Bystrica')), ('PO', _('Presov')), ('PD', _('Prievidza')), ('PU', _('Puchov')), ('RA', _('Revuca')), ('RS', _('Rimavska Sobota')), ('RV', _('Roznava')), ('RK', _('Ruzomberok')), ('SB', _('Sabinov')), ('SC', _('Senec')), ('SE', _('Senica')), ('SI', _('Skalica')), ('SV', _('Snina')), ('SO', _('Sobrance')), ('SN', _('Spisska Nova Ves')), ('SL', _('Stara Lubovna')), ('SP', _('Stropkov')), ('SK', _('Svidnik')), ('SA', _('Sala')), ('TO', _('Topolcany')), ('TV', _('Trebisov')), ('TN', _('Trencin')), ('TT', _('Trnava')), ('TR', _('Turcianske Teplice')), ('TS', _('Tvrdosin')), ('VK', _('Velky Krtis')), ('VT', _('Vranov nad Toplou')), ('ZM', _('Zlate Moravce')), ('ZV', _('Zvolen')), ('ZC', _('Zarnovica')), ('ZH', _('Ziar nad Hronom')), ('ZA', _('Zilina')), )
bsd-3-clause
yxm4109/sample-code
sample-code/examples/python/android_complex.py
36
5220
import os import unittest from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from appium.webdriver.common.multi_action import MultiAction from time import sleep # Returns abs path relative to this file and not cwd PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class ComplexAndroidTests(unittest.TestCase): def setUp(self): desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '4.2' desired_caps['deviceName'] = 'Android Emulator' desired_caps['app'] = PATH( '../../../sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk' ) self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) def tearDown(self): self.driver.quit() def test_find_elements(self): # pause a moment, so xml generation can occur sleep(2) els = self.driver.find_elements_by_xpath('//android.widget.TextView') self.assertEqual('API Demos', els[0].text) el = self.driver.find_element_by_xpath('//android.widget.TextView[contains(@text, "Animat")]') self.assertEqual('Animation', el.text) el = self.driver.find_element_by_accessibility_id("App") el.click() els = self.driver.find_elements_by_android_uiautomator('new UiSelector().clickable(true)') # there are more, but at least 10 visible self.assertLess(10, len(els)) # the list includes 2 before the main visible elements self.assertEqual('Action Bar', els[2].text) els = self.driver.find_elements_by_xpath('//android.widget.TextView') self.assertLess(10, len(els)) self.assertEqual('Action Bar', els[1].text) def test_scroll(self): sleep(2) els = self.driver.find_elements_by_xpath('//android.widget.TextView') self.driver.scroll(els[7], els[3]) el = self.driver.find_element_by_accessibility_id('Views') def test_smiley_face(self): # just for the fun of it. # this doesn't really assert anything. self.driver.find_element_by_accessibility_id('Graphics').click() els = self.driver.find_elements_by_class_name('android.widget.TextView') self.driver.scroll(els[len(els)-1], els[0]) el = None try: el = self.driver.find_element_by_accessibility_id('Touch Paint') except Exception as e: els = self.driver.find_elements_by_class_name('android.widget.TextView') self.driver.scroll(els[len(els)-1], els[0]) if el is None: el = self.driver.find_element_by_accessibility_id('Touch Paint') el.click() # paint e1 = TouchAction() e1.press(x=150, y=100).release() e2 = TouchAction() e2.press(x=250, y=100).release() smile = TouchAction() smile.press(x=110, y=200) \ .move_to(x=1, y=1) \ .move_to(x=1, y=1) \ .move_to(x=1, y=1) \ .move_to(x=1, y=1) \ .move_to(x=1, y=1) \ .move_to(x=2, y=1) \ .move_to(x=2, y=1) \ .move_to(x=2, y=1) \ .move_to(x=2, y=1) \ .move_to(x=2, y=1) \ .move_to(x=3, y=1) \ .move_to(x=3, y=1) \ .move_to(x=3, y=1) \ .move_to(x=3, y=1) \ .move_to(x=3, y=1) \ .move_to(x=4, y=1) \ .move_to(x=4, y=1) \ .move_to(x=4, y=1) \ .move_to(x=4, y=1) \ .move_to(x=4, y=1) \ .move_to(x=5, y=1) \ .move_to(x=5, y=1) \ .move_to(x=5, y=1) \ .move_to(x=5, y=1) \ .move_to(x=5, y=1) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=0) \ .move_to(x=5, y=-1) \ .move_to(x=5, y=-1) \ .move_to(x=5, y=-1) \ .move_to(x=5, y=-1) \ .move_to(x=5, y=-1) \ .move_to(x=4, y=-1) \ .move_to(x=4, y=-1) \ .move_to(x=4, y=-1) \ .move_to(x=4, y=-1) \ .move_to(x=4, y=-1) \ .move_to(x=3, y=-1) \ .move_to(x=3, y=-1) \ .move_to(x=3, y=-1) \ .move_to(x=3, y=-1) \ .move_to(x=3, y=-1) \ .move_to(x=2, y=-1) \ .move_to(x=2, y=-1) \ .move_to(x=2, y=-1) \ .move_to(x=2, y=-1) \ .move_to(x=2, y=-1) \ .move_to(x=1, y=-1) \ .move_to(x=1, y=-1) \ .move_to(x=1, y=-1) \ .move_to(x=1, y=-1) \ .move_to(x=1, y=-1) smile.release() ma = MultiAction(self.driver) ma.add(e1, e2, smile) ma.perform() # so you can see it sleep(10) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(ComplexAndroidTests) unittest.TextTestRunner(verbosity=2).run(suite)
apache-2.0
factorlibre/account-financial-tools
account_asset_management_xls/report/__init__.py
34
1037
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import account_asset_report_xls
agpl-3.0
sloanyang/aquantic
Tools/Scripts/webkitpy/tool/multicommandtool.py
121
12664
# Copyright (c) 2009 Google Inc. All rights reserved. # Copyright (c) 2009 Apple 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. # # MultiCommandTool provides a framework for writing svn-like/git-like tools # which are called with the following format: # tool-name [global options] command-name [command options] import logging import sys from optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option from webkitpy.tool.grammar import pluralize _log = logging.getLogger(__name__) class TryAgain(Exception): pass class Command(object): name = None show_in_main_help = False help_text = None long_help = None argument_names = None def __init__(self, options=None, requires_local_commits=False): self.required_arguments = self._parse_required_arguments(self.argument_names) self.options = options self.requires_local_commits = requires_local_commits self._tool = None # option_parser can be overriden by the tool using set_option_parser # This default parser will be used for standalone_help printing. self.option_parser = HelpPrintingOptionParser(usage=SUPPRESS_USAGE, add_help_option=False, option_list=self.options) def _exit(self, code): sys.exit(code) # This design is slightly awkward, but we need the # the tool to be able to create and modify the option_parser # before it knows what Command to run. def set_option_parser(self, option_parser): self.option_parser = option_parser self._add_options_to_parser() def _add_options_to_parser(self): options = self.options or [] for option in options: self.option_parser.add_option(option) # The tool calls bind_to_tool on each Command after adding it to its list. def bind_to_tool(self, tool): # Command instances can only be bound to one tool at a time. if self._tool and tool != self._tool: raise Exception("Command already bound to tool!") self._tool = tool @staticmethod def _parse_required_arguments(argument_names): required_args = [] if not argument_names: return required_args split_args = argument_names.split(" ") for argument in split_args: if argument[0] == '[': # For now our parser is rather dumb. Do some minimal validation that # we haven't confused it. if argument[-1] != ']': raise Exception("Failure to parse argument string %s. Argument %s is missing ending ]" % (argument_names, argument)) else: required_args.append(argument) return required_args def name_with_arguments(self): usage_string = self.name if self.options: usage_string += " [options]" if self.argument_names: usage_string += " " + self.argument_names return usage_string def parse_args(self, args): return self.option_parser.parse_args(args) def check_arguments_and_execute(self, options, args, tool=None): if len(args) < len(self.required_arguments): _log.error("%s required, %s provided. Provided: %s Required: %s\nSee '%s help %s' for usage." % ( pluralize("argument", len(self.required_arguments)), pluralize("argument", len(args)), "'%s'" % " ".join(args), " ".join(self.required_arguments), tool.name(), self.name)) return 1 return self.execute(options, args, tool) or 0 def standalone_help(self): help_text = self.name_with_arguments().ljust(len(self.name_with_arguments()) + 3) + self.help_text + "\n\n" if self.long_help: help_text += "%s\n\n" % self.long_help help_text += self.option_parser.format_option_help(IndentedHelpFormatter()) return help_text def execute(self, options, args, tool): raise NotImplementedError, "subclasses must implement" # main() exists so that Commands can be turned into stand-alone scripts. # Other parts of the code will likely require modification to work stand-alone. def main(self, args=sys.argv): (options, args) = self.parse_args(args) # Some commands might require a dummy tool return self.check_arguments_and_execute(options, args) class HelpPrintingOptionParser(OptionParser): def __init__(self, epilog_method=None, *args, **kwargs): self.epilog_method = epilog_method OptionParser.__init__(self, *args, **kwargs) def error(self, msg): self.print_usage(sys.stderr) error_message = "%s: error: %s\n" % (self.get_prog_name(), msg) # This method is overriden to add this one line to the output: error_message += "\nType \"%s --help\" to see usage.\n" % self.get_prog_name() self.exit(1, error_message) # We override format_epilog to avoid the default formatting which would paragraph-wrap the epilog # and also to allow us to compute the epilog lazily instead of in the constructor (allowing it to be context sensitive). def format_epilog(self, epilog): if self.epilog_method: return "\n%s\n" % self.epilog_method() return "" class HelpCommand(Command): name = "help" help_text = "Display information about this program or its subcommands" argument_names = "[COMMAND]" def __init__(self): options = [ make_option("-a", "--all-commands", action="store_true", dest="show_all_commands", help="Print all available commands"), ] Command.__init__(self, options) self.show_all_commands = False # A hack used to pass --all-commands to _help_epilog even though it's called by the OptionParser. def _help_epilog(self): # Only show commands which are relevant to this checkout's SCM system. Might this be confusing to some users? if self.show_all_commands: epilog = "All %prog commands:\n" relevant_commands = self._tool.commands[:] else: epilog = "Common %prog commands:\n" relevant_commands = filter(self._tool.should_show_in_main_help, self._tool.commands) longest_name_length = max(map(lambda command: len(command.name), relevant_commands)) relevant_commands.sort(lambda a, b: cmp(a.name, b.name)) command_help_texts = map(lambda command: " %s %s\n" % (command.name.ljust(longest_name_length), command.help_text), relevant_commands) epilog += "%s\n" % "".join(command_help_texts) epilog += "See '%prog help --all-commands' to list all commands.\n" epilog += "See '%prog help COMMAND' for more information on a specific command.\n" return epilog.replace("%prog", self._tool.name()) # Use of %prog here mimics OptionParser.expand_prog_name(). # FIXME: This is a hack so that we don't show --all-commands as a global option: def _remove_help_options(self): for option in self.options: self.option_parser.remove_option(option.get_opt_string()) def execute(self, options, args, tool): if args: command = self._tool.command_by_name(args[0]) if command: print command.standalone_help() return 0 self.show_all_commands = options.show_all_commands self._remove_help_options() self.option_parser.print_help() return 0 class MultiCommandTool(object): global_options = None def __init__(self, name=None, commands=None): self._name = name or OptionParser(prog=name).get_prog_name() # OptionParser has nice logic for fetching the name. # Allow the unit tests to disable command auto-discovery. self.commands = commands or [cls() for cls in self._find_all_commands() if cls.name] self.help_command = self.command_by_name(HelpCommand.name) # Require a help command, even if the manual test list doesn't include one. if not self.help_command: self.help_command = HelpCommand() self.commands.append(self.help_command) for command in self.commands: command.bind_to_tool(self) @classmethod def _add_all_subclasses(cls, class_to_crawl, seen_classes): for subclass in class_to_crawl.__subclasses__(): if subclass not in seen_classes: seen_classes.add(subclass) cls._add_all_subclasses(subclass, seen_classes) @classmethod def _find_all_commands(cls): commands = set() cls._add_all_subclasses(Command, commands) return sorted(commands) def name(self): return self._name def _create_option_parser(self): usage = "Usage: %prog [options] COMMAND [ARGS]" return HelpPrintingOptionParser(epilog_method=self.help_command._help_epilog, prog=self.name(), usage=usage) @staticmethod def _split_command_name_from_args(args): # Assume the first argument which doesn't start with "-" is the command name. command_index = 0 for arg in args: if arg[0] != "-": break command_index += 1 else: return (None, args[:]) command = args[command_index] return (command, args[:command_index] + args[command_index + 1:]) def command_by_name(self, command_name): for command in self.commands: if command_name == command.name: return command return None def path(self): raise NotImplementedError, "subclasses must implement" def command_completed(self): pass def should_show_in_main_help(self, command): return command.show_in_main_help def should_execute_command(self, command): return True def _add_global_options(self, option_parser): global_options = self.global_options or [] for option in global_options: option_parser.add_option(option) def handle_global_options(self, options): pass def main(self, argv=sys.argv): (command_name, args) = self._split_command_name_from_args(argv[1:]) option_parser = self._create_option_parser() self._add_global_options(option_parser) command = self.command_by_name(command_name) or self.help_command if not command: option_parser.error("%s is not a recognized command" % command_name) command.set_option_parser(option_parser) (options, args) = command.parse_args(args) self.handle_global_options(options) (should_execute, failure_reason) = self.should_execute_command(command) if not should_execute: _log.error(failure_reason) return 0 # FIXME: Should this really be 0? while True: try: result = command.check_arguments_and_execute(options, args, self) break except TryAgain, e: pass self.command_completed() return result
gpl-2.0
brishtiteveja/sherlockcoin
contrib/devtools/fix-copyright-headers.py
311
1474
#!/usr/bin/env python ''' Run this script inside of src/ and it will look for all the files that were changed this year that still have the last year in the copyright headers, and it will fix the headers on that file using a perl regex one liner. For example: if it finds something like this and we're in 2014 // Copyright (c) 2009-2013 The Bitcoin developers it will change it to // Copyright (c) 2009-2014 The Bitcoin developers It will do this for all the files in the folder and its children. Author: @gubatron ''' import os import time year = time.gmtime()[0] last_year = year - 1 command = "perl -pi -e 's/%s The Bitcoin/%s The Bitcoin/' %s" listFilesCommand = "find . | grep %s" extensions = [".cpp",".h"] def getLastGitModifiedDate(filePath): gitGetLastCommitDateCommand = "git log " + filePath +" | grep Date | head -n 1" p = os.popen(gitGetLastCommitDateCommand) result = "" for l in p: result = l break result = result.replace("\n","") return result n=1 for extension in extensions: foundFiles = os.popen(listFilesCommand % extension) for filePath in foundFiles: filePath = filePath[1:-1] if filePath.endswith(extension): filePath = os.getcwd() + filePath modifiedTime = getLastGitModifiedDate(filePath) if len(modifiedTime) > 0 and str(year) in modifiedTime: print n,"Last Git Modified: ", modifiedTime, " - ", filePath os.popen(command % (last_year,year,filePath)) n = n + 1
mit
eadgarchen/tensorflow
tensorflow/contrib/keras/api/keras/preprocessing/image/__init__.py
71
2059
# 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. # ============================================================================== """Keras data preprocessing utils for image data.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.keras._impl.keras.preprocessing.image import apply_transform from tensorflow.python.keras._impl.keras.preprocessing.image import array_to_img from tensorflow.python.keras._impl.keras.preprocessing.image import DirectoryIterator from tensorflow.python.keras._impl.keras.preprocessing.image import flip_axis from tensorflow.python.keras._impl.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras._impl.keras.preprocessing.image import img_to_array from tensorflow.python.keras._impl.keras.preprocessing.image import Iterator from tensorflow.python.keras._impl.keras.preprocessing.image import load_img from tensorflow.python.keras._impl.keras.preprocessing.image import NumpyArrayIterator from tensorflow.python.keras._impl.keras.preprocessing.image import random_channel_shift from tensorflow.python.keras._impl.keras.preprocessing.image import random_rotation from tensorflow.python.keras._impl.keras.preprocessing.image import random_shear from tensorflow.python.keras._impl.keras.preprocessing.image import random_shift from tensorflow.python.keras._impl.keras.preprocessing.image import random_zoom del absolute_import del division del print_function
apache-2.0
daliguro/tf101-kernel-test
tools/perf/scripts/python/failed-syscalls-by-pid.py
11180
2058
# failed system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide failed system call totals, broken down by pid. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_error_totals() def raw_syscalls__sys_exit(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, ret): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return if ret < 0: try: syscalls[common_comm][common_pid][id][ret] += 1 except TypeError: syscalls[common_comm][common_pid][id][ret] = 1 def print_error_totals(): if for_comm is not None: print "\nsyscall errors for %s:\n\n" % (for_comm), else: print "\nsyscall errors:\n\n", print "%-30s %10s\n" % ("comm [pid]", "count"), print "%-30s %10s\n" % ("------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id in id_keys: print " syscall: %-16s\n" % syscall_name(id), ret_keys = syscalls[comm][pid][id].keys() for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True): print " err = %-20s %10d\n" % (strerror(ret), val),
gpl-2.0
helldorado/ansible
lib/ansible/modules/net_tools/basics/uri.py
7
22132
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2013, Romeo Theriault <romeot () hawaii.edu> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: uri short_description: Interacts with webservices description: - Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms. - For Windows targets, use the M(win_uri) module instead. version_added: "1.1" options: url: description: - HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path type: str required: true dest: description: - A path of where to download the file to (if desired). If I(dest) is a directory, the basename of the file on the remote server will be used. type: path url_username: description: - A username for the module to use for Digest, Basic or WSSE authentication. type: str aliases: [ user ] url_password: description: - A password for the module to use for Digest, Basic or WSSE authentication. type: str aliases: [ password ] body: description: - The body of the http request/response to the web service. If C(body_format) is set to 'json' it will take an already formatted JSON string or convert a data structure into JSON. If C(body_format) is set to 'form-urlencoded' it will convert a dictionary or list of tuples into an 'application/x-www-form-urlencoded' string. (Added in v2.7) type: raw body_format: description: - The serialization format of the body. When set to C(json) or C(form-urlencoded), encodes the body argument, if needed, and automatically sets the Content-Type header accordingly. As of C(2.3) it is possible to override the `Content-Type` header, when set to C(json) or C(form-urlencoded) via the I(headers) option. type: str choices: [ form-urlencoded, json, raw ] default: raw version_added: "2.0" method: description: - The HTTP method of the request or response. - In more recent versions we do not restrict the method at the module level anymore but it still must be a valid method accepted by the service handling the request. type: str default: GET return_content: description: - Whether or not to return the body of the response as a "content" key in the dictionary result. - Independently of this option, if the reported Content-type is "application/json", then the JSON is always loaded into a key called C(json) in the dictionary results. type: bool default: no force_basic_auth: description: - Force the sending of the Basic authentication header upon initial request. - The library used by the uri module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. type: bool default: no follow_redirects: description: - Whether or not the URI module should follow redirects. C(all) will follow all redirects. C(safe) will follow only "safe" redirects, where "safe" means that the client is only doing a GET or HEAD on the URI to which it is being redirected. C(none) will not follow any redirects. Note that C(yes) and C(no) choices are accepted for backwards compatibility, where C(yes) is the equivalent of C(all) and C(no) is the equivalent of C(safe). C(yes) and C(no) are deprecated and will be removed in some future version of Ansible. type: str choices: ['all', 'no', 'none', 'safe', 'urllib2', 'yes'] default: safe creates: description: - A filename, when it already exists, this step will not be run. type: path removes: description: - A filename, when it does not exist, this step will not be run. type: path status_code: description: - A list of valid, numeric, HTTP status codes that signifies success of the request. type: list default: [ 200 ] timeout: description: - The socket level timeout in seconds type: int default: 30 headers: description: - Add custom HTTP headers to a request in the format of a YAML hash. As of C(2.3) supplying C(Content-Type) here will override the header generated by supplying C(json) or C(form-urlencoded) for I(body_format). type: dict version_added: '2.1' validate_certs: description: - If C(no), SSL certificates will not be validated. - This should only set to C(no) used on personally controlled sites using self-signed certificates. - Prior to 1.9.2 the code defaulted to C(no). type: bool default: yes version_added: '1.9.2' client_cert: description: - PEM formatted certificate chain file to be used for SSL client authentication. - This file can also include the key as well, and if the key is included, I(client_key) is not required type: path version_added: '2.4' client_key: description: - PEM formatted file that contains your private key to be used for SSL client authentication. - If I(client_cert) contains both the certificate and key, this option is not required. type: path version_added: '2.4' src: description: - Path to file to be submitted to the remote server. - Cannot be used with I(body). type: path version_added: '2.7' remote_src: description: - If C(no), the module will search for src on originating/master machine. - If C(yes) the module will use the C(src) path on the remote/target machine. type: bool default: no version_added: '2.7' force: description: - If C(yes) do not get a cached copy. type: bool default: no aliases: [ thirsty ] use_proxy: description: - If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts. type: bool default: yes unix_socket: description: - Path to Unix domain socket to use for connection version_added: '2.8' http_agent: description: - Header to identify as, generally appears in web server logs. type: str default: ansible-httpget notes: - The dependency on httplib2 was removed in Ansible 2.1. - The module returns all the HTTP headers in lower-case. - For Windows targets, use the M(win_uri) module instead. seealso: - module: get_url - module: win_uri author: - Romeo Theriault (@romeotheriault) extends_documentation_fragment: files ''' EXAMPLES = r''' - name: Check that you can connect (GET) to a page and it returns a status 200 uri: url: http://www.example.com - name: Check that a page returns a status 200 and fail if the word AWESOME is not in the page contents uri: url: http://www.example.com return_content: yes register: this failed_when: "'AWESOME' not in this.content" - name: Create a JIRA issue uri: url: https://your.jira.example.com/rest/api/2/issue/ user: your_username password: your_pass method: POST body: "{{ lookup('file','issue.json') }}" force_basic_auth: yes status_code: 201 body_format: json - name: Login to a form based webpage, then use the returned cookie to access the app in later tasks uri: url: https://your.form.based.auth.example.com/index.php method: POST body_format: form-urlencoded body: name: your_username password: your_password enter: Sign in status_code: 302 register: login - name: Login to a form based webpage using a list of tuples uri: url: https://your.form.based.auth.example.com/index.php method: POST body_format: form-urlencoded body: - [ name, your_username ] - [ password, your_password ] - [ enter, Sign in ] status_code: 302 register: login - name: Connect to website using a previously stored cookie uri: url: https://your.form.based.auth.example.com/dashboard.php method: GET return_content: yes headers: Cookie: "{{ login.set_cookie }}" - name: Queue build of a project in Jenkins uri: url: http://{{ jenkins.host }}/job/{{ jenkins.job }}/build?token={{ jenkins.token }} user: "{{ jenkins.user }}" password: "{{ jenkins.password }}" method: GET force_basic_auth: yes status_code: 201 - name: POST from contents of local file uri: url: https://httpbin.org/post method: POST src: file.json - name: POST from contents of remote file uri: url: https://httpbin.org/post method: POST src: /path/to/my/file.json remote_src: yes ''' RETURN = r''' # The return information includes all the HTTP headers in lower-case. elapsed: description: The number of seconds that elapsed while performing the download returned: always type: int sample: 23 msg: description: The HTTP message from the request returned: always type: str sample: OK (unknown bytes) redirected: description: Whether the request was redirected returned: always type: bool sample: false status: description: The HTTP status code from the request returned: always type: int sample: 200 url: description: The actual URL used for the request returned: always type: str sample: https://www.ansible.com/ ''' import cgi import datetime import json import os import re import shutil import sys import tempfile from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import PY2, iteritems, string_types from ansible.module_utils.six.moves.urllib.parse import urlencode, urlsplit from ansible.module_utils._text import to_native, to_text from ansible.module_utils.common._collections_compat import Mapping, Sequence from ansible.module_utils.urls import fetch_url, url_argument_spec JSON_CANDIDATES = ('text', 'json', 'javascript') def format_message(err, resp): msg = resp.pop('msg') return err + (' %s' % msg if msg else '') def write_file(module, url, dest, content, resp): # create a tempfile with some test content fd, tmpsrc = tempfile.mkstemp(dir=module.tmpdir) f = open(tmpsrc, 'wb') try: f.write(content) except Exception as e: os.remove(tmpsrc) msg = format_message("Failed to create temporary content file: %s" % to_native(e), resp) module.fail_json(msg=msg, **resp) f.close() checksum_src = None checksum_dest = None # raise an error if there is no tmpsrc file if not os.path.exists(tmpsrc): os.remove(tmpsrc) msg = format_message("Source '%s' does not exist" % tmpsrc, resp) module.fail_json(msg=msg, **resp) if not os.access(tmpsrc, os.R_OK): os.remove(tmpsrc) msg = format_message("Source '%s' not readable" % tmpsrc, resp) module.fail_json(msg=msg, **resp) checksum_src = module.sha1(tmpsrc) # check if there is no dest file if os.path.exists(dest): # raise an error if copy has no permission on dest if not os.access(dest, os.W_OK): os.remove(tmpsrc) msg = format_message("Destination '%s' not writable" % dest, resp) module.fail_json(msg=msg, **resp) if not os.access(dest, os.R_OK): os.remove(tmpsrc) msg = format_message("Destination '%s' not readable" % dest, resp) module.fail_json(msg=msg, **resp) checksum_dest = module.sha1(dest) else: if not os.access(os.path.dirname(dest), os.W_OK): os.remove(tmpsrc) msg = format_message("Destination dir '%s' not writable" % os.path.dirname(dest), resp) module.fail_json(msg=msg, **resp) if checksum_src != checksum_dest: try: shutil.copyfile(tmpsrc, dest) except Exception as e: os.remove(tmpsrc) msg = format_message("failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)), resp) module.fail_json(msg=msg, **resp) os.remove(tmpsrc) def url_filename(url): fn = os.path.basename(urlsplit(url)[2]) if fn == '': return 'index.html' return fn def absolute_location(url, location): """Attempts to create an absolute URL based on initial URL, and next URL, specifically in the case of a ``Location`` header. """ if '://' in location: return location elif location.startswith('/'): parts = urlsplit(url) base = url.replace(parts[2], '') return '%s%s' % (base, location) elif not location.startswith('/'): base = os.path.dirname(url) return '%s/%s' % (base, location) else: return location def kv_list(data): ''' Convert data into a list of key-value tuples ''' if data is None: return None if isinstance(data, Sequence): return list(data) if isinstance(data, Mapping): return list(data.items()) raise TypeError('cannot form-urlencode body, expect list or dict') def form_urlencoded(body): ''' Convert data into a form-urlencoded string ''' if isinstance(body, string_types): return body if isinstance(body, (Mapping, Sequence)): result = [] # Turn a list of lists into a list of tupples that urlencode accepts for key, values in kv_list(body): if isinstance(values, string_types) or not isinstance(values, (Mapping, Sequence)): values = [values] for value in values: if value is not None: result.append((to_text(key), to_text(value))) return urlencode(result, doseq=True) return body def uri(module, url, dest, body, body_format, method, headers, socket_timeout): # is dest is set and is a directory, let's check if we get redirected and # set the filename from that url redirected = False redir_info = {} r = {} src = module.params['src'] if src: try: headers.update({ 'Content-Length': os.stat(src).st_size }) data = open(src, 'rb') except OSError: module.fail_json(msg='Unable to open source file %s' % src, elapsed=0) else: data = body kwargs = {} if dest is not None: # Stash follow_redirects, in this block we don't want to follow # we'll reset back to the supplied value soon follow_redirects = module.params['follow_redirects'] module.params['follow_redirects'] = False if os.path.isdir(dest): # first check if we are redirected to a file download _, redir_info = fetch_url(module, url, data=body, headers=headers, method=method, timeout=socket_timeout, unix_socket=module.params['unix_socket']) # if we are redirected, update the url with the location header, # and update dest with the new url filename if redir_info['status'] in (301, 302, 303, 307): url = redir_info['location'] redirected = True dest = os.path.join(dest, url_filename(url)) # if destination file already exist, only download if file newer if os.path.exists(dest): kwargs['last_mod_time'] = datetime.datetime.utcfromtimestamp(os.path.getmtime(dest)) # Reset follow_redirects back to the stashed value module.params['follow_redirects'] = follow_redirects resp, info = fetch_url(module, url, data=data, headers=headers, method=method, timeout=socket_timeout, unix_socket=module.params['unix_socket'], **kwargs) try: content = resp.read() except AttributeError: # there was no content, but the error read() # may have been stored in the info as 'body' content = info.pop('body', '') if src: # Try to close the open file handle try: data.close() except Exception: pass r['redirected'] = redirected or info['url'] != url r.update(redir_info) r.update(info) return r, content, dest def main(): argument_spec = url_argument_spec() argument_spec.update( dest=dict(type='path'), url_username=dict(type='str', aliases=['user']), url_password=dict(type='str', aliases=['password'], no_log=True), body=dict(type='raw'), body_format=dict(type='str', default='raw', choices=['form-urlencoded', 'json', 'raw']), src=dict(type='path'), method=dict(type='str', default='GET'), return_content=dict(type='bool', default=False), follow_redirects=dict(type='str', default='safe', choices=['all', 'no', 'none', 'safe', 'urllib2', 'yes']), creates=dict(type='path'), removes=dict(type='path'), status_code=dict(type='list', default=[200]), timeout=dict(type='int', default=30), headers=dict(type='dict', default={}), unix_socket=dict(type='path'), ) module = AnsibleModule( argument_spec=argument_spec, add_file_common_args=True, mutually_exclusive=[['body', 'src']], ) url = module.params['url'] body = module.params['body'] body_format = module.params['body_format'].lower() method = module.params['method'].upper() dest = module.params['dest'] return_content = module.params['return_content'] creates = module.params['creates'] removes = module.params['removes'] status_code = [int(x) for x in list(module.params['status_code'])] socket_timeout = module.params['timeout'] dict_headers = module.params['headers'] if not re.match('^[A-Z]+$', method): module.fail_json(msg="Parameter 'method' needs to be a single word in uppercase, like GET or POST.") if body_format == 'json': # Encode the body unless its a string, then assume it is pre-formatted JSON if not isinstance(body, string_types): body = json.dumps(body) if 'content-type' not in [header.lower() for header in dict_headers]: dict_headers['Content-Type'] = 'application/json' elif body_format == 'form-urlencoded': if not isinstance(body, string_types): try: body = form_urlencoded(body) except ValueError as e: module.fail_json(msg='failed to parse body as form_urlencoded: %s' % to_native(e), elapsed=0) if 'content-type' not in [header.lower() for header in dict_headers]: dict_headers['Content-Type'] = 'application/x-www-form-urlencoded' if creates is not None: # do not run the command if the line contains creates=filename # and the filename already exists. This allows idempotence # of uri executions. if os.path.exists(creates): module.exit_json(stdout="skipped, since '%s' exists" % creates, changed=False) if removes is not None: # do not run the command if the line contains removes=filename # and the filename does not exist. This allows idempotence # of uri executions. if not os.path.exists(removes): module.exit_json(stdout="skipped, since '%s' does not exist" % removes, changed=False) # Make the request start = datetime.datetime.utcnow() resp, content, dest = uri(module, url, dest, body, body_format, method, dict_headers, socket_timeout) resp['elapsed'] = (datetime.datetime.utcnow() - start).seconds resp['status'] = int(resp['status']) resp['changed'] = False # Write the file out if requested if dest is not None: if resp['status'] in status_code and resp['status'] != 304: write_file(module, url, dest, content, resp) # allow file attribute changes resp['changed'] = True module.params['path'] = dest file_args = module.load_file_common_arguments(module.params) file_args['path'] = dest resp['changed'] = module.set_fs_attributes_if_different(file_args, resp['changed']) resp['path'] = dest # Transmogrify the headers, replacing '-' with '_', since variables don't # work with dashes. # In python3, the headers are title cased. Lowercase them to be # compatible with the python2 behaviour. uresp = {} for key, value in iteritems(resp): ukey = key.replace("-", "_").lower() uresp[ukey] = value if 'location' in uresp: uresp['location'] = absolute_location(url, uresp['location']) # Default content_encoding to try content_encoding = 'utf-8' if 'content_type' in uresp: content_type, params = cgi.parse_header(uresp['content_type']) if 'charset' in params: content_encoding = params['charset'] u_content = to_text(content, encoding=content_encoding) if any(candidate in content_type for candidate in JSON_CANDIDATES): try: js = json.loads(u_content) uresp['json'] = js except Exception: if PY2: sys.exc_clear() # Avoid false positive traceback in fail_json() on Python 2 else: u_content = to_text(content, encoding=content_encoding) if resp['status'] not in status_code: uresp['msg'] = 'Status code was %s and not %s: %s' % (resp['status'], status_code, uresp.get('msg', '')) module.fail_json(content=u_content, **uresp) elif return_content: module.exit_json(content=u_content, **uresp) else: module.exit_json(**uresp) if __name__ == '__main__': main()
gpl-3.0
virajprabhu/oppia
core/domain/param_domain.py
15
4731
# coding: utf-8 # # Copyright 2014 The Oppia 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. """Classes relating to parameters.""" __author__ = 'Sean Lip' import feconf import re import utils from core.domain import obj_services from core.domain import value_generators_domain class ParamSpec(object): """Value object for an exploration parameter specification.""" def __init__(self, obj_type): self.obj_type = obj_type def to_dict(self): return { 'obj_type': self.obj_type, } @classmethod def from_dict(cls, param_spec_dict): return cls(param_spec_dict['obj_type']) def validate(self): # Ensure that this object class exists. obj_services.Registry.get_object_class_by_type(self.obj_type) # Ensure the obj_type is UnicodeString, since that is the only supported # type of ParamSpec. # TODO(bhenning): Expand parameter support in the editor to multiple # types, then validate all changes and rule inputs to properly match the # type of the parameter. if self.obj_type != 'UnicodeString': raise utils.ValidationError( 'Only \'UnicodeString\' is the supported object type for ' 'parameters, not: %s' % self.obj_type) class ParamChange(object): """Value object for a parameter change.""" def __init__(self, name, generator_id, customization_args): # TODO(sll): Check that all required args for customization exist in # customization_args. self._name = name self._generator_id = generator_id self._customization_args = customization_args @property def name(self): return self._name @property def generator(self): return value_generators_domain.Registry.get_generator_class_by_id( self._generator_id)() @property def customization_args(self): return self._customization_args def to_dict(self): return { 'name': self.name, 'generator_id': self.generator.id, 'customization_args': self.customization_args } @classmethod def from_dict(cls, param_change_dict): return cls( param_change_dict['name'], param_change_dict['generator_id'], param_change_dict['customization_args'] ) def _get_value(self, context_params): """Generates a single value for a parameter change.""" return self.generator.generate_value( context_params, **self.customization_args) def get_normalized_value(self, obj_type, context_params): """Generates a single normalized value for a parameter change.""" raw_value = self._get_value(context_params) return obj_services.Registry.get_object_class_by_type( obj_type).normalize(raw_value) def validate(self): if not isinstance(self.name, basestring): raise utils.ValidationError( 'Expected param_change name to be a string, received %s' % self.name) if not re.match(feconf.ALPHANUMERIC_REGEX, self.name): raise utils.ValidationError( 'Only parameter names with characters in [a-zA-Z0-9] are ' 'accepted.') try: self.generator except KeyError: raise utils.ValidationError( 'Invalid generator id %s' % self._generator_id) except Exception: raise utils.ValidationError( 'Generator %s is not a valid generator for exploration ' 'parameters. Valid generators must not require any ' 'initialization arguments.' % self._generator_id) if not isinstance(self.customization_args, dict): raise utils.ValidationError( 'Expected a dict of customization_args, received %s' % self.customization_args) for arg_name in self.customization_args: if not isinstance(arg_name, basestring): raise Exception( 'Invalid parameter change customization_arg name: %s' % arg_name)
apache-2.0
proxysh/Safejumper-for-Desktop
buildlinux/env64/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py
39
2261
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import abc import math import six from cryptography import utils from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa @six.add_metaclass(abc.ABCMeta) class AsymmetricPadding(object): @abc.abstractproperty def name(self): """ A string naming this padding (e.g. "PSS", "PKCS1"). """ @utils.register_interface(AsymmetricPadding) class PKCS1v15(object): name = "EMSA-PKCS1-v1_5" @utils.register_interface(AsymmetricPadding) class PSS(object): MAX_LENGTH = object() name = "EMSA-PSS" def __init__(self, mgf, salt_length): self._mgf = mgf if (not isinstance(salt_length, six.integer_types) and salt_length is not self.MAX_LENGTH): raise TypeError("salt_length must be an integer.") if salt_length is not self.MAX_LENGTH and salt_length < 0: raise ValueError("salt_length must be zero or greater.") self._salt_length = salt_length @utils.register_interface(AsymmetricPadding) class OAEP(object): name = "EME-OAEP" def __init__(self, mgf, algorithm, label): if not isinstance(algorithm, hashes.HashAlgorithm): raise TypeError("Expected instance of hashes.HashAlgorithm.") self._mgf = mgf self._algorithm = algorithm self._label = label class MGF1(object): MAX_LENGTH = object() def __init__(self, algorithm): if not isinstance(algorithm, hashes.HashAlgorithm): raise TypeError("Expected instance of hashes.HashAlgorithm.") self._algorithm = algorithm def calculate_max_pss_salt_length(key, hash_algorithm): if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): raise TypeError("key must be an RSA public or private key") # bit length - 1 per RFC 3447 emlen = int(math.ceil((key.key_size - 1) / 8.0)) salt_length = emlen - hash_algorithm.digest_size - 2 assert salt_length >= 0 return salt_length
gpl-2.0
reubano/hdxscraper-fao
setup.py
5
1612
import sys import app import pkutils try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages sys.dont_write_bytecode = True requirements = list(pkutils.parse_requirements('requirements.txt')) dependencies = list(pkutils.parse_requirements('requirements.txt', dep=True)) dev_requirements = list(pkutils.parse_requirements('dev-requirements.txt')) readme = pkutils.read('README.md') license = app.__license__ name = app.__title__ gh = 'https://github.com/reubano' setup( name=name, version=app.__version__, description=app.__description__, long_description=readme, author=app.__author__, author_email=app.__email__, url='%s/%s' % (gh, name), download_url='%s/%s/downloads/%s*.tgz' % (gh, name, name), include_package_data=True, install_requires=requirements, dependency_links=dependencies, tests_require=dev_requirements, classifiers=[ pkutils.LICENSES[license], 'Development Status :: 4 - Beta', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: Microsoft :: POSIX' ], keywords=[name, 'scraperwiki', 'api'], packages=find_packages(exclude=['tests']), package_data={}, zip_safe=False, license=license, platforms=['MacOS X', 'Windows', 'Linux'], )
mit
tobegit3hub/glance_docker
glance/cmd/control.py
15
13889
# Copyright (c) 2011 OpenStack Foundation # # 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. """ Helper script for starting/stopping/reloading Glance server programs. Thanks for some of the code, Swifties ;) """ from __future__ import print_function from __future__ import with_statement import argparse import fcntl import os import resource import signal import subprocess import sys import tempfile import time # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) from oslo_config import cfg from oslo_utils import units # NOTE(jokke): simplified transition to py3, behaves like py2 xrange from six.moves import range from glance.common import config from glance import i18n _ = i18n._ CONF = cfg.CONF ALL_COMMANDS = ['start', 'status', 'stop', 'shutdown', 'restart', 'reload', 'force-reload'] ALL_SERVERS = ['api', 'registry', 'scrubber'] RELOAD_SERVERS = ['glance-api', 'glance-registry'] GRACEFUL_SHUTDOWN_SERVERS = ['glance-api', 'glance-registry', 'glance-scrubber'] MAX_DESCRIPTORS = 32768 MAX_MEMORY = 2 * units.Gi # 2 GB USAGE = """%(prog)s [options] <SERVER> <COMMAND> [CONFPATH] Where <SERVER> is one of: all, {0} And command is one of: {1} And CONFPATH is the optional configuration file to use.""".format( ', '.join(ALL_SERVERS), ', '.join(ALL_COMMANDS)) exitcode = 0 def gated_by(predicate): def wrap(f): def wrapped_f(*args): if predicate: return f(*args) else: return None return wrapped_f return wrap def pid_files(server, pid_file): pid_files = [] if pid_file: if os.path.exists(os.path.abspath(pid_file)): pid_files = [os.path.abspath(pid_file)] else: if os.path.exists('/var/run/glance/%s.pid' % server): pid_files = ['/var/run/glance/%s.pid' % server] for pid_file in pid_files: pid = int(open(pid_file).read().strip()) yield pid_file, pid def do_start(verb, pid_file, server, args): if verb != 'Respawn' and pid_file == CONF.pid_file: for pid_file, pid in pid_files(server, pid_file): if os.path.exists('/proc/%s' % pid): print(_("%(serv)s appears to already be running: %(pid)s") % {'serv': server, 'pid': pid_file}) return else: print(_("Removing stale pid file %s") % pid_file) os.unlink(pid_file) try: resource.setrlimit(resource.RLIMIT_NOFILE, (MAX_DESCRIPTORS, MAX_DESCRIPTORS)) resource.setrlimit(resource.RLIMIT_DATA, (MAX_MEMORY, MAX_MEMORY)) except ValueError: print(_('Unable to increase file descriptor limit. ' 'Running as non-root?')) os.environ['PYTHON_EGG_CACHE'] = '/tmp' def write_pid_file(pid_file, pid): with open(pid_file, 'w') as fp: fp.write('%d\n' % pid) def redirect_to_null(fds): with open(os.devnull, 'r+b') as nullfile: for desc in fds: # close fds try: os.dup2(nullfile.fileno(), desc) except OSError: pass def redirect_to_syslog(fds, server): log_cmd = 'logger' log_cmd_params = '-t "%s[%d]"' % (server, os.getpid()) process = subprocess.Popen([log_cmd, log_cmd_params], stdin=subprocess.PIPE) for desc in fds: # pipe to logger command try: os.dup2(process.stdin.fileno(), desc) except OSError: pass def redirect_stdio(server, capture_output): input = [sys.stdin.fileno()] output = [sys.stdout.fileno(), sys.stderr.fileno()] redirect_to_null(input) if capture_output: redirect_to_syslog(output, server) else: redirect_to_null(output) @gated_by(CONF.capture_output) def close_stdio_on_exec(): fds = [sys.stdin.fileno(), sys.stdout.fileno(), sys.stderr.fileno()] for desc in fds: # set close on exec flag fcntl.fcntl(desc, fcntl.F_SETFD, fcntl.FD_CLOEXEC) def launch(pid_file, conf_file=None, capture_output=False, await_time=0): args = [server] if conf_file: args += ['--config-file', conf_file] msg = (_('%(verb)sing %(serv)s with %(conf)s') % {'verb': verb, 'serv': server, 'conf': conf_file}) else: msg = (_('%(verb)sing %(serv)s') % {'verb': verb, 'serv': server}) print(msg) close_stdio_on_exec() pid = os.fork() if pid == 0: os.setsid() redirect_stdio(server, capture_output) try: os.execlp('%s' % server, *args) except OSError as e: msg = (_('unable to launch %(serv)s. Got error: %(e)s') % {'serv': server, 'e': e}) sys.exit(msg) sys.exit(0) else: write_pid_file(pid_file, pid) await_child(pid, await_time) return pid @gated_by(CONF.await_child) def await_child(pid, await_time): bail_time = time.time() + await_time while time.time() < bail_time: reported_pid, status = os.waitpid(pid, os.WNOHANG) if reported_pid == pid: global exitcode exitcode = os.WEXITSTATUS(status) break time.sleep(0.05) conf_file = None if args and os.path.exists(args[0]): conf_file = os.path.abspath(os.path.expanduser(args[0])) return launch(pid_file, conf_file, CONF.capture_output, CONF.await_child) def do_check_status(pid_file, server): if os.path.exists(pid_file): with open(pid_file, 'r') as pidfile: pid = pidfile.read().strip() print(_("%(serv)s (pid %(pid)s) is running...") % {'serv': server, 'pid': pid}) else: print(_("%s is stopped") % server) def get_pid_file(server, pid_file): pid_file = (os.path.abspath(pid_file) if pid_file else '/var/run/glance/%s.pid' % server) dir, file = os.path.split(pid_file) if not os.path.exists(dir): try: os.makedirs(dir) except OSError: pass if not os.access(dir, os.W_OK): fallback = os.path.join(tempfile.mkdtemp(), '%s.pid' % server) msg = (_('Unable to create pid file %(pid)s. Running as non-root?\n' 'Falling back to a temp file, you can stop %(service)s ' 'service using:\n' ' %(file)s %(server)s stop --pid-file %(fb)s') % {'pid': pid_file, 'service': server, 'file': __file__, 'server': server, 'fb': fallback}) print(msg) pid_file = fallback return pid_file def do_reload(pid_file, server): if server not in RELOAD_SERVERS: msg = (_('Reload of %(serv)s not supported') % {'serv': server}) sys.exit(msg) pid = None if os.path.exists(pid_file): with open(pid_file, 'r') as pidfile: pid = int(pidfile.read().strip()) else: msg = (_('Server %(serv)s is stopped') % {'serv': server}) sys.exit(msg) sig = signal.SIGHUP try: print(_('Reloading %(serv)s (pid %(pid)s) with signal(%(sig)s)') % {'serv': server, 'pid': pid, 'sig': sig}) os.kill(pid, sig) except OSError: print(_("Process %d not running") % pid) def do_stop(server, args, graceful=False): if graceful and server in GRACEFUL_SHUTDOWN_SERVERS: sig = signal.SIGHUP else: sig = signal.SIGTERM did_anything = False pfiles = pid_files(server, CONF.pid_file) for pid_file, pid in pfiles: did_anything = True try: os.unlink(pid_file) except OSError: pass try: print(_('Stopping %(serv)s (pid %(pid)s) with signal(%(sig)s)') % {'serv': server, 'pid': pid, 'sig': sig}) os.kill(pid, sig) except OSError: print(_("Process %d not running") % pid) for pid_file, pid in pfiles: for _junk in range(150): # 15 seconds if not os.path.exists('/proc/%s' % pid): break time.sleep(0.1) else: print(_('Waited 15 seconds for pid %(pid)s (%(file)s) to die;' ' giving up') % {'pid': pid, 'file': pid_file}) if not did_anything: print(_('%s is already stopped') % server) def add_command_parsers(subparsers): cmd_parser = argparse.ArgumentParser(add_help=False) cmd_subparsers = cmd_parser.add_subparsers(dest='command') for cmd in ALL_COMMANDS: parser = cmd_subparsers.add_parser(cmd) parser.add_argument('args', nargs=argparse.REMAINDER) for server in ALL_SERVERS: full_name = 'glance-' + server parser = subparsers.add_parser(server, parents=[cmd_parser]) parser.set_defaults(servers=[full_name]) parser = subparsers.add_parser(full_name, parents=[cmd_parser]) parser.set_defaults(servers=[full_name]) parser = subparsers.add_parser('all', parents=[cmd_parser]) parser.set_defaults(servers=['glance-' + s for s in ALL_SERVERS]) def main(): global exitcode opts = [ cfg.SubCommandOpt('server', title='Server types', help='Available server types', handler=add_command_parsers), cfg.StrOpt('pid-file', metavar='PATH', help='File to use as pid file. Default: ' '/var/run/glance/$server.pid.'), cfg.IntOpt('await-child', metavar='DELAY', default=0, help='Period to wait for service death ' 'in order to report exit code ' '(default is to not wait at all).'), cfg.BoolOpt('capture-output', default=False, help='Capture stdout/err in syslog ' 'instead of discarding it.'), cfg.BoolOpt('respawn', default=False, help='Restart service on unexpected death.'), ] CONF.register_cli_opts(opts) config.parse_args(usage=USAGE) @gated_by(CONF.await_child) @gated_by(CONF.respawn) def mutually_exclusive(): sys.stderr.write('--await-child and --respawn are mutually exclusive') sys.exit(1) mutually_exclusive() @gated_by(CONF.respawn) def anticipate_respawn(children): while children: pid, status = os.wait() if pid in children: (pid_file, server, args) = children.pop(pid) running = os.path.exists(pid_file) one_second_ago = time.time() - 1 bouncing = (running and os.path.getmtime(pid_file) >= one_second_ago) if running and not bouncing: args = (pid_file, server, args) new_pid = do_start('Respawn', *args) children[new_pid] = args else: rsn = 'bouncing' if bouncing else 'deliberately stopped' print(_('Suppressed respawn as %(serv)s was %(rsn)s.') % {'serv': server, 'rsn': rsn}) if CONF.server.command == 'start': children = {} for server in CONF.server.servers: pid_file = get_pid_file(server, CONF.pid_file) args = (pid_file, server, CONF.server.args) pid = do_start('Start', *args) children[pid] = args anticipate_respawn(children) if CONF.server.command == 'status': for server in CONF.server.servers: pid_file = get_pid_file(server, CONF.pid_file) do_check_status(pid_file, server) if CONF.server.command == 'stop': for server in CONF.server.servers: do_stop(server, CONF.server.args) if CONF.server.command == 'shutdown': for server in CONF.server.servers: do_stop(server, CONF.server.args, graceful=True) if CONF.server.command == 'restart': for server in CONF.server.servers: do_stop(server, CONF.server.args) for server in CONF.server.servers: pid_file = get_pid_file(server, CONF.pid_file) do_start('Restart', pid_file, server, CONF.server.args) if CONF.server.command in ('reload', 'force-reload'): for server in CONF.server.servers: pid_file = get_pid_file(server, CONF.pid_file) do_reload(pid_file, server) sys.exit(exitcode)
apache-2.0
proversity-org/edx-platform
pavelib/paver_tests/utils.py
3
3100
"""Unit tests for the Paver server tasks.""" import os from unittest import TestCase import paver.easy from paver import tasks from paver.easy import BuildFailure class PaverTestCase(TestCase): """ Base class for Paver test cases. """ def setUp(self): super(PaverTestCase, self).setUp() # Show full length diffs upon test failure self.maxDiff = None # pylint: disable=invalid-name # Create a mock Paver environment tasks.environment = MockEnvironment() # Don't run pre-reqs os.environ['NO_PREREQ_INSTALL'] = 'true' def tearDown(self): super(PaverTestCase, self).tearDown() tasks.environment = tasks.Environment() del os.environ['NO_PREREQ_INSTALL'] @property def task_messages(self): """Returns the messages output by the Paver task.""" return tasks.environment.messages @property def platform_root(self): """Returns the current platform's root directory.""" return os.getcwd() def reset_task_messages(self): """Clear the recorded message""" tasks.environment.messages = [] class MockEnvironment(tasks.Environment): """ Mock environment that collects information about Paver commands. """ def __init__(self): super(MockEnvironment, self).__init__() self.dry_run = True self.messages = [] def info(self, message, *args): """Capture any messages that have been recorded""" if args: output = message % args else: output = message if not output.startswith("--->"): self.messages.append(unicode(output)) def fail_on_eslint(*args): """ For our tests, we need the call for diff-quality running eslint reports to fail, since that is what is going to fail when we pass in a percentage ("p") requirement. """ if "eslint" in args[0]: # Essentially mock diff-quality exiting with 1 paver.easy.sh("exit 1") else: return def fail_on_pylint(*args): """ For our tests, we need the call for diff-quality running pylint reports to fail, since that is what is going to fail when we pass in a percentage ("p") requirement. """ if "pylint" in args[0]: # Essentially mock diff-quality exiting with 1 paver.easy.sh("exit 1") else: return def fail_on_npm_install(*args): """ For our tests, we need the call for diff-quality running pep8 reports to fail, since that is what is going to fail when we pass in a percentage ("p") requirement. """ if "npm install" in args[0]: raise BuildFailure('Subprocess return code: 1') else: return def unexpected_fail_on_npm_install(*args): """ For our tests, we need the call for diff-quality running pep8 reports to fail, since that is what is going to fail when we pass in a percentage ("p") requirement. """ if "npm install" in args[0]: raise BuildFailure('Subprocess return code: 50') else: return
agpl-3.0
unindented/streamcode
client/static/jsrepl/extern/python/reloop-closured/lib/python2.7/mimify.py
304
15021
#! /usr/bin/env python """Mimification and unmimification of mail messages. Decode quoted-printable parts of a mail message or encode using quoted-printable. Usage: mimify(input, output) unmimify(input, output, decode_base64 = 0) to encode and decode respectively. Input and output may be the name of a file or an open file object. Only a readline() method is used on the input file, only a write() method is used on the output file. When using file names, the input and output file names may be the same. Interactive usage: mimify.py -e [infile [outfile]] mimify.py -d [infile [outfile]] to encode and decode respectively. Infile defaults to standard input and outfile to standard output. """ # Configure MAXLEN = 200 # if lines longer than this, encode as quoted-printable CHARSET = 'ISO-8859-1' # default charset for non-US-ASCII mail QUOTE = '> ' # string replies are quoted with # End configure import re import warnings warnings.warn("the mimify module is deprecated; use the email package instead", DeprecationWarning, 2) __all__ = ["mimify","unmimify","mime_encode_header","mime_decode_header"] qp = re.compile('^content-transfer-encoding:\\s*quoted-printable', re.I) base64_re = re.compile('^content-transfer-encoding:\\s*base64', re.I) mp = re.compile('^content-type:.*multipart/.*boundary="?([^;"\n]*)', re.I|re.S) chrset = re.compile('^(content-type:.*charset=")(us-ascii|iso-8859-[0-9]+)(".*)', re.I|re.S) he = re.compile('^-*\n') mime_code = re.compile('=([0-9a-f][0-9a-f])', re.I) mime_head = re.compile('=\\?iso-8859-1\\?q\\?([^? \t\n]+)\\?=', re.I) repl = re.compile('^subject:\\s+re: ', re.I) class File: """A simple fake file object that knows about limited read-ahead and boundaries. The only supported method is readline().""" def __init__(self, file, boundary): self.file = file self.boundary = boundary self.peek = None def readline(self): if self.peek is not None: return '' line = self.file.readline() if not line: return line if self.boundary: if line == self.boundary + '\n': self.peek = line return '' if line == self.boundary + '--\n': self.peek = line return '' return line class HeaderFile: def __init__(self, file): self.file = file self.peek = None def readline(self): if self.peek is not None: line = self.peek self.peek = None else: line = self.file.readline() if not line: return line if he.match(line): return line while 1: self.peek = self.file.readline() if len(self.peek) == 0 or \ (self.peek[0] != ' ' and self.peek[0] != '\t'): return line line = line + self.peek self.peek = None def mime_decode(line): """Decode a single line of quoted-printable text to 8bit.""" newline = '' pos = 0 while 1: res = mime_code.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ chr(int(res.group(1), 16)) pos = res.end(0) return newline + line[pos:] def mime_decode_header(line): """Decode a header line to 8bit.""" newline = '' pos = 0 while 1: res = mime_head.search(line, pos) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = ' '.join(match.split('_')) newline = newline + line[pos:res.start(0)] + mime_decode(match) pos = res.end(0) return newline + line[pos:] def unmimify_part(ifile, ofile, decode_base64 = 0): """Convert a quoted-printable part of a MIME mail message to 8bit.""" multipart = None quoted_printable = 0 is_base64 = 0 is_repl = 0 if ifile.boundary and ifile.boundary[:2] == QUOTE: prefix = QUOTE else: prefix = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: return if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' line = mime_decode_header(line) if qp.match(line): quoted_printable = 1 continue # skip this header if decode_base64 and base64_re.match(line): is_base64 = 1 continue ofile.write(pref + line) if not prefix and repl.match(line): # we're dealing with a reply message is_repl = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): break if is_repl and (quoted_printable or multipart): is_repl = 0 # read body while 1: line = ifile.readline() if not line: return line = re.sub(mime_head, '\\1', line) if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' ## if is_repl and len(line) >= 4 and line[:4] == QUOTE+'--' and line[-3:] != '--\n': ## multipart = line[:-1] while multipart: if line == multipart + '--\n': ofile.write(pref + line) multipart = None line = None break if line == multipart + '\n': ofile.write(pref + line) nifile = File(ifile, multipart) unmimify_part(nifile, ofile, decode_base64) line = nifile.peek if not line: # premature end of file break continue # not a boundary between parts break if line and quoted_printable: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) if line and is_base64 and not pref: import base64 line = base64.decodestring(line) if line: ofile.write(pref + line) def unmimify(infile, outfile, decode_base64 = 0): """Convert quoted-printable parts of a MIME mail message to 8bit.""" if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile if type(outfile) == type(''): ofile = open(outfile, 'w') else: ofile = outfile nifile = File(ifile, None) unmimify_part(nifile, ofile, decode_base64) ofile.flush() mime_char = re.compile('[=\177-\377]') # quote these chars in body mime_header_char = re.compile('[=?\177-\377]') # quote these in header def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line mime_header = re.compile('([ \t(]|^)([-a-zA-Z0-9_+]*[\177-\377][-a-zA-Z0-9_+\177-\377]*)(?=[ \t)]|\n)') def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1)) pos = res.end(0) return newline + line[pos:] mv = re.compile('^mime-version:', re.I) cte = re.compile('^content-transfer-encoding:', re.I) iso_char = re.compile('[\177-\377]') def mimify_part(ifile, ofile, is_mime): """Convert an 8bit part of a MIME mail message to quoted-printable.""" has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if chrset_res.group(2).lower() == 'us-ascii': line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3)) else: # change iso-8859-* into us-ascii line = '%sus-ascii%s' % chrset_res.group(1, 3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek if not line: # premature end of file break ofile.write(line) continue # unexpectedly no multipart separator--copy rest of file while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) def mimify(infile, outfile): """Convert 8bit parts of a MIME mail message to quoted-printable.""" if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile if type(outfile) == type(''): ofile = open(outfile, 'w') else: ofile = outfile nifile = File(ifile, None) mimify_part(nifile, ofile, 0) ofile.flush() import sys if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'): import getopt usage = 'Usage: mimify [-l len] -[ed] [infile [outfile]]' decode_base64 = 0 opts, args = getopt.getopt(sys.argv[1:], 'l:edb') if len(args) not in (0, 1, 2): print usage sys.exit(1) if (('-e', '') in opts) == (('-d', '') in opts) or \ ((('-b', '') in opts) and (('-d', '') not in opts)): print usage sys.exit(1) for o, a in opts: if o == '-e': encode = mimify elif o == '-d': encode = unmimify elif o == '-l': try: MAXLEN = int(a) except (ValueError, OverflowError): print usage sys.exit(1) elif o == '-b': decode_base64 = 1 if len(args) == 0: encode_args = (sys.stdin, sys.stdout) elif len(args) == 1: encode_args = (args[0], sys.stdout) else: encode_args = (args[0], args[1]) if decode_base64: encode_args = encode_args + (decode_base64,) encode(*encode_args)
mit
vertexproject/synapse
synapse/models/media.py
1
2409
import synapse.lib.module as s_module class MediaModule(s_module.CoreModule): def getModelDefs(self): name = 'media' ctors = () forms = ( ('media:news', {}, ( ('url', ('inet:url', {}), { 'doc': 'The (optional) URL where the news was published.', 'ex': 'http://cnn.com/news/mars-lander.html', }), ('url:fqdn', ('inet:fqdn', {}), { 'doc': 'The FQDN within the news URL.', 'ex': 'cnn.com', }), ('file', ('file:bytes', {}), { 'doc': 'The (optional) file blob containing or published as the news.', }), ('title', ('str', {'lower': True}), { 'doc': 'Title/Headline for the news.', 'ex': 'mars lander reaches mars', 'disp': {'hint': 'text'}, }), ('summary', ('str', {}), { 'doc': 'A brief summary of the news item.', 'ex': 'lorum ipsum', 'disp': {'hint': 'text'}, }), ('published', ('time', {}), { 'doc': 'The date the news item was published.', 'ex': '20161201180433', }), ('org', ('ou:alias', {}), { 'doc': 'The org alias which published the news.', 'ex': 'microsoft', }), ('author', ('ps:name', {}), { 'doc': 'The free-form author of the news.', 'deprecated': True, 'ex': 'stark,anthony' }), ('authors', ('array', {'type': 'ps:contact', 'split': ',', 'uniq': True, 'sorted': True}), { 'doc': 'An array of authors of the news item.', }), ('rss:feed', ('inet:url', {}), { 'doc': 'The RSS feed that published the news.', }), )), ) types = ( ('media:news', ('guid', {}), { 'doc': 'A GUID for a news article or report.' }), ) modldef = (name, { 'ctors': ctors, 'forms': forms, 'types': types, }) return (modldef, )
apache-2.0
jonlooney/jxmlease
jxmlease/__init__.py
1
7746
#!/usr/bin/env python # Copyright (c) 2015-2016, Juniper Networks, Inc. # All rights reserved. # # Copyright (C) 2012 Martin Blech and individual contributors. # # See the LICENSE file for further information. """jxmlease converts between XML and intelligent Python data structures. For a quick start, you can use the :py:meth:`parse` method to convert a block of XML to a Python data structure. This example parses ``xml`` and uses the :py:meth:`XMLDictNode.prettyprint` method to display the result:: >>> xml = "<a><b><c>foo</c><c>bar</c></b></a>" >>> parse(xml).prettyprint() {u'a': {u'b': {u'c': [u'foo', u'bar']}}} Or, you can use the :py:class:`XMLDictNode` class to convert a Python data structure to an intelligent XML data structure. The following example creates an :py:obj:`XMLDictNode` object from ``data_structure`` and outputs the resulting XML using the :py:meth:`XMLNodeBase.emit_xml` method:: >>> data_structure = {u'a': {u'b': {u'c': [u'foo', u'bar']}}} >>> print XMLDictNode(data_structure).emit_xml() <?xml version="1.0" encoding="utf-8"?> <a> <b> <c>foo</c> <c>bar</c> </b> </a> """ from __future__ import absolute_import try: # pragma no cover from cStringIO import StringIO except ImportError: # pragma no cover try: from StringIO import StringIO except ImportError: from io import StringIO try: # pragma no cover from collections import OrderedDict as _OrderedDict except ImportError: # pragma no cover try: from ordereddict import OrderedDict as _OrderedDict except ImportError: _OrderedDict = dict try: # pragma no cover from pprint import pprint except ImportError: # pragma no cover def pprint(obj, *args, **kwargs): """Internal backup substitute for the pprint library function.""" if len(args) > 0: stream = args[0] else: stream = kwargs.get("stream", None) if stream is not None: stream.write("%r\n" % obj) else: print("%r" % obj) # pylint: disable=superfluous-parens try: # pragma no cover _unicode = unicode # pylint: disable=unicode-builtin except NameError: # pragma no cover _unicode = str # While doing processing for a generator, process XML text 1KB at a # time. # Note: While parsing_increment is only used by one module, it makes sense # to keep it here, since someone might want to override it, and we expect to # only publicly expose the package (and not individual modules). parsing_increment = 1024 # A user can use this to set their custom defaults for parsers. parser_defaults = {} __author__ = 'Juniper Networks' __version__ = '1.0.1dev1' __license__ = 'MIT' __all__ = [ 'XMLDictNode', 'XMLListNode', 'XMLCDATANode', 'Parser', 'parse', 'EtreeParser', 'parse_etree' ] class OrderedDict(_OrderedDict): """Standard OrderedDict class, with a small local modification. This module uses the OrderedDict class to maintain ordering of the input data. """ def __repr__(self, _repr_running=None): if _repr_running is None: _repr_running = {} temp = self.__class__.__name__ try: # The OrderedDict.__repr__ function takes an # extra argument. It also prints the name of # the main object's class. This logic temporarily # resets the class name so this appears to be # what it (fundamentally) is: an OrderedDict # object. (For this reason, there is also extra # logic to make the XMLDictNode __repr__ function # work correctly.) self.__class__.__name__ = _OrderedDict.__name__ rv = _OrderedDict.__repr__(self, _repr_running) except TypeError: # Looks like the class didn't understand the second # argument. Retry with just one argument. rv = _OrderedDict.__repr__(self) finally: self.__class__.__name__ = temp return rv # Handle the node classes and import them first. This will ensure the # references are fully resolved prior to importing other modules that # may need them. class _XMLCDATAPlaceholder(object): # pragma no cover """A placeholder class for XMLCDATANode. This class produces an error if called, but tries to give enough information about the underlying class to pylint to make its checks meaningful. """ def __new__(cls, *args, **kwargs): raise NotImplementedError("Class not properly inherited") def __init__(self, *args, **kwargs): super(_XMLCDATAPlaceholder, self).__init__(*args, **kwargs) def __getattr__(self, name): return getattr(_node_refs['XMLCDATANode'], name) class _XMLDictPlaceholder(object): # pragma no cover """A placeholder class for XMLDictNode. This class produces an error if called, but tries to give enough information about the underlying class to pylint to make its checks meaningful. """ def __new__(cls, *args, **kwargs): raise NotImplementedError("Class not properly inherited") def __init__(self, *args, **kwargs): super(_XMLDictPlaceholder, self).__init__(*args, **kwargs) def __getattr__(self, name): return getattr(_node_refs['XMLDictNode'], name) class _XMLListPlaceholder(object): # pragma no cover """A placeholder class for XMLLstNode. This class produces an error if called, but tries to give enough information about the underlying class to pylint to make its checks meaningful. """ def __new__(cls, *args, **kwargs): raise NotImplementedError("Class not properly inherited") def __init__(self, *args, **kwargs): super(_XMLListPlaceholder, self).__init__(*args, **kwargs) def __getattr__(self, name): return getattr(_node_refs['XMLListNode'], name) # This is a silly little hack to get around the fact that we have circular # references in the three different node type files. _node_refs = {'XMLListNode': None, 'XMLCDATANode': None, 'XMLDictNode': None} # These imports are purposely at the end because they depend on things that # are defined above this line. # pylint: disable=wrong-import-position # Import the base node. from ._basenode import XMLNodeBase # Import the node classes, updating the references in the dictionary. from .listnode import XMLListNode _node_refs['XMLListNode'] = XMLListNode from .cdatanode import XMLCDATANode _node_refs['XMLCDATANode'] = XMLCDATANode from .dictnode import XMLDictNode _node_refs['XMLDictNode'] = XMLDictNode # Now, import anything else we want. from .xmlparser import Parser, parse from .etreeparser import EtreeParser, parse_etree def emit_xml(obj, *args, **kwargs): """Translate a Python dictionary or list to XML output. This method internally creates an :py:class:`XMLDictNode` or :py:class:`XMLListNode` object, as appropriate, and then calls the :py:meth:`emit_xml <XMLNodeBase.emit_xml>` method of that class. Any arguments you supply are passed on to the :py:meth:`emit_xml <XMLNodeBase.emit_xml>` method of that class. Please see the documentation for the class' :py:meth:`emit_xml <XMLNodeBase.emit_xml>` method for information on arguments and return values. Raises: :py:exc:`TypeError`: If the object is not an appropriate type to convert to an XML tree. """ if isinstance(obj, (XMLDictNode, dict)): parsed_obj = XMLDictNode(obj) elif isinstance(obj, (XMLListNode, list, tuple)): parsed_obj = XMLListNode(obj) else: raise TypeError return parsed_obj.emit_xml(*args, **kwargs)
mit
michael-ball/sublime-text
sublime-text-3/Packages/SublimeLinter/sublimelinter.py
3
15688
# # sublimelinter.py # Part of SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ryan Hileman and Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter3 # License: MIT # """This module provides the SublimeLinter plugin class and supporting methods.""" import os import re import sublime import sublime_plugin from .lint.linter import Linter from .lint.highlight import HighlightSet from .lint.queue import queue from .lint import persist, util def plugin_loaded(): """The ST3 entry point for plugins.""" persist.plugin_is_loaded = True persist.settings.load() persist.printf('debug mode:', 'on' if persist.debug_mode() else 'off') util.create_tempdir() for linter in persist.linter_classes.values(): linter.initialize() plugin = SublimeLinter.shared_plugin() queue.start(plugin.lint) util.generate_menus() util.generate_color_scheme(from_reload=False) persist.settings.on_update_call(SublimeLinter.on_settings_updated) # This ensures we lint the active view on a fresh install window = sublime.active_window() if window: plugin.on_activated(window.active_view()) class SublimeLinter(sublime_plugin.EventListener): """The main ST3 plugin class.""" # We use this to match linter settings filenames. LINTER_SETTINGS_RE = re.compile('^SublimeLinter(-.+?)?\.sublime-settings') shared_instance = None @classmethod def shared_plugin(cls): """Return the plugin instance.""" return cls.shared_instance def __init__(self, *args, **kwargs): """Initialize a new instance.""" super().__init__(*args, **kwargs) # Keeps track of which views we have assigned linters to self.loaded_views = set() # Keeps track of which views have actually been linted self.linted_views = set() # A mapping between view ids and syntax names self.view_syntax = {} self.__class__.shared_instance = self @classmethod def lint_all_views(cls): """Simulate a modification of all views, which will trigger a relint.""" def apply(view): if view.id() in persist.view_linters: cls.shared_instance.hit(view) util.apply_to_all_views(apply) def lint(self, view_id, hit_time=None, callback=None): """ Lint the view with the given id. This method is called asynchronously by persist.Daemon when a lint request is pulled off the queue, or called synchronously when the Lint command is executed or a file is saved and Show Errors on Save is enabled. If provided, hit_time is the time at which the lint request was added to the queue. It is used to determine if the view has been modified since the lint request was queued. If so, the lint is aborted, since another lint request is already in the queue. callback is the method to call when the lint is finished. If not provided, it defaults to highlight(). """ # If the view has been modified since the lint was triggered, # don't lint again. if hit_time is not None and persist.last_hit_times.get(view_id, 0) > hit_time: return view = Linter.get_view(view_id) if view is None: return filename = view.file_name() code = Linter.text(view) callback = callback or self.highlight Linter.lint_view(view, filename, code, hit_time, callback) def highlight(self, view, linters, hit_time): """ Highlight any errors found during a lint of the given view. This method is called by Linter.lint_view after linting is finished. linters is a list of the linters that ran. hit_time has the same meaning as in lint(), and if the view was modified since the lint request was made, this method aborts drawing marks. If the view has not been modified since hit_time, all of the marks and errors from the list of linters are aggregated and drawn, and the status is updated. """ vid = view.id() # If the view has been modified since the lint was triggered, # don't draw marks. if hit_time is not None and persist.last_hit_times.get(vid, 0) > hit_time: return errors = {} highlights = persist.highlights[vid] = HighlightSet() for linter in linters: if linter.highlight: highlights.add(linter.highlight) if linter.errors: for line, errs in linter.errors.items(): errors.setdefault(line, []).extend(errs) # Keep track of one view in each window that shares view's buffer window_views = {} buffer_id = view.buffer_id() for window in sublime.windows(): wid = window.id() for other_view in window.views(): if other_view.buffer_id() == buffer_id: vid = other_view.id() persist.highlights[vid] = highlights highlights.clear(other_view) highlights.draw(other_view) persist.errors[vid] = errors if window_views.get(wid) is None: window_views[wid] = other_view for view in window_views.values(): self.on_selection_modified_async(view) def hit(self, view): """Record an activity that could trigger a lint and enqueue a desire to lint.""" vid = view.id() self.check_syntax(view) self.linted_views.add(vid) if view.size() == 0: for linter in Linter.get_linters(vid): linter.clear() return persist.last_hit_times[vid] = queue.hit(view) def check_syntax(self, view): """ Check and return if view's syntax has changed. If the syntax has changed, a new linter is assigned. """ vid = view.id() syntax = persist.get_syntax(view) # Syntax either has never been set or just changed if vid not in self.view_syntax or self.view_syntax[vid] != syntax: self.view_syntax[vid] = syntax Linter.assign(view, reset=True) self.clear(view) return True else: return False def clear(self, view): """Clear all marks, errors and status from the given view.""" Linter.clear_view(view) def is_scratch(self, view): """ Return whether a view is effectively scratch. There is a bug (or feature) in the current ST3 where the Find panel is not marked scratch but has no window. There is also a bug where settings files opened from within .sublime-package files are not marked scratch during the initial on_modified event, so we have to check that a view with a filename actually exists on disk if the file being opened is in the Sublime Text packages directory. """ if view.is_scratch() or view.is_read_only() or view.window() is None or view.settings().get("repl") is not None: return True elif ( view.file_name() and view.file_name().startswith(sublime.packages_path() + os.path.sep) and not os.path.exists(view.file_name()) ): return True else: return False def view_has_file_only_linter(self, vid): """Return True if any linters for the given view are file-only.""" for lint in persist.view_linters.get(vid, []): if lint.tempfile_suffix == '-': return True return False # sublime_plugin.EventListener event handlers def on_modified(self, view): """Called when a view is modified.""" if self.is_scratch(view): return if view.id() not in persist.view_linters: syntax_changed = self.check_syntax(view) if not syntax_changed: return else: syntax_changed = False if syntax_changed or persist.settings.get('lint_mode', 'background') == 'background': self.hit(view) else: self.clear(view) def on_activated(self, view): """Called when a view gains input focus.""" if self.is_scratch(view): return # Reload the plugin settings. persist.settings.load() self.check_syntax(view) view_id = view.id() if view_id not in self.linted_views: if view_id not in self.loaded_views: self.on_new(view) if persist.settings.get('lint_mode', 'background') in ('background', 'load/save'): self.hit(view) self.on_selection_modified_async(view) def on_open_settings(self, view): """ Called when any settings file is opened. view is the view that contains the text of the settings file. """ if self.is_settings_file(view, user_only=True): persist.settings.save(view=view) def is_settings_file(self, view, user_only=False): """Return True if view is a SublimeLinter settings file.""" filename = view.file_name() if not filename: return False if not filename.startswith(sublime.packages_path()): return False dirname, filename = os.path.split(filename) dirname = os.path.basename(dirname) if self.LINTER_SETTINGS_RE.match(filename): if user_only: return dirname == 'User' else: return dirname in (persist.PLUGIN_DIRECTORY, 'User') @classmethod def on_settings_updated(cls, relint=False): """Callback triggered when the settings are updated.""" if relint: cls.lint_all_views() else: Linter.redraw_all() def on_new(self, view): """Called when a new buffer is created.""" self.on_open_settings(view) if self.is_scratch(view): return vid = view.id() self.loaded_views.add(vid) self.view_syntax[vid] = persist.get_syntax(view) def get_focused_view_id(self, view): """ Return the focused view which shares view's buffer. When updating the status, we want to make sure we get the selection of the focused view, since multiple views into the same buffer may be open. """ active_view = view.window().active_view() for view in view.window().views(): if view == active_view: return view def on_selection_modified_async(self, view): """Called when the selection changes (cursor moves or text selected).""" if self.is_scratch(view): return view = self.get_focused_view_id(view) if view is None: return vid = view.id() # Get the line number of the first line of the first selection. try: lineno = view.rowcol(view.sel()[0].begin())[0] except IndexError: lineno = -1 if vid in persist.errors: errors = persist.errors[vid] if errors: lines = sorted(list(errors)) counts = [len(errors[line]) for line in lines] count = sum(counts) plural = 's' if count > 1 else '' if lineno in errors: # Sort the errors by column line_errors = sorted(errors[lineno], key=lambda error: error[0]) line_errors = [error[1] for error in line_errors] if plural: # Sum the errors before the first error on this line index = lines.index(lineno) first = sum(counts[0:index]) + 1 if len(line_errors) > 1: last = first + len(line_errors) - 1 status = '{}-{} of {} errors: '.format(first, last, count) else: status = '{} of {} errors: '.format(first, count) else: status = 'Error: ' status += '; '.join(line_errors) else: status = '%i error%s' % (count, plural) view.set_status('sublimelinter', status) else: view.erase_status('sublimelinter') def on_pre_save(self, view): """ Called before view is saved. If a settings file is the active view and is saved, copy the current settings first so we can compare post-save. """ if view.window().active_view() == view and self.is_settings_file(view): persist.settings.copy() def on_post_save(self, view): """Called after view is saved.""" if self.is_scratch(view): return # First check to see if the project settings changed if view.window().project_file_name() == view.file_name(): self.lint_all_views() else: # Now see if a .sublimelinterrc has changed filename = os.path.basename(view.file_name()) if filename == '.sublimelinterrc': # If a .sublimelinterrc has changed, to be safe # clear the rc cache and relint. util.get_rc_settings.cache_clear() self.lint_all_views() # If a file other than one of our settings files changed, # check if the syntax changed or if we need to show errors. elif filename != 'SublimeLinter.sublime-settings': self.file_was_saved(view) def file_was_saved(self, view): """Check if the syntax changed or if we need to show errors.""" syntax_changed = self.check_syntax(view) vid = view.id() mode = persist.settings.get('lint_mode', 'background') show_errors = persist.settings.get('show_errors_on_save', False) if syntax_changed: self.clear(view) if vid in persist.view_linters: if mode != 'manual': self.lint(vid) else: show_errors = False else: show_errors = False else: if ( show_errors or mode in ('load/save', 'save only') or mode == 'background' and self.view_has_file_only_linter(vid) ): self.lint(vid) elif mode == 'manual': show_errors = False if show_errors and vid in persist.errors and persist.errors[vid]: view.run_command('sublimelinter_show_all_errors') def on_close(self, view): """Called after view is closed.""" if self.is_scratch(view): return vid = view.id() if vid in self.loaded_views: self.loaded_views.remove(vid) if vid in self.linted_views: self.linted_views.remove(vid) if vid in self.view_syntax: del self.view_syntax[vid] persist.view_did_close(vid) class SublimelinterEditCommand(sublime_plugin.TextCommand): """A plugin command used to generate an edit object for a view.""" def run(self, edit): """Run the command.""" persist.edit(self.view.id(), edit)
unlicense
ChromiumWebApps/chromium
third_party/closure_linter/closure_linter/javascripttokenizer.py
137
15717
#!/usr/bin/env python # # Copyright 2007 The Closure Linter 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. """Regular expression based JavaScript parsing classes.""" __author__ = ('robbyw@google.com (Robert Walker)', 'ajp@google.com (Andy Perelson)') import copy import re from closure_linter import javascripttokens from closure_linter.common import matcher from closure_linter.common import tokenizer # Shorthand Type = javascripttokens.JavaScriptTokenType Matcher = matcher.Matcher class JavaScriptModes(object): """Enumeration of the different matcher modes used for JavaScript.""" TEXT_MODE = 'text' SINGLE_QUOTE_STRING_MODE = 'single_quote_string' DOUBLE_QUOTE_STRING_MODE = 'double_quote_string' BLOCK_COMMENT_MODE = 'block_comment' DOC_COMMENT_MODE = 'doc_comment' DOC_COMMENT_LEX_SPACES_MODE = 'doc_comment_spaces' LINE_COMMENT_MODE = 'line_comment' PARAMETER_MODE = 'parameter' FUNCTION_MODE = 'function' class JavaScriptTokenizer(tokenizer.Tokenizer): """JavaScript tokenizer. Convert JavaScript code in to an array of tokens. """ # Useful patterns for JavaScript parsing. IDENTIFIER_CHAR = r'A-Za-z0-9_$.' # Number patterns based on: # http://www.mozilla.org/js/language/js20-2000-07/formal/lexer-grammar.html MANTISSA = r""" (\d+(?!\.)) | # Matches '10' (\d+\.(?!\d)) | # Matches '10.' (\d*\.\d+) # Matches '.5' or '10.5' """ DECIMAL_LITERAL = r'(%s)([eE][-+]?\d+)?' % MANTISSA HEX_LITERAL = r'0[xX][0-9a-fA-F]+' NUMBER = re.compile(r""" ((%s)|(%s)) """ % (HEX_LITERAL, DECIMAL_LITERAL), re.VERBOSE) # Strings come in three parts - first we match the start of the string, then # the contents, then the end. The contents consist of any character except a # backslash or end of string, or a backslash followed by any character, or a # backslash followed by end of line to support correct parsing of multi-line # strings. SINGLE_QUOTE = re.compile(r"'") SINGLE_QUOTE_TEXT = re.compile(r"([^'\\]|\\(.|$))+") DOUBLE_QUOTE = re.compile(r'"') DOUBLE_QUOTE_TEXT = re.compile(r'([^"\\]|\\(.|$))+') START_SINGLE_LINE_COMMENT = re.compile(r'//') END_OF_LINE_SINGLE_LINE_COMMENT = re.compile(r'//$') START_DOC_COMMENT = re.compile(r'/\*\*') START_BLOCK_COMMENT = re.compile(r'/\*') END_BLOCK_COMMENT = re.compile(r'\*/') BLOCK_COMMENT_TEXT = re.compile(r'([^*]|\*(?!/))+') # Comment text is anything that we are not going to parse into another special # token like (inline) flags or end comments. Complicated regex to match # most normal characters, and '*', '{', '}', and '@' when we are sure that # it is safe. Expression [^*{\s]@ must come first, or the other options will # match everything before @, and we won't match @'s that aren't part of flags # like in email addresses in the @author tag. DOC_COMMENT_TEXT = re.compile(r'([^*{}\s]@|[^*{}@]|\*(?!/))+') DOC_COMMENT_NO_SPACES_TEXT = re.compile(r'([^*{}\s]@|[^*{}@\s]|\*(?!/))+') # Match the prefix ' * ' that starts every line of jsdoc. Want to include # spaces after the '*', but nothing else that occurs after a '*', and don't # want to match the '*' in '*/'. DOC_PREFIX = re.compile(r'\s*\*(\s+|(?!/))') START_BLOCK = re.compile('{') END_BLOCK = re.compile('}') REGEX_CHARACTER_CLASS = r""" \[ # Opening bracket ([^\]\\]|\\.)* # Anything but a ] or \, # or a backslash followed by anything \] # Closing bracket """ # We ensure the regex is followed by one of the above tokens to avoid # incorrectly parsing something like x / y / z as x REGEX(/ y /) z POST_REGEX_LIST = [ ';', ',', r'\.', r'\)', r'\]', '$', r'\/\/', r'\/\*', ':', '}'] REGEX = re.compile(r""" / # opening slash (?!\*) # not the start of a comment (\\.|[^\[\/\\]|(%s))* # a backslash followed by anything, # or anything but a / or [ or \, # or a character class / # closing slash [gimsx]* # optional modifiers (?=\s*(%s)) """ % (REGEX_CHARACTER_CLASS, '|'.join(POST_REGEX_LIST)), re.VERBOSE) ANYTHING = re.compile(r'.*') PARAMETERS = re.compile(r'[^\)]+') CLOSING_PAREN_WITH_SPACE = re.compile(r'\)\s*') FUNCTION_DECLARATION = re.compile(r'\bfunction\b') OPENING_PAREN = re.compile(r'\(') CLOSING_PAREN = re.compile(r'\)') OPENING_BRACKET = re.compile(r'\[') CLOSING_BRACKET = re.compile(r'\]') # We omit these JS keywords from the list: # function - covered by FUNCTION_DECLARATION. # delete, in, instanceof, new, typeof - included as operators. # this - included in identifiers. # null, undefined - not included, should go in some "special constant" list. KEYWORD_LIST = ['break', 'case', 'catch', 'continue', 'default', 'do', 'else', 'finally', 'for', 'if', 'return', 'switch', 'throw', 'try', 'var', 'while', 'with'] # Match a keyword string followed by a non-identifier character in order to # not match something like doSomething as do + Something. KEYWORD = re.compile('(%s)((?=[^%s])|$)' % ( '|'.join(KEYWORD_LIST), IDENTIFIER_CHAR)) # List of regular expressions to match as operators. Some notes: for our # purposes, the comma behaves similarly enough to a normal operator that we # include it here. r'\bin\b' actually matches 'in' surrounded by boundary # characters - this may not match some very esoteric uses of the in operator. # Operators that are subsets of larger operators must come later in this list # for proper matching, e.g., '>>' must come AFTER '>>>'. OPERATOR_LIST = [',', r'\+\+', '===', '!==', '>>>=', '>>>', '==', '>=', '<=', '!=', '<<=', '>>=', '<<', '>>', '>', '<', r'\+=', r'\+', '--', '\^=', '-=', '-', '/=', '/', r'\*=', r'\*', '%=', '%', '&&', r'\|\|', '&=', '&', r'\|=', r'\|', '=', '!', ':', '\?', r'\bdelete\b', r'\bin\b', r'\binstanceof\b', r'\bnew\b', r'\btypeof\b', r'\bvoid\b'] OPERATOR = re.compile('|'.join(OPERATOR_LIST)) WHITESPACE = re.compile(r'\s+') SEMICOLON = re.compile(r';') # Technically JavaScript identifiers can't contain '.', but we treat a set of # nested identifiers as a single identifier. NESTED_IDENTIFIER = r'[a-zA-Z_$][%s.]*' % IDENTIFIER_CHAR IDENTIFIER = re.compile(NESTED_IDENTIFIER) SIMPLE_LVALUE = re.compile(r""" (?P<identifier>%s) # a valid identifier (?=\s* # optional whitespace \= # look ahead to equal sign (?!=)) # not follwed by equal """ % NESTED_IDENTIFIER, re.VERBOSE) # A doc flag is a @ sign followed by non-space characters that appears at the # beginning of the line, after whitespace, or after a '{'. The look-behind # check is necessary to not match someone@google.com as a flag. DOC_FLAG = re.compile(r'(^|(?<=\s))@(?P<name>[a-zA-Z]+)') # To properly parse parameter names, we need to tokenize whitespace into a # token. DOC_FLAG_LEX_SPACES = re.compile(r'(^|(?<=\s))@(?P<name>%s)\b' % '|'.join(['param'])) DOC_INLINE_FLAG = re.compile(r'(?<={)@(?P<name>[a-zA-Z]+)') # Star followed by non-slash, i.e a star that does not end a comment. # This is used for TYPE_GROUP below. SAFE_STAR = r'(\*(?!/))' COMMON_DOC_MATCHERS = [ # Find the end of the comment. Matcher(END_BLOCK_COMMENT, Type.END_DOC_COMMENT, JavaScriptModes.TEXT_MODE), # Tokenize documented flags like @private. Matcher(DOC_INLINE_FLAG, Type.DOC_INLINE_FLAG), Matcher(DOC_FLAG_LEX_SPACES, Type.DOC_FLAG, JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE), # Encountering a doc flag should leave lex spaces mode. Matcher(DOC_FLAG, Type.DOC_FLAG, JavaScriptModes.DOC_COMMENT_MODE), # Tokenize braces so we can find types. Matcher(START_BLOCK, Type.DOC_START_BRACE), Matcher(END_BLOCK, Type.DOC_END_BRACE), Matcher(DOC_PREFIX, Type.DOC_PREFIX, None, True)] # The token matcher groups work as follows: it is an list of Matcher objects. # The matchers will be tried in this order, and the first to match will be # returned. Hence the order is important because the matchers that come first # overrule the matchers that come later. JAVASCRIPT_MATCHERS = { # Matchers for basic text mode. JavaScriptModes.TEXT_MODE: [ # Check a big group - strings, starting comments, and regexes - all # of which could be intertwined. 'string with /regex/', # /regex with 'string'/, /* comment with /regex/ and string */ (and so # on) Matcher(START_DOC_COMMENT, Type.START_DOC_COMMENT, JavaScriptModes.DOC_COMMENT_MODE), Matcher(START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, JavaScriptModes.BLOCK_COMMENT_MODE), Matcher(END_OF_LINE_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT), Matcher(START_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT, JavaScriptModes.LINE_COMMENT_MODE), Matcher(SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, JavaScriptModes.SINGLE_QUOTE_STRING_MODE), Matcher(DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), Matcher(REGEX, Type.REGEX), # Next we check for start blocks appearing outside any of the items # above. Matcher(START_BLOCK, Type.START_BLOCK), Matcher(END_BLOCK, Type.END_BLOCK), # Then we search for function declarations. Matcher(FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, JavaScriptModes.FUNCTION_MODE), # Next, we convert non-function related parens to tokens. Matcher(OPENING_PAREN, Type.START_PAREN), Matcher(CLOSING_PAREN, Type.END_PAREN), # Next, we convert brackets to tokens. Matcher(OPENING_BRACKET, Type.START_BRACKET), Matcher(CLOSING_BRACKET, Type.END_BRACKET), # Find numbers. This has to happen before operators because scientific # notation numbers can have + and - in them. Matcher(NUMBER, Type.NUMBER), # Find operators and simple assignments Matcher(SIMPLE_LVALUE, Type.SIMPLE_LVALUE), Matcher(OPERATOR, Type.OPERATOR), # Find key words and whitespace. Matcher(KEYWORD, Type.KEYWORD), Matcher(WHITESPACE, Type.WHITESPACE), # Find identifiers. Matcher(IDENTIFIER, Type.IDENTIFIER), # Finally, we convert semicolons to tokens. Matcher(SEMICOLON, Type.SEMICOLON)], # Matchers for single quote strings. JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ Matcher(SINGLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for double quote strings. JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ Matcher(DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for block comments. JavaScriptModes.BLOCK_COMMENT_MODE: [ # First we check for exiting a block comment. Matcher(END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, JavaScriptModes.TEXT_MODE), # Match non-comment-ending text.. Matcher(BLOCK_COMMENT_TEXT, Type.COMMENT)], # Matchers for doc comments. JavaScriptModes.DOC_COMMENT_MODE: COMMON_DOC_MATCHERS + [ Matcher(DOC_COMMENT_TEXT, Type.COMMENT)], JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: COMMON_DOC_MATCHERS + [ Matcher(WHITESPACE, Type.COMMENT), Matcher(DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], # Matchers for single line comments. JavaScriptModes.LINE_COMMENT_MODE: [ # We greedy match until the end of the line in line comment mode. Matcher(ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], # Matchers for code after the function keyword. JavaScriptModes.FUNCTION_MODE: [ # Must match open paren before anything else and move into parameter # mode, otherwise everything inside the parameter list is parsed # incorrectly. Matcher(OPENING_PAREN, Type.START_PARAMETERS, JavaScriptModes.PARAMETER_MODE), Matcher(WHITESPACE, Type.WHITESPACE), Matcher(IDENTIFIER, Type.FUNCTION_NAME)], # Matchers for function parameters JavaScriptModes.PARAMETER_MODE: [ # When in function parameter mode, a closing paren is treated specially. # Everything else is treated as lines of parameters. Matcher(CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, JavaScriptModes.TEXT_MODE), Matcher(PARAMETERS, Type.PARAMETERS, JavaScriptModes.PARAMETER_MODE)]} # When text is not matched, it is given this default type based on mode. # If unspecified in this map, the default default is Type.NORMAL. JAVASCRIPT_DEFAULT_TYPES = { JavaScriptModes.DOC_COMMENT_MODE: Type.COMMENT, JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: Type.COMMENT } def __init__(self, parse_js_doc = True): """Create a tokenizer object. Args: parse_js_doc: Whether to do detailed parsing of javascript doc comments, or simply treat them as normal comments. Defaults to parsing JsDoc. """ matchers = self.JAVASCRIPT_MATCHERS if not parse_js_doc: # Make a copy so the original doesn't get modified. matchers = copy.deepcopy(matchers) matchers[JavaScriptModes.DOC_COMMENT_MODE] = matchers[ JavaScriptModes.BLOCK_COMMENT_MODE] tokenizer.Tokenizer.__init__(self, JavaScriptModes.TEXT_MODE, matchers, self.JAVASCRIPT_DEFAULT_TYPES) def _CreateToken(self, string, token_type, line, line_number, values=None): """Creates a new JavaScriptToken object. Args: string: The string of input the token contains. token_type: The type of token. line: The text of the line this token is in. line_number: The line number of the token. values: A dict of named values within the token. For instance, a function declaration may have a value called 'name' which captures the name of the function. """ return javascripttokens.JavaScriptToken(string, token_type, line, line_number, values)
bsd-3-clause
halvertoluke/edx-platform
lms/djangoapps/teams/models.py
48
10408
"""Django models related to teams functionality.""" from datetime import datetime from uuid import uuid4 import pytz from model_utils import FieldTracker from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from django.utils.translation import ugettext_lazy from django_countries.fields import CountryField from django_comment_common.signals import ( thread_created, thread_edited, thread_deleted, thread_voted, comment_created, comment_edited, comment_deleted, comment_voted, comment_endorsed ) from xmodule_django.models import CourseKeyField from util.model_utils import slugify from student.models import LanguageField, CourseEnrollment from .errors import AlreadyOnTeamInCourse, NotEnrolledInCourseForTeam, ImmutableMembershipFieldException from lms.djangoapps.teams.utils import emit_team_event from lms.djangoapps.teams import TEAM_DISCUSSION_CONTEXT @receiver(thread_voted) @receiver(thread_created) @receiver(comment_voted) @receiver(comment_created) def post_create_vote_handler(sender, **kwargs): # pylint: disable=unused-argument """Update the user's last activity date upon creating or voting for a post.""" handle_activity(kwargs['user'], kwargs['post']) @receiver(thread_edited) @receiver(thread_deleted) @receiver(comment_edited) @receiver(comment_deleted) def post_edit_delete_handler(sender, **kwargs): # pylint: disable=unused-argument """Update the user's last activity date upon editing or deleting a post.""" post = kwargs['post'] handle_activity(kwargs['user'], post, long(post.user_id)) @receiver(comment_endorsed) def comment_endorsed_handler(sender, **kwargs): # pylint: disable=unused-argument """Update the user's last activity date upon endorsing a comment.""" comment = kwargs['post'] handle_activity(kwargs['user'], comment, long(comment.thread.user_id)) def handle_activity(user, post, original_author_id=None): """Handle user activity from django_comment_client and discussion_api and update the user's last activity date. Checks if the user who performed the action is the original author, and that the discussion has the team context. """ if original_author_id is not None and user.id != original_author_id: return if getattr(post, "context", "course") == TEAM_DISCUSSION_CONTEXT: CourseTeamMembership.update_last_activity(user, post.commentable_id) class CourseTeam(models.Model): """This model represents team related info.""" class Meta(object): app_label = "teams" team_id = models.CharField(max_length=255, unique=True) discussion_topic_id = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, db_index=True) course_id = CourseKeyField(max_length=255, db_index=True) topic_id = models.CharField(max_length=255, db_index=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=300) country = CountryField(blank=True) language = LanguageField( blank=True, help_text=ugettext_lazy("Optional language the team uses as ISO 639-1 code."), ) last_activity_at = models.DateTimeField(db_index=True) # indexed for ordering users = models.ManyToManyField(User, db_index=True, related_name='teams', through='CourseTeamMembership') team_size = models.IntegerField(default=0, db_index=True) # indexed for ordering field_tracker = FieldTracker() # Don't emit changed events when these fields change. FIELD_BLACKLIST = ['last_activity_at', 'team_size'] @classmethod def create(cls, name, course_id, description, topic_id=None, country=None, language=None): """Create a complete CourseTeam object. Args: name (str): The name of the team to be created. course_id (str): The ID string of the course associated with this team. description (str): A description of the team. topic_id (str): An optional identifier for the topic the team formed around. country (str, optional): An optional country where the team is based, as ISO 3166-1 code. language (str, optional): An optional language which the team uses, as ISO 639-1 code. """ unique_id = uuid4().hex team_id = slugify(name)[0:20] + '-' + unique_id discussion_topic_id = unique_id course_team = cls( team_id=team_id, discussion_topic_id=discussion_topic_id, name=name, course_id=course_id, topic_id=topic_id if topic_id else '', description=description, country=country if country else '', language=language if language else '', last_activity_at=datetime.utcnow().replace(tzinfo=pytz.utc) ) return course_team def __repr__(self): return "<CourseTeam team_id={0.team_id}>".format(self) def add_user(self, user): """Adds the given user to the CourseTeam.""" if not CourseEnrollment.is_enrolled(user, self.course_id): raise NotEnrolledInCourseForTeam if CourseTeamMembership.user_in_team_for_course(user, self.course_id): raise AlreadyOnTeamInCourse return CourseTeamMembership.objects.create( user=user, team=self ) def reset_team_size(self): """Reset team_size to reflect the current membership count.""" self.team_size = CourseTeamMembership.objects.filter(team=self).count() self.save() class CourseTeamMembership(models.Model): """This model represents the membership of a single user in a single team.""" class Meta(object): app_label = "teams" unique_together = (('user', 'team'),) user = models.ForeignKey(User) team = models.ForeignKey(CourseTeam, related_name='membership') date_joined = models.DateTimeField(auto_now_add=True) last_activity_at = models.DateTimeField() immutable_fields = ('user', 'team', 'date_joined') def __setattr__(self, name, value): """Memberships are immutable, with the exception of last activity date. """ if name in self.immutable_fields: # Check the current value -- if it is None, then this # model is being created from the database and it's fine # to set the value. Otherwise, we're trying to overwrite # an immutable field. current_value = getattr(self, name, None) if value == current_value: # This is an attempt to set an immutable value to the same value # to which it's already set. Don't complain - just ignore the attempt. return else: # This is an attempt to set an immutable value to a different value. # Allow it *only* if the current value is None. if current_value is not None: raise ImmutableMembershipFieldException( "Field %r shouldn't change from %r to %r" % (name, current_value, value) ) super(CourseTeamMembership, self).__setattr__(name, value) def save(self, *args, **kwargs): """Customize save method to set the last_activity_at if it does not currently exist. Also resets the team's size if this model is being created. """ should_reset_team_size = False if self.pk is None: should_reset_team_size = True if not self.last_activity_at: self.last_activity_at = datetime.utcnow().replace(tzinfo=pytz.utc) super(CourseTeamMembership, self).save(*args, **kwargs) if should_reset_team_size: self.team.reset_team_size() def delete(self, *args, **kwargs): """Recompute the related team's team_size after deleting a membership""" super(CourseTeamMembership, self).delete(*args, **kwargs) self.team.reset_team_size() @classmethod def get_memberships(cls, username=None, course_ids=None, team_id=None): """ Get a queryset of memberships. Args: username (unicode, optional): The username to filter on. course_ids (list of unicode, optional) Course IDs to filter on. team_id (unicode, optional): The team_id to filter on. """ queryset = cls.objects.all() if username is not None: queryset = queryset.filter(user__username=username) if course_ids is not None: queryset = queryset.filter(team__course_id__in=course_ids) if team_id is not None: queryset = queryset.filter(team__team_id=team_id) return queryset @classmethod def user_in_team_for_course(cls, user, course_id): """ Checks whether or not a user is already in a team in the given course. Args: user: the user that we want to query on course_id: the course_id of the course we're interested in Returns: True if the user is on a team in the course already False if not """ return cls.objects.filter(user=user, team__course_id=course_id).exists() @classmethod def update_last_activity(cls, user, discussion_topic_id): """Set the `last_activity_at` for both this user and their team in the given discussion topic. No-op if the user is not a member of the team for this discussion. """ try: membership = cls.objects.get(user=user, team__discussion_topic_id=discussion_topic_id) # If a privileged user is active in the discussion of a team # they do not belong to, do not update their last activity # information. except ObjectDoesNotExist: return now = datetime.utcnow().replace(tzinfo=pytz.utc) membership.last_activity_at = now membership.team.last_activity_at = now membership.team.save() membership.save() emit_team_event('edx.team.activity_updated', membership.team.course_id, { 'team_id': membership.team_id, })
agpl-3.0
Konbonix/DisasterSupplyTracker
lib/gae_mini_profiler/sampling_profiler.py
13
7408
"""CPU profiler that works by sampling the call stack periodically. This profiler provides a very simplistic view of where your request is spending its time. It does this by periodically sampling your request's call stack to figure out in which functions real time is being spent. PRO: since the profiler only samples the call stack occasionally, it has much less overhead than an instrumenting profiler, and avoids biases that instrumenting profilers have due to instrumentation overhead (which causes instrumenting profilers to overstate how much time is spent in frequently called functions, or functions with deep call stacks). CON: since the profiler only samples, it does not allow you to accurately answer a question like, "how much time was spent in routine X?", especially if routine X takes relatively little time. (You *can* answer questions like "what is the ratio of time spent in routine X vs routine Y," at least if both routines take a reasonable amount of time.) It is better suited for answering the question, "Where is the time spent by my app?" """ from collections import defaultdict import logging import os import sys import time import threading import traceback from gae_mini_profiler import util _is_dev_server = os.environ["SERVER_SOFTWARE"].startswith("Devel") class InspectingThread(threading.Thread): """Thread that periodically triggers profiler inspections.""" SAMPLES_PER_SECOND = 250 def __init__(self, profile=None): super(InspectingThread, self).__init__() self._stop_event = threading.Event() self.profile = profile def stop(self): """Stop this thread.""" # http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python self._stop_event.set() def should_stop(self): return self._stop_event.is_set() def run(self): """Start periodic profiler inspections. This will run, periodically inspecting and then sleeping, until manually stopped via stop().""" # Keep sampling until this thread is explicitly stopped. while not self.should_stop(): # Take a sample of the main request thread's frame stack... self.profile.take_sample() # ...then sleep and let it do some more work. time.sleep(1.0 / InspectingThread.SAMPLES_PER_SECOND) # Only take one sample per thread if this is running on the # single-threaded dev server. if _is_dev_server and len(self.profile.samples) > 0: break class ProfileSample(object): """Single stack trace sample gathered during a periodic inspection.""" def __init__(self, stack): self.stack_trace = traceback.extract_stack(stack) class Profile(object): """Profiler that periodically inspects a request and logs stack traces.""" def __init__(self): # All saved stack trace samples self.samples = [] # Thread id for the request thread currently being profiled self.current_request_thread_id = None # Thread that constantly waits, inspects, waits, inspect, ... self.inspecting_thread = None def results(self): """Return sampling results in a dictionary for template context.""" aggregated_calls = defaultdict(int) total_samples = len(self.samples) for sample in self.samples: for filename, line_num, function_name, src in sample.stack_trace: aggregated_calls["%s\n\n%s:%s (%s)" % (src, filename, line_num, function_name)] += 1 # Turn aggregated call samples into dictionary of results calls = [{ "func_desc": item[0], "func_desc_short": util.short_method_fmt(item[0]), "count_samples": item[1], "per_samples": "%s%%" % util.decimal_fmt( 100.0 * item[1] / total_samples), } for item in aggregated_calls.items()] # Sort call sample results by # of times calls appeared in a sample calls = sorted(calls, reverse=True, key=lambda call: call["count_samples"]) return { "calls": calls, "total_samples": total_samples, "is_dev_server": _is_dev_server, } def take_sample(self): # Look at stacks of all existing threads... # See http://bzimmer.ziclix.com/2008/12/17/python-thread-dumps/ for thread_id, stack in sys._current_frames().items(): # ...but only sample from the main request thread. if _is_dev_server: # In development, current_request_thread_id won't be set # properly. threading.current_thread().ident always returns -1 # in dev. So instead, we just take a peek at the stack's # current package to figure out if it is the request thread. # Even though the dev server is single-threaded, # sys._current_frames will return multiple threads, because # some of them are spawned by the App Engine dev server for # internal purposes. We don't want to sample these internal dev # server threads -- we want to sample the thread that is # running the current request. Since the dev server will be # running this sampling code immediately from the run() code # below, we can spot this thread's stack by looking at its # global namespace (f_globals) and making sure it's currently # in the gae_mini_profiler package. should_sample = (stack.f_globals["__package__"] == "gae_mini_profiler") else: # In production, current_request_thread_id will be set properly # by threading.current_thread().ident. # TODO(kamens): this profiler will need work if we ever # actually use multiple threads in a single request and want to # profile more than one of them. should_sample = thread_id == self.current_request_thread_id if should_sample: # Grab a sample of this thread's current stack self.samples.append(ProfileSample(stack)) def run(self, fxn): """Run function with samping profiler enabled, saving results.""" if not hasattr(threading, "current_thread"): # Sampling profiler is not supported in Python2.5 logging.warn("The sampling profiler is not supported in Python2.5") return fxn() # Store the thread id for the current request's thread. This lets # the inspecting thread know which thread to inspect. self.current_request_thread_id = threading.current_thread().ident # Start the thread that will be periodically inspecting the frame # stack of this current request thread self.inspecting_thread = InspectingThread(profile=self) self.inspecting_thread.start() try: # Run the request fxn which will be inspected by the inspecting # thread. return fxn() finally: # Stop and clear the inspecting thread self.inspecting_thread.stop() self.inspecting_thread = None
apache-2.0
russel1237/scikit-learn
sklearn/decomposition/tests/test_pca.py
199
10949
import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raises from sklearn import datasets from sklearn.decomposition import PCA from sklearn.decomposition import RandomizedPCA from sklearn.decomposition.pca import _assess_dimension_ from sklearn.decomposition.pca import _infer_dimension_ iris = datasets.load_iris() def test_pca(): # PCA on dense arrays pca = PCA(n_components=2) X = iris.data X_r = pca.fit(X).transform(X) np.testing.assert_equal(X_r.shape[1], 2) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) pca = PCA() pca.fit(X) assert_almost_equal(pca.explained_variance_ratio_.sum(), 1.0, 3) X_r = pca.transform(X) X_r2 = pca.fit_transform(X) assert_array_almost_equal(X_r, X_r2) # Test get_covariance and get_precision with n_components == n_features # with n_components < n_features and with n_components == 0 for n_components in [0, 2, X.shape[1]]: pca.n_components = n_components pca.fit(X) cov = pca.get_covariance() precision = pca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1]), 12) def test_whitening(): # Check that PCA output has unit-variance rng = np.random.RandomState(0) n_samples = 100 n_features = 80 n_components = 30 rank = 50 # some low rank data with correlated features X = np.dot(rng.randn(n_samples, rank), np.dot(np.diag(np.linspace(10.0, 1.0, rank)), rng.randn(rank, n_features))) # the component-wise variance of the first 50 features is 3 times the # mean component-wise variance of the remaingin 30 features X[:, :50] *= 3 assert_equal(X.shape, (n_samples, n_features)) # the component-wise variance is thus highly varying: assert_almost_equal(X.std(axis=0).std(), 43.9, 1) for this_PCA, copy in [(x, y) for x in (PCA, RandomizedPCA) for y in (True, False)]: # whiten the data while projecting to the lower dim subspace X_ = X.copy() # make sure we keep an original across iterations. pca = this_PCA(n_components=n_components, whiten=True, copy=copy) # test fit_transform X_whitened = pca.fit_transform(X_.copy()) assert_equal(X_whitened.shape, (n_samples, n_components)) X_whitened2 = pca.transform(X_) assert_array_almost_equal(X_whitened, X_whitened2) assert_almost_equal(X_whitened.std(axis=0), np.ones(n_components)) assert_almost_equal(X_whitened.mean(axis=0), np.zeros(n_components)) X_ = X.copy() pca = this_PCA(n_components=n_components, whiten=False, copy=copy).fit(X_) X_unwhitened = pca.transform(X_) assert_equal(X_unwhitened.shape, (n_samples, n_components)) # in that case the output components still have varying variances assert_almost_equal(X_unwhitened.std(axis=0).std(), 74.1, 1) # we always center, so no test for non-centering. def test_explained_variance(): # Check that PCA output has unit-variance rng = np.random.RandomState(0) n_samples = 100 n_features = 80 X = rng.randn(n_samples, n_features) pca = PCA(n_components=2).fit(X) rpca = RandomizedPCA(n_components=2, random_state=42).fit(X) assert_array_almost_equal(pca.explained_variance_, rpca.explained_variance_, 1) assert_array_almost_equal(pca.explained_variance_ratio_, rpca.explained_variance_ratio_, 3) # compare to empirical variances X_pca = pca.transform(X) assert_array_almost_equal(pca.explained_variance_, np.var(X_pca, axis=0)) X_rpca = rpca.transform(X) assert_array_almost_equal(rpca.explained_variance_, np.var(X_rpca, axis=0)) def test_pca_check_projection(): # Test that the projection of data is correct rng = np.random.RandomState(0) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) Yt = PCA(n_components=2).fit(X).transform(Xt) Yt /= np.sqrt((Yt ** 2).sum()) assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_pca_inverse(): # Test that the projection of data can be inverted rng = np.random.RandomState(0) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) pca = PCA(n_components=2).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) # same as above with whitening (approximate reconstruction) pca = PCA(n_components=2, whiten=True) pca.fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) def test_pca_validation(): X = [[0, 1], [1, 0]] for n_components in [-1, 3]: assert_raises(ValueError, PCA(n_components).fit, X) def test_randomized_pca_check_projection(): # Test that the projection by RandomizedPCA on dense data is correct rng = np.random.RandomState(0) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) Yt = RandomizedPCA(n_components=2, random_state=0).fit(X).transform(Xt) Yt /= np.sqrt((Yt ** 2).sum()) assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_randomized_pca_check_list(): # Test that the projection by RandomizedPCA on list data is correct X = [[1.0, 0.0], [0.0, 1.0]] X_transformed = RandomizedPCA(n_components=1, random_state=0).fit(X).transform(X) assert_equal(X_transformed.shape, (2, 1)) assert_almost_equal(X_transformed.mean(), 0.00, 2) assert_almost_equal(X_transformed.std(), 0.71, 2) def test_randomized_pca_inverse(): # Test that RandomizedPCA is inversible on dense data rng = np.random.RandomState(0) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed signal # (since the data is almost of rank n_components) pca = RandomizedPCA(n_components=2, random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=2) # same as above with whitening (approximate reconstruction) pca = RandomizedPCA(n_components=2, whiten=True, random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) relative_max_delta = (np.abs(X - Y_inverse) / np.abs(X).mean()).max() assert_almost_equal(relative_max_delta, 0.11, decimal=2) def test_pca_dim(): # Check automated dimensionality setting rng = np.random.RandomState(0) n, p = 100, 5 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) pca = PCA(n_components='mle').fit(X) assert_equal(pca.n_components, 'mle') assert_equal(pca.n_components_, 1) def test_infer_dim_1(): # TODO: explain what this is testing # Or at least use explicit variable names... n, p = 1000, 5 rng = np.random.RandomState(0) X = (rng.randn(n, p) * .1 + rng.randn(n, 1) * np.array([3, 4, 5, 1, 2]) + np.array([1, 0, 7, 4, 6])) pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ ll = [] for k in range(p): ll.append(_assess_dimension_(spect, k, n, p)) ll = np.array(ll) assert_greater(ll[1], ll.max() - .01 * n) def test_infer_dim_2(): # TODO: explain what this is testing # Or at least use explicit variable names... n, p = 1000, 5 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) X[10:20] += np.array([6, 0, 7, 2, -1]) pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ assert_greater(_infer_dimension_(spect, n, p), 1) def test_infer_dim_3(): n, p = 100, 5 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5, 1, 2]) X[10:20] += np.array([6, 0, 7, 2, -1]) X[30:40] += 2 * np.array([-1, 1, -1, 1, -1]) pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ assert_greater(_infer_dimension_(spect, n, p), 2) def test_infer_dim_by_explained_variance(): X = iris.data pca = PCA(n_components=0.95) pca.fit(X) assert_equal(pca.n_components, 0.95) assert_equal(pca.n_components_, 2) pca = PCA(n_components=0.01) pca.fit(X) assert_equal(pca.n_components, 0.01) assert_equal(pca.n_components_, 1) rng = np.random.RandomState(0) # more features than samples X = rng.rand(5, 20) pca = PCA(n_components=.5).fit(X) assert_equal(pca.n_components, 0.5) assert_equal(pca.n_components_, 2) def test_pca_score(): # Test that probabilistic PCA scoring yields a reasonable score n, p = 1000, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) pca = PCA(n_components=2) pca.fit(X) ll1 = pca.score(X) h = -0.5 * np.log(2 * np.pi * np.exp(1) * 0.1 ** 2) * p np.testing.assert_almost_equal(ll1 / h, 1, 0) def test_pca_score2(): # Test that probabilistic PCA correctly separated different datasets n, p = 100, 3 rng = np.random.RandomState(0) X = rng.randn(n, p) * .1 + np.array([3, 4, 5]) pca = PCA(n_components=2) pca.fit(X) ll1 = pca.score(X) ll2 = pca.score(rng.randn(n, p) * .2 + np.array([3, 4, 5])) assert_greater(ll1, ll2) # Test that it gives the same scores if whiten=True pca = PCA(n_components=2, whiten=True) pca.fit(X) ll2 = pca.score(X) assert_almost_equal(ll1, ll2) def test_pca_score3(): # Check that probabilistic PCA selects the right model n, p = 200, 3 rng = np.random.RandomState(0) Xl = (rng.randn(n, p) + rng.randn(n, 1) * np.array([3, 4, 5]) + np.array([1, 0, 7])) Xt = (rng.randn(n, p) + rng.randn(n, 1) * np.array([3, 4, 5]) + np.array([1, 0, 7])) ll = np.zeros(p) for k in range(p): pca = PCA(n_components=k) pca.fit(Xl) ll[k] = pca.score(Xt) assert_true(ll.argmax() == 1)
bsd-3-clause
anthroprose/expunge
node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
388
91069
# Copyright (c) 2013 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. # Notes: # # This is all roughly based on the Makefile system used by the Linux # kernel, but is a non-recursive make -- we put the entire dependency # graph in front of make and let it figure it out. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level Makefile. This means that all # variables in .mk-files clobber one another. Be careful to use := # where appropriate for immediate evaluation, and similarly to watch # that you're not relying on a variable value to last beween different # .mk files. # # TODOs: # # Global settings and utility functions are currently stuffed in the # toplevel Makefile. It may make sense to generate some .mk files on # the side to keep the the files readable. import os import re import sys import subprocess import gyp import gyp.common import gyp.xcode_emulation from gyp.common import GetEnvironFallback from gyp.common import GypError generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'SHARED_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/$(TARGET)/geni', 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen', 'PRODUCT_DIR': '$(builddir)', 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python. 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python. 'RULE_INPUT_PATH': '$(abspath $<)', 'RULE_INPUT_EXT': '$(suffix $<)', 'RULE_INPUT_NAME': '$(notdir $<)', 'CONFIGURATION_NAME': '$(BUILDTYPE)', } # Make supports multiple toolsets generator_supports_multiple_toolsets = True # Request sorted dependencies in the order from dependents to dependencies. generator_wants_sorted_dependencies = False # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. import gyp.generator.xcode as xcode_generator global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) global generator_additional_path_sections generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'}) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)') def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) android_ndk_version = generator_flags.get('android_ndk_version', None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params['options'].generator_output or \ params['options'].toplevel_dir builddir_name = generator_flags.get('output_dir', 'out') qualified_out_dir = os.path.normpath(os.path.join( output_dir, builddir_name, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': params['options'].toplevel_dir, 'qualified_out_dir': qualified_out_dir, } # The .d checking code below uses these functions: # wildcard, sort, foreach, shell, wordlist # wildcard can handle spaces, the rest can't. # Since I could find no way to make foreach work with spaces in filenames # correctly, the .d files have spaces replaced with another character. The .d # file for # Chromium\ Framework.framework/foo # is for example # out/Release/.deps/out/Release/Chromium?Framework.framework/foo # This is the replacement character. SPACE_REPLACEMENT = '?' LINK_COMMANDS_LINUX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) # We support two kinds of shared objects (.so): # 1) shared_library, which is just bundling together many dependent libraries # into a link line. # 2) loadable_module, which is generating a module intended for dlopen(). # # They differ only slightly: # In the former case, we want to package all dependent code into the .so. # In the latter case, we want to package just the API exposed by the # outermost module. # This means shared_library uses --whole-archive, while loadable_module doesn't. # (Note that --whole-archive is incompatible with the --start-group used in # normal linking.) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) """ LINK_COMMANDS_MAC = """\ quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ LINK_COMMANDS_ANDROID = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ quiet_cmd_link_host = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ LINK_COMMANDS_AIX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # Header of toplevel Makefile. # This should go into the build tree, but it's easier to keep it here for now. SHARED_HEADER = ("""\ # We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := %(srcdir)s abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= %(builddir)s # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= %(default_configuration)s # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := %(make_global_settings)s CC.target ?= %(CC.target)s CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) CXX.target ?= %(CXX.target)s CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) LINK.target ?= %(LINK.target)s LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. LINK ?= $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= %(CC.host)s CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) CXX.host ?= %(CXX.host)s CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) LINK.host ?= %(LINK.host)s LDFLAGS.host ?= AR.host ?= %(AR.host)s # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1) unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \\ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters.""" r""" define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef """ """ # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< %(extra_commands)s quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@" %(link_commands)s """ r""" # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))' """ """ # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain """ + SPACE_REPLACEMENT + \ """ instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\\ for p in $(POSTBUILDS); do\\ eval $$p;\\ E=$$?;\\ if [ $$E -ne 0 ]; then\\ break;\\ fi;\\ done;\\ if [ $$E -ne 0 ]; then\\ rm -rf "$@";\\ exit $$E;\\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains """ + \ SPACE_REPLACEMENT + """ for # spaces already and dirx strips the """ + SPACE_REPLACEMENT + \ """ characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "%(default_target)s" target first so it is the default, # even though we don't have the deps yet. .PHONY: %(default_target)s %(default_target)s: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %%.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: """) SHARED_HEADER_MAC_COMMANDS = """ quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" """ def WriteRootHeaderSuffixRules(writer): extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) writer.write('# Suffix rules, putting all outputs into $(obj).\n') for ext in extensions: writer.write('$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n# Try building from generated source, too.\n') for ext in extensions: writer.write( '$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n') for ext in extensions: writer.write('$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n' % ext) writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext]) writer.write('\n') SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\ # Suffix rules, putting all outputs into $(obj). """) SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\ # Try building from generated source, too. """) SHARED_FOOTER = """\ # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif """ header = """\ # This file is generated by gyp; do not edit. """ # Maps every compilable file extension to the do_cmd that compiles it. COMPILABLE_EXTENSIONS = { '.c': 'cc', '.cc': 'cxx', '.cpp': 'cxx', '.cxx': 'cxx', '.s': 'cc', '.S': 'cc', } def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS): if res: return True return False def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o') def Target(filename): """Translate a compilable filename to its .o target.""" return os.path.splitext(filename)[0] + '.o' def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'" def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$') def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#') def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub('[^a-zA-Z0-9_]', '_', string) srcdir_prefix = '' def Sourceify(path): """Convert a path to its source directory form.""" if '$(' in path: return path if os.path.isabs(path): return path return srcdir_prefix + path def QuoteSpaces(s, quote=r'\ '): return s.replace(' ', quote) # TODO: Avoid code duplication with _ValidateSourcesForMSVSProject in msvs.py. def _ValidateSourcesForOSX(spec, all_sources): """Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target. """ if spec.get('type', None) != 'static_library': return basenames = {} for source in all_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' % spec['target_name'] + error + 'libtool on OS X will generate' + ' warnings for them.') raise GypError('Duplicate basenames in sources section, see list above') # Map from qualified target to path to output. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class MakefileWriter(object): """MakefileWriter packages up the writing of one target-specific foobar.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, generator_flags, flavor): self.generator_flags = generator_flags self.flavor = flavor self.suffix_rules_srcdir = {} self.suffix_rules_objdir1 = {} self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. for ext in COMPILABLE_EXTENSIONS.keys(): # Suffix rules for source folder. self.suffix_rules_srcdir.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) # Suffix rules for generated source files. self.suffix_rules_objdir1.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) self.suffix_rules_objdir2.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD @$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]))}) def Write(self, qualified_target, base_path, output_filename, spec, configs, part_of_all): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = self.ComputeOutput(spec) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', 'shared_library') if (self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS): self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get('sources', []) + extra_sources if all_sources: if self.flavor == 'mac': # libtool on OS X generates warnings for duplicate basenames in the same # target. _ValidateSourcesForOSX(spec, all_sources) self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify)) sources = filter(Compilable, all_sources) if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = set([os.path.splitext(s)[1] for s in sources]) for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn('# End of this set of suffix rules') # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ('static_library', 'shared_library'): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get('android_ndk_version', None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close() def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): """Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) # For consistency with other builders, put sub-project build output in the # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn('export builddir_name ?= %s' % os.path.join(os.path.dirname(output_filename), build_dir)) self.WriteLn('.PHONY: all') self.WriteLn('all:') if makefile_path: makefile_path = ' -C ' + makefile_path self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets))) self.fp.close() def WriteActions(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action['action'] if self.flavor == 'mac': action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands] command = gyp.common.EncodePOSIXShellList(action_commands) if 'message' in action: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) else: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name)) if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd %s; ' % Sourceify(self.path or '.') # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:' '$(builddir)/lib.target:$$LD_LIBRARY_PATH; ' 'export LD_LIBRARY_PATH; ' '%s%s' % (name, cd_action, command)) self.WriteLn() outputs = map(self.Absolutify, outputs) # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert ' ' not in input, ( "Spaces in action input filenames not supported (%s)" % input) for output in outputs: assert ' ' not in output, ( "Spaces in action output filenames not supported (%s)" % output) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)), part_of_all=part_of_all, command=name) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = 'action_%s_outputs' % name self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs))) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn() self.WriteLn() def WriteRules(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, rule['rule_name'])) count = 0 self.WriteLn('### Generated for rule %s:' % name) all_outputs = [] for rule_source in rule.get('rule_sources', []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs if int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs inputs = map(Sourceify, map(self.Absolutify, [rule_source] + rule.get('inputs', []))) actions = ['$(call do_cmd,%s_%d)' % (name, count)] if name == 'resources_grit': # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ['@touch --no-create $@'] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = map(self.Absolutify, outputs) all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn('%s: obj := $(abs_obj)' % outputs[0]) self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0]) self.WriteMakeRule(outputs, inputs, actions, command="%s_%d" % (name, count)) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)') for output in outputs: output = re.sub(variables_with_spaces, '', output) assert ' ' not in output, ( "Spaces in rule filenames not yet supported (%s)" % output) self.WriteLn('all_deps += %s' % ' '.join(outputs)) action = [self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule['action']] mkdirs = '' if len(dirs) > 0: mkdirs = 'mkdir -p %s; ' % ' '.join(dirs) cd_action = 'cd %s; ' % Sourceify(self.path or '.') # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == 'mac': action = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action] action = gyp.common.EncodePOSIXShellList(action) action = action.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) mkdirs = mkdirs.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { 'action': action, 'cd_action': cd_action, 'count': count, 'mkdirs': mkdirs, 'name': name, }) self.WriteLn( 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % { 'count': count, 'name': name, }) self.WriteLn() count += 1 outputs_variable = 'rule_%s_outputs' % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn('### Finished generating for rule: %s' % name) self.WriteLn() self.WriteLn('### Finished generating for all rules') self.WriteLn('') def WriteCopies(self, copies, extra_outputs, part_of_all): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Generated for copy rule.') variable = StringToMakefileVariable(self.qualified_target + '_copies') outputs = [] for copy in copies: for path in copy['files']: # Absolutify() may call normpath, and will strip trailing slashes. path = Sourceify(self.Absolutify(path)) filename = os.path.split(path)[1] output = Sourceify(self.Absolutify(os.path.join(copy['destination'], filename))) # If the output path has variables in it, which happens in practice for # 'copies', writing the environment as target-local doesn't work, # because the variables are already needed for the target name. # Copying the environment variables into global make variables doesn't # work either, because then the .d files will potentially contain spaces # after variable expansion, and .d file handling cannot handle spaces. # As a workaround, manually expand variables at gyp time. Since 'copies' # can't run scripts, there's no need to write the env then. # WriteDoCmd() will escape spaces for .d files. env = self.GetSortedXcodeEnv() output = gyp.xcode_emulation.ExpandEnvVars(output, env) path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], 'copy', part_of_all) outputs.append(output) self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs)))) extra_outputs.append('$(%s)' % variable) self.WriteLn() def WriteMacBundleResources(self, resources, bundle_deps): """Writes Makefile code for 'mac_bundle_resources'.""" self.WriteLn('### Generated for mac_bundle_resources') for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(Sourceify, map(self.Absolutify, resources))): _, ext = os.path.splitext(output) if ext != '.xcassets': # Make does not supports '.xcassets' emulation. self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource', part_of_all=True) bundle_deps.append(output) def WriteMacInfoPlist(self, bundle_deps): """Write Makefile code for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, lambda p: Sourceify(self.Absolutify(p))) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' + os.path.basename(info_plist)) self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D', quoter=EscapeCppDefine) self.WriteMakeRule([intermediate_plist], [info_plist], ['$(call do_cmd,infoplist)', # "Convert" the plist so that any weird whitespace changes from the # preprocessor do not affect the XML parser in mac_tool. '@plutil -convert xml1 $@ $@']) info_plist = intermediate_plist # plists can contain envvars and substitute them into the file. self.WriteSortedXcodeEnv( out, self.GetSortedXcodeEnv(additional_settings=extra_env)) self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist', part_of_all=True) bundle_deps.append(out) def WriteSources(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', quoter=EscapeCppDefine) if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(configname) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get('cflags') cflags_c = config.get('cflags_c') cflags_cc = config.get('cflags_cc') self.WriteLn("# Flags passed to all source files."); self.WriteList(cflags, 'CFLAGS_%s' % configname) self.WriteLn("# Flags passed to only C files."); self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) self.WriteLn("# Flags passed to only C++ files."); self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) if self.flavor == 'mac': self.WriteLn("# Flags passed to only ObjC files."); self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) self.WriteLn("# Flags passed to only ObjC++ files."); self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) includes = config.get('include_dirs') if includes: includes = map(Sourceify, map(self.Absolutify, includes)) self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') compilable = filter(Compilable, sources) objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable))) self.WriteList(objs, 'OBJS') for obj in objs: assert ' ' not in obj, ( "Spaces in object filenames not supported (%s)" % obj) self.WriteLn('# Add to the list of files we specially track ' 'dependencies for.') self.WriteLn('all_deps += $(OBJS)') self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule(['$(OBJS)'], deps, comment = 'Make sure our dependencies are built ' 'before any of us.', order_only = True) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule(['$(OBJS)'], extra_outputs, comment = 'Make sure our actions/rules run ' 'before any of us.', order_only = True) pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) if pchdeps: self.WriteLn('# Dependencies from obj files to their precompiled headers') for source, obj, gch in pchdeps: self.WriteLn('%s: %s' % (obj, gch)) self.WriteLn('# End precompiled header dependencies') if objs: extra_link_deps.append('$(OBJS)') self.WriteLn("""\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""") self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn("$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('c') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('cc') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))") if self.flavor == 'mac': self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('m') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('mm') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))") self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += filter(Linkable, sources) self.WriteLn() def WritePchTargets(self, pch_commands): """Writes make rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: extra_flags = { 'c': '$(CFLAGS_C_$(BUILDTYPE))', 'cc': '$(CFLAGS_CC_$(BUILDTYPE))', 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))', 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))', }[lang] var_name = { 'c': 'GYP_PCH_CFLAGS', 'cc': 'GYP_PCH_CXXFLAGS', 'm': 'GYP_PCH_OBJCFLAGS', 'mm': 'GYP_PCH_OBJCXXFLAGS', }[lang] self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags) self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input)) self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang) self.WriteLn('') assert ' ' not in gch, ( "Spaces in gch filenames not supported (%s)" % gch) self.WriteLn('all_deps += %s' % gch) self.WriteLn('') def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ assert not self.is_mac_bundle if self.flavor == 'mac' and self.type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): return self.xcode_settings.GetExecutablePath() target = spec['target_name'] target_prefix = '' target_ext = '' if self.type == 'static_library': if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' target_ext = '.a' elif self.type in ('loadable_module', 'shared_library'): if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' target_ext = '.so' elif self.type == 'none': target = '%s.stamp' % target elif self.type != 'executable': print ("ERROR: What output file should be generated?", "type", self.type, "target", target) target_prefix = spec.get('product_prefix', target_prefix) target = spec.get('product_name', target) product_ext = spec.get('product_extension') if product_ext: target_ext = '.' + product_ext return target_prefix + target + target_ext def _InstallImmediately(self): return self.toolset == 'target' and self.flavor == 'mac' and self.type in ( 'static_library', 'executable', 'shared_library', 'loadable_module') def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ assert not self.is_mac_bundle path = os.path.join('$(obj).' + self.toolset, self.path) if self.type == 'executable' or self._InstallImmediately(): path = '$(builddir)' path = spec.get('product_dir', path) return os.path.join(path, self.ComputeOutputBasename(spec)) def ComputeMacBundleOutput(self, spec): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetWrapperName()) def ComputeMacBundleBinaryOutput(self, spec): """Return the 'output' (full output path) to the binary in a bundle.""" path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetExecutablePath()) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if 'dependencies' in spec: deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]]) for dep in spec['dependencies']: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? # This hack makes it work: # link_deps.extend(spec.get('libraries', [])) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def WriteDependencyOnExtraOutputs(self, target, extra_outputs): self.WriteMakeRule([self.output_binary], extra_outputs, comment = 'Build our special outputs first.', order_only = True) def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule(extra_outputs, deps, comment=('Preserve order dependency of ' 'special output on deps.'), order_only = True) target_postbuilds = {} if self.type != 'none': for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(configname, generator_default_variables['PRODUCT_DIR'], lambda p: Sourceify(self.Absolutify(p))) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output))), QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output_binary)))) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend( gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i in xrange(len(postbuilds)): if not postbuilds[i].startswith('$'): postbuilds[i] = EscapeShellArgument(postbuilds[i]) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' 'on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, ('Postbuilds do not work with ' 'custom product_dir') if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd( [self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print "WARNING: no output for", self.type, target # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony = True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment = 'Add target alias to "all" target.', phony = True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % ( install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony = True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment = 'Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment = 'Short alias for building this %s.' % file_desc, phony = True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment = 'Add %s to "all" target.' % file_desc, phony = True) def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values)) def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = '' if postbuilds: assert ',' not in command suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule(outputs, inputs, actions = ['$(call do_cmd,%s%s)' % (command, suffix)], comment = comment, command = command, force = True) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn('all_deps += %s' % ' '.join(outputs)) def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = map(QuoteSpaces, outputs) inputs = map(QuoteSpaces, inputs) if comment: self.WriteLn('# ' + comment) if phony: self.WriteLn('.PHONY: ' + ' '.join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = ' FORCE_DO_CMD' if force else '' if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn('%s: | %s%s' % (' '.join(outputs), ' '.join(inputs), force_append)) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn('%s: %s%s' % (outputs[0], ' '.join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. intermediate = "%s.intermediate" % (command if command else self.target) self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:'); self.WriteLn('%s: %s' % ('.INTERMEDIATE', intermediate)) self.WriteLn('%s: %s%s' % (intermediate, ' '.join(inputs), force_append)) actions.insert(0, '$(call do_cmd,touch)') if actions: for action in actions: self.WriteLn('\t%s' % action) self.WriteLn() def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): """Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents. """ if self.type not in ('executable', 'shared_library', 'static_library'): return self.WriteLn('# Variable definitions for Android applications') self.WriteLn('include $(CLEAR_VARS)') self.WriteLn('LOCAL_MODULE := ' + module_name) self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) ' '$(DEFS_$(BUILDTYPE)) ' # LOCAL_CFLAGS is applied to both of C and C++. There is # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C # sources. '$(CFLAGS_C_$(BUILDTYPE)) ' # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while # LOCAL_C_INCLUDES does not expect it. So put it in # LOCAL_CFLAGS. '$(INCS_$(BUILDTYPE))') # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))') self.WriteLn('LOCAL_C_INCLUDES :=') self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)') # Detect the C++ extension. cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0} default_cpp_ext = '.cpp' for filename in all_sources: ext = os.path.splitext(filename)[1] if ext in cpp_ext: cpp_ext[ext] += 1 if cpp_ext[ext] > cpp_ext[default_cpp_ext]: default_cpp_ext = ext self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext) self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)), 'LOCAL_SRC_FILES') # Filter out those which do not match prefix and suffix and produce # the resulting list without prefix and suffix. def DepsToModules(deps, prefix, suffix): modules = [] for filepath in deps: filename = os.path.basename(filepath) if filename.startswith(prefix) and filename.endswith(suffix): modules.append(filename[len(prefix):-len(suffix)]) return modules # Retrieve the default value of 'SHARED_LIB_SUFFIX' params = {'flavor': 'linux'} default_variables = {} CalculateVariables(default_variables, params) self.WriteList( DepsToModules(link_deps, generator_default_variables['SHARED_LIB_PREFIX'], default_variables['SHARED_LIB_SUFFIX']), 'LOCAL_SHARED_LIBRARIES') self.WriteList( DepsToModules(link_deps, generator_default_variables['STATIC_LIB_PREFIX'], generator_default_variables['STATIC_LIB_SUFFIX']), 'LOCAL_STATIC_LIBRARIES') if self.type == 'executable': self.WriteLn('include $(BUILD_EXECUTABLE)') elif self.type == 'shared_library': self.WriteLn('include $(BUILD_SHARED_LIBRARY)') elif self.type == 'static_library': self.WriteLn('include $(BUILD_STATIC_LIBRARY)') self.WriteLn() def WriteLn(self, text=''): self.fp.write(text + '\n') def GetSortedXcodeEnv(self, additional_settings=None): return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, "$(abs_builddir)", os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)", additional_settings) def GetSortedXcodePostbuildEnv(self): # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE', '') # Even if strip_save_file is empty, explicitly write it. Else a postbuild # might pick up an export from an earlier target. return self.GetSortedXcodeEnv( additional_settings={'CHROMIUM_STRIP_SAVE_FILE': strip_save_file}) def WriteSortedXcodeEnv(self, target, env): for k, v in env: # For # foo := a\ b # the escaped space does the right thing. For # export foo := a\ b # it does not -- the backslash is written to the env as literal character. # So don't escape spaces in |env[k]|. self.WriteLn('%s: export %s := %s' % (QuoteSpaces(target), k, v)) def Objectify(self, path): """Convert a path to its output directory form.""" if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset) if not '$(obj)' in path: path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path) return path def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' % (self.toolset, lang)) return path return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if '$(' in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip('/') return os.path.normpath(os.path.join(self.path, path)) def ExpandInputRoot(self, template, expansion, dirname): if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template: return template path = template % { 'INPUT_ROOT': expansion, 'INPUT_DIRNAME': dirname, } return path def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # XXX(TooTallNate): disabling this code since we don't want this behavior... #if (self.type == 'shared_library' and # (self.flavor != 'mac' or self.toolset != 'target')): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias) return '$(builddir)/' + self.alias def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params['options'] build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params['build_files_arg']] gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], options.toplevel_dir) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join('.', gyp_binary) root_makefile.write( "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n" "%(makefile_name)s: %(deps)s\n" "\t$(call do_cmd,regen_makefile)\n\n" % { 'makefile_name': makefile_name, 'deps': ' '.join(map(Sourceify, build_files)), 'cmd': gyp.common.EncodePOSIXShellList( [gyp_binary, '-fmake'] + gyp.RegenerateFlags(options) + build_files_args)}) def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: arguments = ['make'] if options.toplevel_dir and options.toplevel_dir != '.': arguments += '-C', options.toplevel_dir arguments.append('BUILDTYPE=' + config) print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def GenerateOutput(target_list, target_dicts, data, params): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) builddir_name = generator_flags.get('output_dir', 'out') android_ndk_version = generator_flags.get('android_ndk_version', None) default_target = generator_flags.get('default_target', 'all') def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) if options.generator_output: output_file = os.path.join( options.depth, options.generator_output, base_path, base_name) base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.toplevel_dir) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = set([target_dicts[target]['toolset'] for target in target_list]) for target in target_list: spec = target_dicts[target] if spec['default_configuration'] != 'Default': default_configuration = spec['default_configuration'] break if not default_configuration: default_configuration = 'Default' srcdir = '.' makefile_name = 'Makefile' + options.suffix makefile_path = os.path.join(options.toplevel_dir, makefile_name) if options.generator_output: global srcdir_prefix makefile_path = os.path.join( options.toplevel_dir, options.generator_output, makefile_name) srcdir = gyp.common.RelativePath(srcdir, options.generator_output) srcdir_prefix = '$(srcdir)/' flock_command= 'flock' copy_archive_arguments = '-af' header_params = { 'default_target': default_target, 'builddir': builddir_name, 'default_configuration': default_configuration, 'flock': flock_command, 'flock_index': 1, 'link_commands': LINK_COMMANDS_LINUX, 'extra_commands': '', 'srcdir': srcdir, 'copy_archive_args': copy_archive_arguments, } if flavor == 'mac': flock_command = './gyp-mac-tool flock' header_params.update({ 'flock': flock_command, 'flock_index': 2, 'link_commands': LINK_COMMANDS_MAC, 'extra_commands': SHARED_HEADER_MAC_COMMANDS, }) elif flavor == 'android': header_params.update({ 'link_commands': LINK_COMMANDS_ANDROID, }) elif flavor == 'solaris': header_params.update({ 'flock': './gyp-flock-tool flock', 'flock_index': 2, }) elif flavor == 'freebsd': # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific. header_params.update({ 'flock': 'lockf', }) elif flavor == 'openbsd': copy_archive_arguments = '-pPRf' header_params.update({ 'copy_archive_args': copy_archive_arguments, }) elif flavor == 'aix': copy_archive_arguments = '-pPRf' header_params.update({ 'copy_archive_args': copy_archive_arguments, 'link_commands': LINK_COMMANDS_AIX, 'flock': './gyp-flock-tool flock', 'flock_index': 2, }) header_params.update({ 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'), 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'), 'CXX.target': GetEnvironFallback(('CXX_target', 'CXX'), '$(CXX)'), 'LINK.target': GetEnvironFallback(('LINK_target', 'LINK'), '$(LINK)'), 'CC.host': GetEnvironFallback(('CC_host',), 'gcc'), 'AR.host': GetEnvironFallback(('AR_host',), 'ar'), 'CXX.host': GetEnvironFallback(('CXX_host',), 'g++'), 'LINK.host': GetEnvironFallback(('LINK_host',), '$(CXX.host)'), }) build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_array = data[build_file].get('make_global_settings', []) wrappers = {} for key, value in make_global_settings_array: if key.endswith('_wrapper'): wrappers[key[:-len('_wrapper')]] = '$(abspath %s)' % value make_global_settings = '' for key, value in make_global_settings_array: if re.match('.*_wrapper', key): continue if value[0] != '$': value = '$(abspath %s)' % value wrapper = wrappers.get(key) if wrapper: value = '%s %s' % (wrapper, value) del wrappers[key] if key in ('CC', 'CC.host', 'CXX', 'CXX.host'): make_global_settings += ( 'ifneq (,$(filter $(origin %s), undefined default))\n' % key) # Let gyp-time envvars win over global settings. env_key = key.replace('.', '_') # CC.host -> CC_host if env_key in os.environ: value = os.environ[env_key] make_global_settings += ' %s = %s\n' % (key, value) make_global_settings += 'endif\n' else: make_global_settings += '%s ?= %s\n' % (key, value) # TODO(ukai): define cmd when only wrapper is specified in # make_global_settings. header_params['make_global_settings'] = make_global_settings gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, 'w') root_makefile.write(SHARED_HEADER % header_params) # Currently any versions have the same effect, but in future the behavior # could be different. if android_ndk_version: root_makefile.write( '# Define LOCAL_PATH for build of Android applications.\n' 'LOCAL_PATH := $(call my-dir)\n' '\n') for toolset in toolsets: root_makefile.write('TOOLSET := %s\n' % toolset) WriteRootHeaderSuffixRules(root_makefile) # Put build-time support tools next to the root Makefile. dest_path = os.path.dirname(makefile_path) gyp.common.CopyTool(flavor, dest_path) # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget( qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings_array == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. %s vs. %s" % (this_make_global_settings, make_global_settings)) build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) included_files = data[build_file]['included_files'] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if (params['home_dot_gyp'] and abs_include_file.startswith(params['home_dot_gyp'])): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath(build_file, target + '.' + toolset + options.suffix + '.mk') spec = target_dicts[qualified_target] configs = spec['configurations'] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) writer = MakefileWriter(generator_flags, flavor) writer.Write(qualified_target, base_path, output_file, spec, configs, part_of_all=qualified_target in needed_targets) # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath(output_file, os.path.dirname(makefile_path)) include_list.add(mkfile_rel_path) # Write out per-gyp (sub-project) Makefiles. depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd()) for build_file in build_files: # The paths in build_files were relativized above, so undo that before # testing against the non-relativized items in target_list and before # calculating the Makefile path. build_file = os.path.join(depth_rel_path, build_file) gyp_targets = [target_dicts[target]['target_name'] for target in target_list if target.startswith(build_file) and target in needed_targets] # Only generate Makefiles for gyp files with targets. if not gyp_targets: continue base_path, output_file = CalculateMakefilePath(build_file, os.path.splitext(os.path.basename(build_file))[0] + '.Makefile') makefile_rel_path = gyp.common.RelativePath(os.path.dirname(makefile_path), os.path.dirname(output_file)) writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, builddir_name) # Write out the sorted list of includes. root_makefile.write('\n') for include_file in sorted(include_list): # We wrap each .mk include in an if statement so users can tell make to # not load a file by setting NO_LOAD. The below make code says, only # load the .mk file if the .mk filename doesn't start with a token in # NO_LOAD. root_makefile.write( "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n" " $(findstring $(join ^,$(prefix)),\\\n" " $(join ^," + include_file + ")))),)\n") root_makefile.write(" include " + include_file + "\n") root_makefile.write("endif\n") root_makefile.write('\n') if (not generator_flags.get('standalone') and generator_flags.get('auto_regeneration', True)): WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) root_makefile.write(SHARED_FOOTER) root_makefile.close()
apache-2.0
Ayaz2589/Ayaz2589.github.io
node_modules/npm/node_modules/npm-lifecycle/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py
1446
65937
#!/usr/bin/env python # 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. """Unit tests for the MSVSSettings.py file.""" import StringIO import unittest import gyp.MSVSSettings as MSVSSettings class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.stderr = StringIO.StringIO() def _ExpectedWarnings(self, expected): """Compares recorded lines to expected warnings.""" self.stderr.seek(0) actual = self.stderr.read().split('\n') actual = [line for line in actual if line] self.assertEqual(sorted(expected), sorted(actual)) def testValidateMSVSSettings_tool_names(self): """Tests that only MSVS tool names are allowed.""" MSVSSettings.ValidateMSVSSettings( {'VCCLCompilerTool': {}, 'VCLinkerTool': {}, 'VCMIDLTool': {}, 'foo': {}, 'VCResourceCompilerTool': {}, 'VCLibrarianTool': {}, 'VCManifestTool': {}, 'ClCompile': {}}, self.stderr) self._ExpectedWarnings([ 'Warning: unrecognized tool foo', 'Warning: unrecognized tool ClCompile']) def testValidateMSVSSettings_settings(self): """Tests that for invalid MSVS settings.""" MSVSSettings.ValidateMSVSSettings( {'VCCLCompilerTool': { 'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': ['string1', 'string2'], 'AdditionalUsingDirectories': 'folder1;folder2', 'AssemblerListingLocation': 'a_file_name', 'AssemblerOutput': '0', 'BasicRuntimeChecks': '5', 'BrowseInformation': 'fdkslj', 'BrowseInformationFile': 'a_file_name', 'BufferSecurityCheck': 'true', 'CallingConvention': '-1', 'CompileAs': '1', 'DebugInformationFormat': '2', 'DefaultCharIsUnsigned': 'true', 'Detect64BitPortabilityProblems': 'true', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'string1;string2', 'EnableEnhancedInstructionSet': '1', 'EnableFiberSafeOptimizations': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'EnablePREfast': 'true', 'Enableprefast': 'bogus', 'ErrorReporting': '1', 'ExceptionHandling': '1', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': '1', 'FloatingPointExceptions': 'true', 'FloatingPointModel': '1', 'ForceConformanceInForLoopScope': 'true', 'ForcedIncludeFiles': 'file1;file2', 'ForcedUsingFiles': 'file1;file2', 'GeneratePreprocessedFile': '1', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': '1', 'KeepComments': 'true', 'MinimalRebuild': 'true', 'ObjectFile': 'a_file_name', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMP': 'true', 'Optimization': '1', 'PrecompiledHeaderFile': 'a_file_name', 'PrecompiledHeaderThrough': 'a_file_name', 'PreprocessorDefinitions': 'string1;string2', 'ProgramDataBaseFileName': 'a_file_name', 'RuntimeLibrary': '1', 'RuntimeTypeInfo': 'true', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '1', 'SuppressStartupBanner': 'true', 'TreatWChar_tAsBuiltInType': 'true', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'string1;string2', 'UseFullPaths': 'true', 'UsePrecompiledHeader': '1', 'UseUnicodeResponseFiles': 'true', 'WarnAsError': 'true', 'WarningLevel': '1', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': 'a_file_name', 'ZZXYZ': 'bogus'}, 'VCLinkerTool': { 'AdditionalDependencies': 'file1;file2', 'AdditionalDependencies_excluded': 'file3', 'AdditionalLibraryDirectories': 'folder1;folder2', 'AdditionalManifestDependencies': 'file1;file2', 'AdditionalOptions': 'a string1', 'AddModuleNamesToAssembly': 'file1;file2', 'AllowIsolation': 'true', 'AssemblyDebug': '2', 'AssemblyLinkResource': 'file1;file2', 'BaseAddress': 'a string1', 'CLRImageType': '2', 'CLRThreadAttribute': '2', 'CLRUnmanagedCodeCheck': 'true', 'DataExecutionPrevention': '2', 'DelayLoadDLLs': 'file1;file2', 'DelaySign': 'true', 'Driver': '2', 'EmbedManagedResourceFile': 'file1;file2', 'EnableCOMDATFolding': '2', 'EnableUAC': 'true', 'EntryPointSymbol': 'a string1', 'ErrorReporting': '2', 'FixedBaseAddress': '2', 'ForceSymbolReferences': 'file1;file2', 'FunctionOrder': 'a_file_name', 'GenerateDebugInformation': 'true', 'GenerateManifest': 'true', 'GenerateMapFile': 'true', 'HeapCommitSize': 'a string1', 'HeapReserveSize': 'a string1', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreDefaultLibraryNames': 'file1;file2', 'IgnoreEmbeddedIDL': 'true', 'IgnoreImportLibrary': 'true', 'ImportLibrary': 'a_file_name', 'KeyContainer': 'a_file_name', 'KeyFile': 'a_file_name', 'LargeAddressAware': '2', 'LinkIncremental': '2', 'LinkLibraryDependencies': 'true', 'LinkTimeCodeGeneration': '2', 'ManifestFile': 'a_file_name', 'MapExports': 'true', 'MapFileName': 'a_file_name', 'MergedIDLBaseFileName': 'a_file_name', 'MergeSections': 'a string1', 'MidlCommandFile': 'a_file_name', 'ModuleDefinitionFile': 'a_file_name', 'OptimizeForWindows98': '1', 'OptimizeReferences': '2', 'OutputFile': 'a_file_name', 'PerUserRedirection': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': 'a_file_name', 'ProgramDatabaseFile': 'a_file_name', 'RandomizedBaseAddress': '2', 'RegisterOutput': 'true', 'ResourceOnlyDLL': 'true', 'SetChecksum': 'true', 'ShowProgress': '2', 'StackCommitSize': 'a string1', 'StackReserveSize': 'a string1', 'StripPrivateSymbols': 'a_file_name', 'SubSystem': '2', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'true', 'SwapRunFromCD': 'true', 'SwapRunFromNet': 'true', 'TargetMachine': '2', 'TerminalServerAware': '2', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'a_file_name', 'TypeLibraryResourceID': '33', 'UACExecutionLevel': '2', 'UACUIAccess': 'true', 'UseLibraryDependencyInputs': 'true', 'UseUnicodeResponseFiles': 'true', 'Version': 'a string1'}, 'VCMIDLTool': { 'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'CPreprocessOptions': 'a string1', 'DefaultCharType': '1', 'DLLDataFileName': 'a_file_name', 'EnableErrorChecks': '1', 'ErrorCheckAllocations': 'true', 'ErrorCheckBounds': 'true', 'ErrorCheckEnumRange': 'true', 'ErrorCheckRefPointers': 'true', 'ErrorCheckStubData': 'true', 'GenerateStublessProxies': 'true', 'GenerateTypeLibrary': 'true', 'HeaderFileName': 'a_file_name', 'IgnoreStandardIncludePath': 'true', 'InterfaceIdentifierFileName': 'a_file_name', 'MkTypLibCompatible': 'true', 'notgood': 'bogus', 'OutputDirectory': 'a string1', 'PreprocessorDefinitions': 'string1;string2', 'ProxyFileName': 'a_file_name', 'RedirectOutputAndErrors': 'a_file_name', 'StructMemberAlignment': '1', 'SuppressStartupBanner': 'true', 'TargetEnvironment': '1', 'TypeLibraryName': 'a_file_name', 'UndefinePreprocessorDefinitions': 'string1;string2', 'ValidateParameters': 'true', 'WarnAsError': 'true', 'WarningLevel': '1'}, 'VCResourceCompilerTool': { 'AdditionalOptions': 'a string1', 'AdditionalIncludeDirectories': 'folder1;folder2', 'Culture': '1003', 'IgnoreStandardIncludePath': 'true', 'notgood2': 'bogus', 'PreprocessorDefinitions': 'string1;string2', 'ResourceOutputFileName': 'a string1', 'ShowProgress': 'true', 'SuppressStartupBanner': 'true', 'UndefinePreprocessorDefinitions': 'string1;string2'}, 'VCLibrarianTool': { 'AdditionalDependencies': 'file1;file2', 'AdditionalLibraryDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'ExportNamedFunctions': 'string1;string2', 'ForceSymbolReferences': 'a string1', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreSpecificDefaultLibraries': 'file1;file2', 'LinkLibraryDependencies': 'true', 'ModuleDefinitionFile': 'a_file_name', 'OutputFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'UseUnicodeResponseFiles': 'true'}, 'VCManifestTool': { 'AdditionalManifestFiles': 'file1;file2', 'AdditionalOptions': 'a string1', 'AssemblyIdentity': 'a string1', 'ComponentFileName': 'a_file_name', 'DependencyInformationFile': 'a_file_name', 'GenerateCatalogFiles': 'true', 'InputResourceManifests': 'a string1', 'ManifestResourceFile': 'a_file_name', 'OutputManifestFile': 'a_file_name', 'RegistrarScriptFile': 'a_file_name', 'ReplacementsFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'TypeLibraryFile': 'a_file_name', 'UpdateFileHashes': 'truel', 'UpdateFileHashesSearchPath': 'a_file_name', 'UseFAT32Workaround': 'true', 'UseUnicodeResponseFiles': 'true', 'VerboseOutput': 'true'}}, self.stderr) self._ExpectedWarnings([ 'Warning: for VCCLCompilerTool/BasicRuntimeChecks, ' 'index value (5) not in expected range [0, 4)', 'Warning: for VCCLCompilerTool/BrowseInformation, ' "invalid literal for int() with base 10: 'fdkslj'", 'Warning: for VCCLCompilerTool/CallingConvention, ' 'index value (-1) not in expected range [0, 4)', 'Warning: for VCCLCompilerTool/DebugInformationFormat, ' 'converted value for 2 not specified.', 'Warning: unrecognized setting VCCLCompilerTool/Enableprefast', 'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ', 'Warning: for VCLinkerTool/TargetMachine, ' 'converted value for 2 not specified.', 'Warning: unrecognized setting VCMIDLTool/notgood', 'Warning: unrecognized setting VCResourceCompilerTool/notgood2', 'Warning: for VCManifestTool/UpdateFileHashes, ' "expected bool; got 'truel'" '']) def testValidateMSBuildSettings_settings(self): """Tests that for invalid MSBuild settings.""" MSVSSettings.ValidateMSBuildSettings( {'ClCompile': { 'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': ['string1', 'string2'], 'AdditionalUsingDirectories': 'folder1;folder2', 'AssemblerListingLocation': 'a_file_name', 'AssemblerOutput': 'NoListing', 'BasicRuntimeChecks': 'StackFrameRuntimeCheck', 'BrowseInformation': 'false', 'BrowseInformationFile': 'a_file_name', 'BufferSecurityCheck': 'true', 'BuildingInIDE': 'true', 'CallingConvention': 'Cdecl', 'CompileAs': 'CompileAsC', 'CompileAsManaged': 'true', 'CreateHotpatchableImage': 'true', 'DebugInformationFormat': 'ProgramDatabase', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'string1;string2', 'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions', 'EnableFiberSafeOptimizations': 'true', 'EnablePREfast': 'true', 'Enableprefast': 'bogus', 'ErrorReporting': 'Prompt', 'ExceptionHandling': 'SyncCThrow', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': 'Neither', 'FloatingPointExceptions': 'true', 'FloatingPointModel': 'Precise', 'ForceConformanceInForLoopScope': 'true', 'ForcedIncludeFiles': 'file1;file2', 'ForcedUsingFiles': 'file1;file2', 'FunctionLevelLinking': 'false', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': 'OnlyExplicitInline', 'IntrinsicFunctions': 'false', 'MinimalRebuild': 'true', 'MultiProcessorCompilation': 'true', 'ObjectFileName': 'a_file_name', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMPSupport': 'true', 'Optimization': 'Disabled', 'PrecompiledHeader': 'NotUsing', 'PrecompiledHeaderFile': 'a_file_name', 'PrecompiledHeaderOutputFile': 'a_file_name', 'PreprocessKeepComments': 'true', 'PreprocessorDefinitions': 'string1;string2', 'PreprocessOutputPath': 'a string1', 'PreprocessSuppressLineNumbers': 'false', 'PreprocessToFile': 'false', 'ProcessorNumber': '33', 'ProgramDataBaseFileName': 'a_file_name', 'RuntimeLibrary': 'MultiThreaded', 'RuntimeTypeInfo': 'true', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '1Byte', 'SuppressStartupBanner': 'true', 'TrackerLogDirectory': 'a_folder', 'TreatSpecificWarningsAsErrors': 'string1;string2', 'TreatWarningAsError': 'true', 'TreatWChar_tAsBuiltInType': 'true', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'string1;string2', 'UseFullPaths': 'true', 'UseUnicodeForAssemblerListing': 'true', 'WarningLevel': 'TurnOffAllWarnings', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': 'a_file_name', 'ZZXYZ': 'bogus'}, 'Link': { 'AdditionalDependencies': 'file1;file2', 'AdditionalLibraryDirectories': 'folder1;folder2', 'AdditionalManifestDependencies': 'file1;file2', 'AdditionalOptions': 'a string1', 'AddModuleNamesToAssembly': 'file1;file2', 'AllowIsolation': 'true', 'AssemblyDebug': '', 'AssemblyLinkResource': 'file1;file2', 'BaseAddress': 'a string1', 'BuildingInIDE': 'true', 'CLRImageType': 'ForceIJWImage', 'CLRSupportLastError': 'Enabled', 'CLRThreadAttribute': 'MTAThreadingAttribute', 'CLRUnmanagedCodeCheck': 'true', 'CreateHotPatchableImage': 'X86Image', 'DataExecutionPrevention': 'false', 'DelayLoadDLLs': 'file1;file2', 'DelaySign': 'true', 'Driver': 'NotSet', 'EmbedManagedResourceFile': 'file1;file2', 'EnableCOMDATFolding': 'false', 'EnableUAC': 'true', 'EntryPointSymbol': 'a string1', 'FixedBaseAddress': 'false', 'ForceFileOutput': 'Enabled', 'ForceSymbolReferences': 'file1;file2', 'FunctionOrder': 'a_file_name', 'GenerateDebugInformation': 'true', 'GenerateMapFile': 'true', 'HeapCommitSize': 'a string1', 'HeapReserveSize': 'a string1', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreEmbeddedIDL': 'true', 'IgnoreSpecificDefaultLibraries': 'a_file_list', 'ImageHasSafeExceptionHandlers': 'true', 'ImportLibrary': 'a_file_name', 'KeyContainer': 'a_file_name', 'KeyFile': 'a_file_name', 'LargeAddressAware': 'false', 'LinkDLL': 'true', 'LinkErrorReporting': 'SendErrorReport', 'LinkStatus': 'true', 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', 'ManifestFile': 'a_file_name', 'MapExports': 'true', 'MapFileName': 'a_file_name', 'MergedIDLBaseFileName': 'a_file_name', 'MergeSections': 'a string1', 'MidlCommandFile': 'a_file_name', 'MinimumRequiredVersion': 'a string1', 'ModuleDefinitionFile': 'a_file_name', 'MSDOSStubFileName': 'a_file_name', 'NoEntryPoint': 'true', 'OptimizeReferences': 'false', 'OutputFile': 'a_file_name', 'PerUserRedirection': 'true', 'PreventDllBinding': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': 'a_file_name', 'ProgramDatabaseFile': 'a_file_name', 'RandomizedBaseAddress': 'false', 'RegisterOutput': 'true', 'SectionAlignment': '33', 'SetChecksum': 'true', 'ShowProgress': 'LinkVerboseREF', 'SpecifySectionAttributes': 'a string1', 'StackCommitSize': 'a string1', 'StackReserveSize': 'a string1', 'StripPrivateSymbols': 'a_file_name', 'SubSystem': 'Console', 'SupportNobindOfDelayLoadedDLL': 'true', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'true', 'SwapRunFromCD': 'true', 'SwapRunFromNET': 'true', 'TargetMachine': 'MachineX86', 'TerminalServerAware': 'false', 'TrackerLogDirectory': 'a_folder', 'TreatLinkerWarningAsErrors': 'true', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'a_file_name', 'TypeLibraryResourceID': '33', 'UACExecutionLevel': 'AsInvoker', 'UACUIAccess': 'true', 'Version': 'a string1'}, 'ResourceCompile': { 'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'Culture': '0x236', 'IgnoreStandardIncludePath': 'true', 'NullTerminateStrings': 'true', 'PreprocessorDefinitions': 'string1;string2', 'ResourceOutputFileName': 'a string1', 'ShowProgress': 'true', 'SuppressStartupBanner': 'true', 'TrackerLogDirectory': 'a_folder', 'UndefinePreprocessorDefinitions': 'string1;string2'}, 'Midl': { 'AdditionalIncludeDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'ApplicationConfigurationMode': 'true', 'ClientStubFile': 'a_file_name', 'CPreprocessOptions': 'a string1', 'DefaultCharType': 'Signed', 'DllDataFileName': 'a_file_name', 'EnableErrorChecks': 'EnableCustom', 'ErrorCheckAllocations': 'true', 'ErrorCheckBounds': 'true', 'ErrorCheckEnumRange': 'true', 'ErrorCheckRefPointers': 'true', 'ErrorCheckStubData': 'true', 'GenerateClientFiles': 'Stub', 'GenerateServerFiles': 'None', 'GenerateStublessProxies': 'true', 'GenerateTypeLibrary': 'true', 'HeaderFileName': 'a_file_name', 'IgnoreStandardIncludePath': 'true', 'InterfaceIdentifierFileName': 'a_file_name', 'LocaleID': '33', 'MkTypLibCompatible': 'true', 'OutputDirectory': 'a string1', 'PreprocessorDefinitions': 'string1;string2', 'ProxyFileName': 'a_file_name', 'RedirectOutputAndErrors': 'a_file_name', 'ServerStubFile': 'a_file_name', 'StructMemberAlignment': 'NotSet', 'SuppressCompilerWarnings': 'true', 'SuppressStartupBanner': 'true', 'TargetEnvironment': 'Itanium', 'TrackerLogDirectory': 'a_folder', 'TypeLibFormat': 'NewFormat', 'TypeLibraryName': 'a_file_name', 'UndefinePreprocessorDefinitions': 'string1;string2', 'ValidateAllParameters': 'true', 'WarnAsError': 'true', 'WarningLevel': '1'}, 'Lib': { 'AdditionalDependencies': 'file1;file2', 'AdditionalLibraryDirectories': 'folder1;folder2', 'AdditionalOptions': 'a string1', 'DisplayLibrary': 'a string1', 'ErrorReporting': 'PromptImmediately', 'ExportNamedFunctions': 'string1;string2', 'ForceSymbolReferences': 'a string1', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreSpecificDefaultLibraries': 'file1;file2', 'LinkTimeCodeGeneration': 'true', 'MinimumRequiredVersion': 'a string1', 'ModuleDefinitionFile': 'a_file_name', 'Name': 'a_file_name', 'OutputFile': 'a_file_name', 'RemoveObjects': 'file1;file2', 'SubSystem': 'Console', 'SuppressStartupBanner': 'true', 'TargetMachine': 'MachineX86i', 'TrackerLogDirectory': 'a_folder', 'TreatLibWarningAsErrors': 'true', 'UseUnicodeResponseFiles': 'true', 'Verbose': 'true'}, 'Manifest': { 'AdditionalManifestFiles': 'file1;file2', 'AdditionalOptions': 'a string1', 'AssemblyIdentity': 'a string1', 'ComponentFileName': 'a_file_name', 'EnableDPIAwareness': 'fal', 'GenerateCatalogFiles': 'truel', 'GenerateCategoryTags': 'true', 'InputResourceManifests': 'a string1', 'ManifestFromManagedAssembly': 'a_file_name', 'notgood3': 'bogus', 'OutputManifestFile': 'a_file_name', 'OutputResourceManifests': 'a string1', 'RegistrarScriptFile': 'a_file_name', 'ReplacementsFile': 'a_file_name', 'SuppressDependencyElement': 'true', 'SuppressStartupBanner': 'true', 'TrackerLogDirectory': 'a_folder', 'TypeLibraryFile': 'a_file_name', 'UpdateFileHashes': 'true', 'UpdateFileHashesSearchPath': 'a_file_name', 'VerboseOutput': 'true'}, 'ProjectReference': { 'LinkLibraryDependencies': 'true', 'UseLibraryDependencyInputs': 'true'}, 'ManifestResourceCompile': { 'ResourceOutputFileName': 'a_file_name'}, '': { 'EmbedManifest': 'true', 'GenerateManifest': 'true', 'IgnoreImportLibrary': 'true', 'LinkIncremental': 'false'}}, self.stderr) self._ExpectedWarnings([ 'Warning: unrecognized setting ClCompile/Enableprefast', 'Warning: unrecognized setting ClCompile/ZZXYZ', 'Warning: unrecognized setting Manifest/notgood3', 'Warning: for Manifest/GenerateCatalogFiles, ' "expected bool; got 'truel'", 'Warning: for Lib/TargetMachine, unrecognized enumerated value ' 'MachineX86i', "Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"]) def testConvertToMSBuildSettings_empty(self): """Tests an empty conversion.""" msvs_settings = {} expected_msbuild_settings = {} actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_minimal(self): """Tests a minimal conversion.""" msvs_settings = { 'VCCLCompilerTool': { 'AdditionalIncludeDirectories': 'dir1', 'AdditionalOptions': '/foo', 'BasicRuntimeChecks': '0', }, 'VCLinkerTool': { 'LinkTimeCodeGeneration': '1', 'ErrorReporting': '1', 'DataExecutionPrevention': '2', }, } expected_msbuild_settings = { 'ClCompile': { 'AdditionalIncludeDirectories': 'dir1', 'AdditionalOptions': '/foo', 'BasicRuntimeChecks': 'Default', }, 'Link': { 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', 'LinkErrorReporting': 'PromptImmediately', 'DataExecutionPrevention': 'true', }, } actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_warnings(self): """Tests conversion that generates warnings.""" msvs_settings = { 'VCCLCompilerTool': { 'AdditionalIncludeDirectories': '1', 'AdditionalOptions': '2', # These are incorrect values: 'BasicRuntimeChecks': '12', 'BrowseInformation': '21', 'UsePrecompiledHeader': '13', 'GeneratePreprocessedFile': '14'}, 'VCLinkerTool': { # These are incorrect values: 'Driver': '10', 'LinkTimeCodeGeneration': '31', 'ErrorReporting': '21', 'FixedBaseAddress': '6'}, 'VCResourceCompilerTool': { # Custom 'Culture': '1003'}} expected_msbuild_settings = { 'ClCompile': { 'AdditionalIncludeDirectories': '1', 'AdditionalOptions': '2'}, 'Link': {}, 'ResourceCompile': { # Custom 'Culture': '0x03eb'}} actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([ 'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to ' 'MSBuild, index value (12) not in expected range [0, 4)', 'Warning: while converting VCCLCompilerTool/BrowseInformation to ' 'MSBuild, index value (21) not in expected range [0, 3)', 'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to ' 'MSBuild, index value (13) not in expected range [0, 3)', 'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to ' 'MSBuild, value must be one of [0, 1, 2]; got 14', 'Warning: while converting VCLinkerTool/Driver to ' 'MSBuild, index value (10) not in expected range [0, 4)', 'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to ' 'MSBuild, index value (31) not in expected range [0, 5)', 'Warning: while converting VCLinkerTool/ErrorReporting to ' 'MSBuild, index value (21) not in expected range [0, 3)', 'Warning: while converting VCLinkerTool/FixedBaseAddress to ' 'MSBuild, index value (6) not in expected range [0, 3)', ]) def testConvertToMSBuildSettings_full_synthetic(self): """Tests conversion of all the MSBuild settings.""" msvs_settings = { 'VCCLCompilerTool': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'AdditionalUsingDirectories': 'folder1;folder2;folder3', 'AssemblerListingLocation': 'a_file_name', 'AssemblerOutput': '0', 'BasicRuntimeChecks': '1', 'BrowseInformation': '2', 'BrowseInformationFile': 'a_file_name', 'BufferSecurityCheck': 'true', 'CallingConvention': '0', 'CompileAs': '1', 'DebugInformationFormat': '4', 'DefaultCharIsUnsigned': 'true', 'Detect64BitPortabilityProblems': 'true', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'd1;d2;d3', 'EnableEnhancedInstructionSet': '0', 'EnableFiberSafeOptimizations': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'EnablePREfast': 'true', 'ErrorReporting': '1', 'ExceptionHandling': '2', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': '0', 'FloatingPointExceptions': 'true', 'FloatingPointModel': '1', 'ForceConformanceInForLoopScope': 'true', 'ForcedIncludeFiles': 'file1;file2;file3', 'ForcedUsingFiles': 'file1;file2;file3', 'GeneratePreprocessedFile': '1', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': '2', 'KeepComments': 'true', 'MinimalRebuild': 'true', 'ObjectFile': 'a_file_name', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMP': 'true', 'Optimization': '3', 'PrecompiledHeaderFile': 'a_file_name', 'PrecompiledHeaderThrough': 'a_file_name', 'PreprocessorDefinitions': 'd1;d2;d3', 'ProgramDataBaseFileName': 'a_file_name', 'RuntimeLibrary': '0', 'RuntimeTypeInfo': 'true', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '1', 'SuppressStartupBanner': 'true', 'TreatWChar_tAsBuiltInType': 'true', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'd1;d2;d3', 'UseFullPaths': 'true', 'UsePrecompiledHeader': '1', 'UseUnicodeResponseFiles': 'true', 'WarnAsError': 'true', 'WarningLevel': '2', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': 'a_file_name'}, 'VCLinkerTool': { 'AdditionalDependencies': 'file1;file2;file3', 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', 'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3', 'AdditionalManifestDependencies': 'file1;file2;file3', 'AdditionalOptions': 'a_string', 'AddModuleNamesToAssembly': 'file1;file2;file3', 'AllowIsolation': 'true', 'AssemblyDebug': '0', 'AssemblyLinkResource': 'file1;file2;file3', 'BaseAddress': 'a_string', 'CLRImageType': '1', 'CLRThreadAttribute': '2', 'CLRUnmanagedCodeCheck': 'true', 'DataExecutionPrevention': '0', 'DelayLoadDLLs': 'file1;file2;file3', 'DelaySign': 'true', 'Driver': '1', 'EmbedManagedResourceFile': 'file1;file2;file3', 'EnableCOMDATFolding': '0', 'EnableUAC': 'true', 'EntryPointSymbol': 'a_string', 'ErrorReporting': '0', 'FixedBaseAddress': '1', 'ForceSymbolReferences': 'file1;file2;file3', 'FunctionOrder': 'a_file_name', 'GenerateDebugInformation': 'true', 'GenerateManifest': 'true', 'GenerateMapFile': 'true', 'HeapCommitSize': 'a_string', 'HeapReserveSize': 'a_string', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreDefaultLibraryNames': 'file1;file2;file3', 'IgnoreEmbeddedIDL': 'true', 'IgnoreImportLibrary': 'true', 'ImportLibrary': 'a_file_name', 'KeyContainer': 'a_file_name', 'KeyFile': 'a_file_name', 'LargeAddressAware': '2', 'LinkIncremental': '1', 'LinkLibraryDependencies': 'true', 'LinkTimeCodeGeneration': '2', 'ManifestFile': 'a_file_name', 'MapExports': 'true', 'MapFileName': 'a_file_name', 'MergedIDLBaseFileName': 'a_file_name', 'MergeSections': 'a_string', 'MidlCommandFile': 'a_file_name', 'ModuleDefinitionFile': 'a_file_name', 'OptimizeForWindows98': '1', 'OptimizeReferences': '0', 'OutputFile': 'a_file_name', 'PerUserRedirection': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': 'a_file_name', 'ProgramDatabaseFile': 'a_file_name', 'RandomizedBaseAddress': '1', 'RegisterOutput': 'true', 'ResourceOnlyDLL': 'true', 'SetChecksum': 'true', 'ShowProgress': '0', 'StackCommitSize': 'a_string', 'StackReserveSize': 'a_string', 'StripPrivateSymbols': 'a_file_name', 'SubSystem': '2', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'true', 'SwapRunFromCD': 'true', 'SwapRunFromNet': 'true', 'TargetMachine': '3', 'TerminalServerAware': '2', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'a_file_name', 'TypeLibraryResourceID': '33', 'UACExecutionLevel': '1', 'UACUIAccess': 'true', 'UseLibraryDependencyInputs': 'false', 'UseUnicodeResponseFiles': 'true', 'Version': 'a_string'}, 'VCResourceCompilerTool': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'Culture': '1003', 'IgnoreStandardIncludePath': 'true', 'PreprocessorDefinitions': 'd1;d2;d3', 'ResourceOutputFileName': 'a_string', 'ShowProgress': 'true', 'SuppressStartupBanner': 'true', 'UndefinePreprocessorDefinitions': 'd1;d2;d3'}, 'VCMIDLTool': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'CPreprocessOptions': 'a_string', 'DefaultCharType': '0', 'DLLDataFileName': 'a_file_name', 'EnableErrorChecks': '2', 'ErrorCheckAllocations': 'true', 'ErrorCheckBounds': 'true', 'ErrorCheckEnumRange': 'true', 'ErrorCheckRefPointers': 'true', 'ErrorCheckStubData': 'true', 'GenerateStublessProxies': 'true', 'GenerateTypeLibrary': 'true', 'HeaderFileName': 'a_file_name', 'IgnoreStandardIncludePath': 'true', 'InterfaceIdentifierFileName': 'a_file_name', 'MkTypLibCompatible': 'true', 'OutputDirectory': 'a_string', 'PreprocessorDefinitions': 'd1;d2;d3', 'ProxyFileName': 'a_file_name', 'RedirectOutputAndErrors': 'a_file_name', 'StructMemberAlignment': '3', 'SuppressStartupBanner': 'true', 'TargetEnvironment': '1', 'TypeLibraryName': 'a_file_name', 'UndefinePreprocessorDefinitions': 'd1;d2;d3', 'ValidateParameters': 'true', 'WarnAsError': 'true', 'WarningLevel': '4'}, 'VCLibrarianTool': { 'AdditionalDependencies': 'file1;file2;file3', 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', 'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'ExportNamedFunctions': 'd1;d2;d3', 'ForceSymbolReferences': 'a_string', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', 'LinkLibraryDependencies': 'true', 'ModuleDefinitionFile': 'a_file_name', 'OutputFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'UseUnicodeResponseFiles': 'true'}, 'VCManifestTool': { 'AdditionalManifestFiles': 'file1;file2;file3', 'AdditionalOptions': 'a_string', 'AssemblyIdentity': 'a_string', 'ComponentFileName': 'a_file_name', 'DependencyInformationFile': 'a_file_name', 'EmbedManifest': 'true', 'GenerateCatalogFiles': 'true', 'InputResourceManifests': 'a_string', 'ManifestResourceFile': 'my_name', 'OutputManifestFile': 'a_file_name', 'RegistrarScriptFile': 'a_file_name', 'ReplacementsFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'TypeLibraryFile': 'a_file_name', 'UpdateFileHashes': 'true', 'UpdateFileHashesSearchPath': 'a_file_name', 'UseFAT32Workaround': 'true', 'UseUnicodeResponseFiles': 'true', 'VerboseOutput': 'true'}} expected_msbuild_settings = { 'ClCompile': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string /J', 'AdditionalUsingDirectories': 'folder1;folder2;folder3', 'AssemblerListingLocation': 'a_file_name', 'AssemblerOutput': 'NoListing', 'BasicRuntimeChecks': 'StackFrameRuntimeCheck', 'BrowseInformation': 'true', 'BrowseInformationFile': 'a_file_name', 'BufferSecurityCheck': 'true', 'CallingConvention': 'Cdecl', 'CompileAs': 'CompileAsC', 'DebugInformationFormat': 'EditAndContinue', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'd1;d2;d3', 'EnableEnhancedInstructionSet': 'NotSet', 'EnableFiberSafeOptimizations': 'true', 'EnablePREfast': 'true', 'ErrorReporting': 'Prompt', 'ExceptionHandling': 'Async', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': 'Neither', 'FloatingPointExceptions': 'true', 'FloatingPointModel': 'Strict', 'ForceConformanceInForLoopScope': 'true', 'ForcedIncludeFiles': 'file1;file2;file3', 'ForcedUsingFiles': 'file1;file2;file3', 'FunctionLevelLinking': 'true', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': 'AnySuitable', 'IntrinsicFunctions': 'true', 'MinimalRebuild': 'true', 'ObjectFileName': 'a_file_name', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMPSupport': 'true', 'Optimization': 'Full', 'PrecompiledHeader': 'Create', 'PrecompiledHeaderFile': 'a_file_name', 'PrecompiledHeaderOutputFile': 'a_file_name', 'PreprocessKeepComments': 'true', 'PreprocessorDefinitions': 'd1;d2;d3', 'PreprocessSuppressLineNumbers': 'false', 'PreprocessToFile': 'true', 'ProgramDataBaseFileName': 'a_file_name', 'RuntimeLibrary': 'MultiThreaded', 'RuntimeTypeInfo': 'true', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '1Byte', 'SuppressStartupBanner': 'true', 'TreatWarningAsError': 'true', 'TreatWChar_tAsBuiltInType': 'true', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'd1;d2;d3', 'UseFullPaths': 'true', 'WarningLevel': 'Level2', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': 'a_file_name'}, 'Link': { 'AdditionalDependencies': 'file1;file2;file3', 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', 'AdditionalManifestDependencies': 'file1;file2;file3', 'AdditionalOptions': 'a_string', 'AddModuleNamesToAssembly': 'file1;file2;file3', 'AllowIsolation': 'true', 'AssemblyDebug': '', 'AssemblyLinkResource': 'file1;file2;file3', 'BaseAddress': 'a_string', 'CLRImageType': 'ForceIJWImage', 'CLRThreadAttribute': 'STAThreadingAttribute', 'CLRUnmanagedCodeCheck': 'true', 'DataExecutionPrevention': '', 'DelayLoadDLLs': 'file1;file2;file3', 'DelaySign': 'true', 'Driver': 'Driver', 'EmbedManagedResourceFile': 'file1;file2;file3', 'EnableCOMDATFolding': '', 'EnableUAC': 'true', 'EntryPointSymbol': 'a_string', 'FixedBaseAddress': 'false', 'ForceSymbolReferences': 'file1;file2;file3', 'FunctionOrder': 'a_file_name', 'GenerateDebugInformation': 'true', 'GenerateMapFile': 'true', 'HeapCommitSize': 'a_string', 'HeapReserveSize': 'a_string', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreEmbeddedIDL': 'true', 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', 'ImportLibrary': 'a_file_name', 'KeyContainer': 'a_file_name', 'KeyFile': 'a_file_name', 'LargeAddressAware': 'true', 'LinkErrorReporting': 'NoErrorReport', 'LinkTimeCodeGeneration': 'PGInstrument', 'ManifestFile': 'a_file_name', 'MapExports': 'true', 'MapFileName': 'a_file_name', 'MergedIDLBaseFileName': 'a_file_name', 'MergeSections': 'a_string', 'MidlCommandFile': 'a_file_name', 'ModuleDefinitionFile': 'a_file_name', 'NoEntryPoint': 'true', 'OptimizeReferences': '', 'OutputFile': 'a_file_name', 'PerUserRedirection': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': 'a_file_name', 'ProgramDatabaseFile': 'a_file_name', 'RandomizedBaseAddress': 'false', 'RegisterOutput': 'true', 'SetChecksum': 'true', 'ShowProgress': 'NotSet', 'StackCommitSize': 'a_string', 'StackReserveSize': 'a_string', 'StripPrivateSymbols': 'a_file_name', 'SubSystem': 'Windows', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'true', 'SwapRunFromCD': 'true', 'SwapRunFromNET': 'true', 'TargetMachine': 'MachineARM', 'TerminalServerAware': 'true', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'a_file_name', 'TypeLibraryResourceID': '33', 'UACExecutionLevel': 'HighestAvailable', 'UACUIAccess': 'true', 'Version': 'a_string'}, 'ResourceCompile': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'Culture': '0x03eb', 'IgnoreStandardIncludePath': 'true', 'PreprocessorDefinitions': 'd1;d2;d3', 'ResourceOutputFileName': 'a_string', 'ShowProgress': 'true', 'SuppressStartupBanner': 'true', 'UndefinePreprocessorDefinitions': 'd1;d2;d3'}, 'Midl': { 'AdditionalIncludeDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'CPreprocessOptions': 'a_string', 'DefaultCharType': 'Unsigned', 'DllDataFileName': 'a_file_name', 'EnableErrorChecks': 'All', 'ErrorCheckAllocations': 'true', 'ErrorCheckBounds': 'true', 'ErrorCheckEnumRange': 'true', 'ErrorCheckRefPointers': 'true', 'ErrorCheckStubData': 'true', 'GenerateStublessProxies': 'true', 'GenerateTypeLibrary': 'true', 'HeaderFileName': 'a_file_name', 'IgnoreStandardIncludePath': 'true', 'InterfaceIdentifierFileName': 'a_file_name', 'MkTypLibCompatible': 'true', 'OutputDirectory': 'a_string', 'PreprocessorDefinitions': 'd1;d2;d3', 'ProxyFileName': 'a_file_name', 'RedirectOutputAndErrors': 'a_file_name', 'StructMemberAlignment': '4', 'SuppressStartupBanner': 'true', 'TargetEnvironment': 'Win32', 'TypeLibraryName': 'a_file_name', 'UndefinePreprocessorDefinitions': 'd1;d2;d3', 'ValidateAllParameters': 'true', 'WarnAsError': 'true', 'WarningLevel': '4'}, 'Lib': { 'AdditionalDependencies': 'file1;file2;file3', 'AdditionalLibraryDirectories': 'folder1;folder2;folder3', 'AdditionalOptions': 'a_string', 'ExportNamedFunctions': 'd1;d2;d3', 'ForceSymbolReferences': 'a_string', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreSpecificDefaultLibraries': 'file1;file2;file3', 'ModuleDefinitionFile': 'a_file_name', 'OutputFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'UseUnicodeResponseFiles': 'true'}, 'Manifest': { 'AdditionalManifestFiles': 'file1;file2;file3', 'AdditionalOptions': 'a_string', 'AssemblyIdentity': 'a_string', 'ComponentFileName': 'a_file_name', 'GenerateCatalogFiles': 'true', 'InputResourceManifests': 'a_string', 'OutputManifestFile': 'a_file_name', 'RegistrarScriptFile': 'a_file_name', 'ReplacementsFile': 'a_file_name', 'SuppressStartupBanner': 'true', 'TypeLibraryFile': 'a_file_name', 'UpdateFileHashes': 'true', 'UpdateFileHashesSearchPath': 'a_file_name', 'VerboseOutput': 'true'}, 'ManifestResourceCompile': { 'ResourceOutputFileName': 'my_name'}, 'ProjectReference': { 'LinkLibraryDependencies': 'true', 'UseLibraryDependencyInputs': 'false'}, '': { 'EmbedManifest': 'true', 'GenerateManifest': 'true', 'IgnoreImportLibrary': 'true', 'LinkIncremental': 'false'}} actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_actual(self): """Tests the conversion of an actual project. A VS2008 project with most of the options defined was created through the VS2008 IDE. It was then converted to VS2010. The tool settings found in the .vcproj and .vcxproj files were converted to the two dictionaries msvs_settings and expected_msbuild_settings. Note that for many settings, the VS2010 converter adds macros like %(AdditionalIncludeDirectories) to make sure than inherited values are included. Since the Gyp projects we generate do not use inheritance, we removed these macros. They were: ClCompile: AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)' AdditionalOptions: ' %(AdditionalOptions)' AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)' DisableSpecificWarnings: ';%(DisableSpecificWarnings)', ForcedIncludeFiles: ';%(ForcedIncludeFiles)', ForcedUsingFiles: ';%(ForcedUsingFiles)', PreprocessorDefinitions: ';%(PreprocessorDefinitions)', UndefinePreprocessorDefinitions: ';%(UndefinePreprocessorDefinitions)', Link: AdditionalDependencies: ';%(AdditionalDependencies)', AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)', AdditionalManifestDependencies: ';%(AdditionalManifestDependencies)', AdditionalOptions: ' %(AdditionalOptions)', AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)', AssemblyLinkResource: ';%(AssemblyLinkResource)', DelayLoadDLLs: ';%(DelayLoadDLLs)', EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)', ForceSymbolReferences: ';%(ForceSymbolReferences)', IgnoreSpecificDefaultLibraries: ';%(IgnoreSpecificDefaultLibraries)', ResourceCompile: AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)', AdditionalOptions: ' %(AdditionalOptions)', PreprocessorDefinitions: ';%(PreprocessorDefinitions)', Manifest: AdditionalManifestFiles: ';%(AdditionalManifestFiles)', AdditionalOptions: ' %(AdditionalOptions)', InputResourceManifests: ';%(InputResourceManifests)', """ msvs_settings = { 'VCCLCompilerTool': { 'AdditionalIncludeDirectories': 'dir1', 'AdditionalOptions': '/more', 'AdditionalUsingDirectories': 'test', 'AssemblerListingLocation': '$(IntDir)\\a', 'AssemblerOutput': '1', 'BasicRuntimeChecks': '3', 'BrowseInformation': '1', 'BrowseInformationFile': '$(IntDir)\\e', 'BufferSecurityCheck': 'false', 'CallingConvention': '1', 'CompileAs': '1', 'DebugInformationFormat': '4', 'DefaultCharIsUnsigned': 'true', 'Detect64BitPortabilityProblems': 'true', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'abc', 'EnableEnhancedInstructionSet': '1', 'EnableFiberSafeOptimizations': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'EnablePREfast': 'true', 'ErrorReporting': '2', 'ExceptionHandling': '2', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': '2', 'FloatingPointExceptions': 'true', 'FloatingPointModel': '1', 'ForceConformanceInForLoopScope': 'false', 'ForcedIncludeFiles': 'def', 'ForcedUsingFiles': 'ge', 'GeneratePreprocessedFile': '2', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': '1', 'KeepComments': 'true', 'MinimalRebuild': 'true', 'ObjectFile': '$(IntDir)\\b', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMP': 'true', 'Optimization': '3', 'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche', 'PrecompiledHeaderThrough': 'StdAfx.hd', 'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE', 'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb', 'RuntimeLibrary': '3', 'RuntimeTypeInfo': 'false', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '3', 'SuppressStartupBanner': 'false', 'TreatWChar_tAsBuiltInType': 'false', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'wer', 'UseFullPaths': 'true', 'UsePrecompiledHeader': '0', 'UseUnicodeResponseFiles': 'false', 'WarnAsError': 'true', 'WarningLevel': '3', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': '$(IntDir)\\c'}, 'VCLinkerTool': { 'AdditionalDependencies': 'zx', 'AdditionalLibraryDirectories': 'asd', 'AdditionalManifestDependencies': 's2', 'AdditionalOptions': '/mor2', 'AddModuleNamesToAssembly': 'd1', 'AllowIsolation': 'false', 'AssemblyDebug': '1', 'AssemblyLinkResource': 'd5', 'BaseAddress': '23423', 'CLRImageType': '3', 'CLRThreadAttribute': '1', 'CLRUnmanagedCodeCheck': 'true', 'DataExecutionPrevention': '0', 'DelayLoadDLLs': 'd4', 'DelaySign': 'true', 'Driver': '2', 'EmbedManagedResourceFile': 'd2', 'EnableCOMDATFolding': '1', 'EnableUAC': 'false', 'EntryPointSymbol': 'f5', 'ErrorReporting': '2', 'FixedBaseAddress': '1', 'ForceSymbolReferences': 'd3', 'FunctionOrder': 'fssdfsd', 'GenerateDebugInformation': 'true', 'GenerateManifest': 'false', 'GenerateMapFile': 'true', 'HeapCommitSize': '13', 'HeapReserveSize': '12', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreDefaultLibraryNames': 'flob;flok', 'IgnoreEmbeddedIDL': 'true', 'IgnoreImportLibrary': 'true', 'ImportLibrary': 'f4', 'KeyContainer': 'f7', 'KeyFile': 'f6', 'LargeAddressAware': '2', 'LinkIncremental': '0', 'LinkLibraryDependencies': 'false', 'LinkTimeCodeGeneration': '1', 'ManifestFile': '$(IntDir)\\$(TargetFileName).2intermediate.manifest', 'MapExports': 'true', 'MapFileName': 'd5', 'MergedIDLBaseFileName': 'f2', 'MergeSections': 'f5', 'MidlCommandFile': 'f1', 'ModuleDefinitionFile': 'sdsd', 'OptimizeForWindows98': '2', 'OptimizeReferences': '2', 'OutputFile': '$(OutDir)\\$(ProjectName)2.exe', 'PerUserRedirection': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd', 'ProgramDatabaseFile': 'Flob.pdb', 'RandomizedBaseAddress': '1', 'RegisterOutput': 'true', 'ResourceOnlyDLL': 'true', 'SetChecksum': 'false', 'ShowProgress': '1', 'StackCommitSize': '15', 'StackReserveSize': '14', 'StripPrivateSymbols': 'd3', 'SubSystem': '1', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'false', 'SwapRunFromCD': 'true', 'SwapRunFromNet': 'true', 'TargetMachine': '1', 'TerminalServerAware': '1', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'f3', 'TypeLibraryResourceID': '12', 'UACExecutionLevel': '2', 'UACUIAccess': 'true', 'UseLibraryDependencyInputs': 'true', 'UseUnicodeResponseFiles': 'false', 'Version': '333'}, 'VCResourceCompilerTool': { 'AdditionalIncludeDirectories': 'f3', 'AdditionalOptions': '/more3', 'Culture': '3084', 'IgnoreStandardIncludePath': 'true', 'PreprocessorDefinitions': '_UNICODE;UNICODE2', 'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res', 'ShowProgress': 'true'}, 'VCManifestTool': { 'AdditionalManifestFiles': 'sfsdfsd', 'AdditionalOptions': 'afdsdafsd', 'AssemblyIdentity': 'sddfdsadfsa', 'ComponentFileName': 'fsdfds', 'DependencyInformationFile': '$(IntDir)\\mt.depdfd', 'EmbedManifest': 'false', 'GenerateCatalogFiles': 'true', 'InputResourceManifests': 'asfsfdafs', 'ManifestResourceFile': '$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf', 'OutputManifestFile': '$(TargetPath).manifestdfs', 'RegistrarScriptFile': 'sdfsfd', 'ReplacementsFile': 'sdffsd', 'SuppressStartupBanner': 'false', 'TypeLibraryFile': 'sfsd', 'UpdateFileHashes': 'true', 'UpdateFileHashesSearchPath': 'sfsd', 'UseFAT32Workaround': 'true', 'UseUnicodeResponseFiles': 'false', 'VerboseOutput': 'true'}} expected_msbuild_settings = { 'ClCompile': { 'AdditionalIncludeDirectories': 'dir1', 'AdditionalOptions': '/more /J', 'AdditionalUsingDirectories': 'test', 'AssemblerListingLocation': '$(IntDir)a', 'AssemblerOutput': 'AssemblyCode', 'BasicRuntimeChecks': 'EnableFastChecks', 'BrowseInformation': 'true', 'BrowseInformationFile': '$(IntDir)e', 'BufferSecurityCheck': 'false', 'CallingConvention': 'FastCall', 'CompileAs': 'CompileAsC', 'DebugInformationFormat': 'EditAndContinue', 'DisableLanguageExtensions': 'true', 'DisableSpecificWarnings': 'abc', 'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions', 'EnableFiberSafeOptimizations': 'true', 'EnablePREfast': 'true', 'ErrorReporting': 'Queue', 'ExceptionHandling': 'Async', 'ExpandAttributedSource': 'true', 'FavorSizeOrSpeed': 'Size', 'FloatingPointExceptions': 'true', 'FloatingPointModel': 'Strict', 'ForceConformanceInForLoopScope': 'false', 'ForcedIncludeFiles': 'def', 'ForcedUsingFiles': 'ge', 'FunctionLevelLinking': 'true', 'GenerateXMLDocumentationFiles': 'true', 'IgnoreStandardIncludePath': 'true', 'InlineFunctionExpansion': 'OnlyExplicitInline', 'IntrinsicFunctions': 'true', 'MinimalRebuild': 'true', 'ObjectFileName': '$(IntDir)b', 'OmitDefaultLibName': 'true', 'OmitFramePointers': 'true', 'OpenMPSupport': 'true', 'Optimization': 'Full', 'PrecompiledHeader': 'NotUsing', # Actual conversion gives '' 'PrecompiledHeaderFile': 'StdAfx.hd', 'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche', 'PreprocessKeepComments': 'true', 'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE', 'PreprocessSuppressLineNumbers': 'true', 'PreprocessToFile': 'true', 'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb', 'RuntimeLibrary': 'MultiThreadedDebugDLL', 'RuntimeTypeInfo': 'false', 'ShowIncludes': 'true', 'SmallerTypeCheck': 'true', 'StringPooling': 'true', 'StructMemberAlignment': '4Bytes', 'SuppressStartupBanner': 'false', 'TreatWarningAsError': 'true', 'TreatWChar_tAsBuiltInType': 'false', 'UndefineAllPreprocessorDefinitions': 'true', 'UndefinePreprocessorDefinitions': 'wer', 'UseFullPaths': 'true', 'WarningLevel': 'Level3', 'WholeProgramOptimization': 'true', 'XMLDocumentationFileName': '$(IntDir)c'}, 'Link': { 'AdditionalDependencies': 'zx', 'AdditionalLibraryDirectories': 'asd', 'AdditionalManifestDependencies': 's2', 'AdditionalOptions': '/mor2', 'AddModuleNamesToAssembly': 'd1', 'AllowIsolation': 'false', 'AssemblyDebug': 'true', 'AssemblyLinkResource': 'd5', 'BaseAddress': '23423', 'CLRImageType': 'ForceSafeILImage', 'CLRThreadAttribute': 'MTAThreadingAttribute', 'CLRUnmanagedCodeCheck': 'true', 'DataExecutionPrevention': '', 'DelayLoadDLLs': 'd4', 'DelaySign': 'true', 'Driver': 'UpOnly', 'EmbedManagedResourceFile': 'd2', 'EnableCOMDATFolding': 'false', 'EnableUAC': 'false', 'EntryPointSymbol': 'f5', 'FixedBaseAddress': 'false', 'ForceSymbolReferences': 'd3', 'FunctionOrder': 'fssdfsd', 'GenerateDebugInformation': 'true', 'GenerateMapFile': 'true', 'HeapCommitSize': '13', 'HeapReserveSize': '12', 'IgnoreAllDefaultLibraries': 'true', 'IgnoreEmbeddedIDL': 'true', 'IgnoreSpecificDefaultLibraries': 'flob;flok', 'ImportLibrary': 'f4', 'KeyContainer': 'f7', 'KeyFile': 'f6', 'LargeAddressAware': 'true', 'LinkErrorReporting': 'QueueForNextLogin', 'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration', 'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest', 'MapExports': 'true', 'MapFileName': 'd5', 'MergedIDLBaseFileName': 'f2', 'MergeSections': 'f5', 'MidlCommandFile': 'f1', 'ModuleDefinitionFile': 'sdsd', 'NoEntryPoint': 'true', 'OptimizeReferences': 'true', 'OutputFile': '$(OutDir)$(ProjectName)2.exe', 'PerUserRedirection': 'true', 'Profile': 'true', 'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd', 'ProgramDatabaseFile': 'Flob.pdb', 'RandomizedBaseAddress': 'false', 'RegisterOutput': 'true', 'SetChecksum': 'false', 'ShowProgress': 'LinkVerbose', 'StackCommitSize': '15', 'StackReserveSize': '14', 'StripPrivateSymbols': 'd3', 'SubSystem': 'Console', 'SupportUnloadOfDelayLoadedDLL': 'true', 'SuppressStartupBanner': 'false', 'SwapRunFromCD': 'true', 'SwapRunFromNET': 'true', 'TargetMachine': 'MachineX86', 'TerminalServerAware': 'false', 'TurnOffAssemblyGeneration': 'true', 'TypeLibraryFile': 'f3', 'TypeLibraryResourceID': '12', 'UACExecutionLevel': 'RequireAdministrator', 'UACUIAccess': 'true', 'Version': '333'}, 'ResourceCompile': { 'AdditionalIncludeDirectories': 'f3', 'AdditionalOptions': '/more3', 'Culture': '0x0c0c', 'IgnoreStandardIncludePath': 'true', 'PreprocessorDefinitions': '_UNICODE;UNICODE2', 'ResourceOutputFileName': '$(IntDir)%(Filename)3.res', 'ShowProgress': 'true'}, 'Manifest': { 'AdditionalManifestFiles': 'sfsdfsd', 'AdditionalOptions': 'afdsdafsd', 'AssemblyIdentity': 'sddfdsadfsa', 'ComponentFileName': 'fsdfds', 'GenerateCatalogFiles': 'true', 'InputResourceManifests': 'asfsfdafs', 'OutputManifestFile': '$(TargetPath).manifestdfs', 'RegistrarScriptFile': 'sdfsfd', 'ReplacementsFile': 'sdffsd', 'SuppressStartupBanner': 'false', 'TypeLibraryFile': 'sfsd', 'UpdateFileHashes': 'true', 'UpdateFileHashesSearchPath': 'sfsd', 'VerboseOutput': 'true'}, 'ProjectReference': { 'LinkLibraryDependencies': 'false', 'UseLibraryDependencyInputs': 'true'}, '': { 'EmbedManifest': 'false', 'GenerateManifest': 'false', 'IgnoreImportLibrary': 'true', 'LinkIncremental': '' }, 'ManifestResourceCompile': { 'ResourceOutputFileName': '$(IntDir)$(TargetFileName).embed.manifest.resfdsf'} } actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) if __name__ == '__main__': unittest.main()
mit
benoitsteiner/tensorflow-opencl
tensorflow/contrib/learn/python/learn/estimators/tensor_signature.py
134
6730
# 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. # ============================================================================== """TensorSignature class and utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python.framework import dtypes from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import parsing_ops class TensorSignature(collections.namedtuple( "TensorSignature", ["dtype", "shape", "is_sparse"])): """Signature of the `Tensor` object. Useful to check compatibility of tensors. Example: ```python examples = tf.placeholder(...) inputs = {'a': var_a, 'b': var_b} signatures = tensor_signature.create_signatures(inputs) result = tensor_signature.create_example_parser_from_signatures( signatures, examples) self.assertTrue(tensor_signature.tensors_compatible(result, signatures)) ``` Attributes: dtype: `DType` object. shape: `TensorShape` object. """ def __new__(cls, tensor): if isinstance(tensor, sparse_tensor.SparseTensor): return super(TensorSignature, cls).__new__( cls, dtype=tensor.values.dtype, shape=None, is_sparse=True) return super(TensorSignature, cls).__new__( cls, dtype=tensor.dtype, shape=tensor.get_shape(), is_sparse=False) def is_compatible_with(self, other): """Returns True if signatures are compatible.""" def _shape_is_compatible_0dim(this, other): """Checks that shapes are compatible skipping dim 0.""" other = tensor_shape.as_shape(other) # If shapes are None (unknown) they may be compatible. if this.dims is None or other.dims is None: return True if this.ndims != other.ndims: return False for dim, (x_dim, y_dim) in enumerate(zip(this.dims, other.dims)): if dim == 0: continue if not x_dim.is_compatible_with(y_dim): return False return True if other.is_sparse: return self.is_sparse and self.dtype.is_compatible_with(other.dtype) return (self.dtype.is_compatible_with(other.dtype) and _shape_is_compatible_0dim(self.shape, other.shape) and not self.is_sparse) def get_placeholder(self): if self.is_sparse: return array_ops.sparse_placeholder(dtype=self.dtype) return array_ops.placeholder(dtype=self.dtype, shape=[None] + list(self.shape[1:])) def get_feature_spec(self): dtype = self.dtype # Convert, because example parser only supports float32, int64 and string. if dtype == dtypes.int32: dtype = dtypes.int64 if dtype == dtypes.float64: dtype = dtypes.float32 if self.is_sparse: return parsing_ops.VarLenFeature(dtype=dtype) return parsing_ops.FixedLenFeature(shape=self.shape[1:], dtype=dtype) def tensors_compatible(tensors, signatures): """Check that tensors are compatible with signatures. Args: tensors: Dict of `Tensor` objects or single `Tensor` object. signatures: Dict of `TensorSignature` objects or single `TensorSignature` object. Returns: True if all tensors are compatible, False otherwise. """ # Dict of Tensors as input. if tensors is None: return signatures is None if isinstance(tensors, dict): if not isinstance(signatures, dict): return False for key in signatures: if key not in tensors: return False if not TensorSignature(tensors[key]).is_compatible_with(signatures[key]): return False return True # Single tensor as input. if signatures is None or isinstance(signatures, dict): return False return TensorSignature(tensors).is_compatible_with(signatures) def create_signatures(tensors): """Creates TensorSignature objects for given tensors. Args: tensors: Dict of `Tensor` objects or single `Tensor`. Returns: Dict of `TensorSignature` objects or single `TensorSignature`. """ if isinstance(tensors, dict): return { key: TensorSignature(tensors[key]) for key in tensors} if tensors is None: return None return TensorSignature(tensors) def create_placeholders_from_signatures(signatures): """Creates placeholders from given signatures. Args: signatures: Dict of `TensorSignature` objects or single `TensorSignature`, or `None`. Returns: Dict of `tf.placeholder` objects or single `tf.placeholder`, or `None`. """ if signatures is None: return None if not isinstance(signatures, dict): return signatures.get_placeholder() return { key: signatures[key].get_placeholder() for key in signatures} def create_example_parser_from_signatures(signatures, examples_batch, single_feature_name="feature"): """Creates example parser from given signatures. Args: signatures: Dict of `TensorSignature` objects or single `TensorSignature`. examples_batch: string `Tensor` of serialized `Example` proto. single_feature_name: string, single feature name. Returns: features: `Tensor` or `dict` of `Tensor` objects. """ feature_spec = {} if not isinstance(signatures, dict): feature_spec[single_feature_name] = signatures.get_feature_spec() else: feature_spec = {key: signatures[key].get_feature_spec() for key in signatures} features = parsing_ops.parse_example(examples_batch, feature_spec) if not isinstance(signatures, dict): # Returns single feature, casts if needed. features = features[single_feature_name] if not signatures.dtype.is_compatible_with(features.dtype): features = math_ops.cast(features, signatures.dtype) return features # Returns dict of features, casts if needed. for name in features: if not signatures[name].dtype.is_compatible_with(features[name].dtype): features[name] = math_ops.cast(features[name], signatures[name].dtype) return features
apache-2.0