repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
xuxiao19910803/edx-platform
common/djangoapps/student/tests/test_credit.py
12
8127
""" Tests for credit courses on the student dashboard. """ import unittest import datetime import pytz from mock import patch from django.conf import settings from django.core.urlresolvers import reverse from django.test.utils import override_settings from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory from student.models import CourseEnrollmentAttribute from student.tests.factories import UserFactory, CourseEnrollmentFactory from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider, CreditEligibility from openedx.core.djangoapps.credit import api as credit_api TEST_CREDIT_PROVIDER_SECRET_KEY = "931433d583c84ca7ba41784bad3232e6" @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') @override_settings(CREDIT_PROVIDER_SECRET_KEYS={ "hogwarts": TEST_CREDIT_PROVIDER_SECRET_KEY, }) @patch.dict(settings.FEATURES, {"ENABLE_CREDIT_ELIGIBILITY": True}) class CreditCourseDashboardTest(ModuleStoreTestCase): """ Tests for credit courses on the student dashboard. """ USERNAME = "ron" PASSWORD = "mobiliarbus" PROVIDER_ID = "hogwarts" PROVIDER_NAME = "Hogwarts School of Witchcraft and Wizardry" PROVIDER_STATUS_URL = "http://credit.example.com/status" def setUp(self): """Create a course and an enrollment. """ super(CreditCourseDashboardTest, self).setUp() # Create a user and log in self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD) result = self.client.login(username=self.USERNAME, password=self.PASSWORD) self.assertTrue(result, msg="Could not log in") # Create a course and configure it as a credit course self.course = CourseFactory() CreditCourse.objects.create(course_key=self.course.id, enabled=True) # pylint: disable=no-member # Configure a credit provider CreditProvider.objects.create( provider_id=self.PROVIDER_ID, display_name=self.PROVIDER_NAME, provider_status_url=self.PROVIDER_STATUS_URL, enable_integration=True, ) # Configure a single credit requirement (minimum passing grade) credit_api.set_credit_requirements( self.course.id, # pylint: disable=no-member [ { "namespace": "grade", "name": "grade", "display_name": "Final Grade", "criteria": { "min_grade": 0.8 } } ] ) # Enroll the user in the course as "verified" self.enrollment = CourseEnrollmentFactory( user=self.user, course_id=self.course.id, # pylint: disable=no-member mode="verified" ) def test_not_eligible_for_credit(self): # The user is not yet eligible for credit, so no additional information should be displayed on the dashboard. response = self._load_dashboard() self.assertNotContains(response, "credit") def test_eligible_for_credit(self): # Simulate that the user has completed the only requirement in the course # so the user is eligible for credit. self._make_eligible() # The user should have the option to purchase credit response = self._load_dashboard() self.assertContains(response, "credit-eligibility-msg") self.assertContains(response, "purchase-credit-btn") # Move the eligibility deadline so it's within 30 days eligibility = CreditEligibility.objects.get(username=self.USERNAME) eligibility.deadline = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=29) eligibility.save() # The user should still have the option to purchase credit, # but there should also be a message urging the user to purchase soon. response = self._load_dashboard() self.assertContains(response, "credit-eligibility-msg") self.assertContains(response, "purchase-credit-btn") self.assertContains(response, "purchase credit for this course expires") def test_purchased_credit(self): # Simulate that the user has purchased credit, but has not # yet initiated a request to the credit provider self._make_eligible() self._purchase_credit() # Expect that the user's status is "pending" response = self._load_dashboard() self.assertContains(response, "credit-request-pending-msg") def test_purchased_credit_and_request_pending(self): # Simulate that the user has purchased credit and initiated a request, # but we haven't yet heard back from the credit provider. self._make_eligible() self._purchase_credit() self._initiate_request() # Expect that the user's status is "pending" response = self._load_dashboard() self.assertContains(response, "credit-request-pending-msg") def test_purchased_credit_and_request_approved(self): # Simulate that the user has purchased credit and initiated a request, # and had that request approved by the credit provider self._make_eligible() self._purchase_credit() request_uuid = self._initiate_request() self._set_request_status(request_uuid, "approved") # Expect that the user's status is "approved" response = self._load_dashboard() self.assertContains(response, "credit-request-approved-msg") def test_purchased_credit_and_request_rejected(self): # Simulate that the user has purchased credit and initiated a request, # and had that request rejected by the credit provider self._make_eligible() self._purchase_credit() request_uuid = self._initiate_request() self._set_request_status(request_uuid, "rejected") # Expect that the user's status is "approved" response = self._load_dashboard() self.assertContains(response, "credit-request-rejected-msg") def test_credit_status_error(self): # Simulate an error condition: the user has a credit enrollment # but no enrollment attribute indicating which provider the user # purchased credit from. self._make_eligible() self._purchase_credit() CourseEnrollmentAttribute.objects.all().delete() # Expect an error message response = self._load_dashboard() self.assertContains(response, "credit-error-msg") def _load_dashboard(self): """Load the student dashboard and return the HttpResponse. """ return self.client.get(reverse("dashboard")) def _make_eligible(self): """Make the user eligible for credit in the course. """ credit_api.set_credit_requirement_status( self.USERNAME, self.course.id, # pylint: disable=no-member "grade", "grade", status="satisfied", reason={ "final_grade": 0.95 } ) def _purchase_credit(self): """Purchase credit from a provider in the course. """ self.enrollment.mode = "credit" self.enrollment.save() # pylint: disable=no-member CourseEnrollmentAttribute.objects.create( enrollment=self.enrollment, namespace="credit", name="provider_id", value=self.PROVIDER_ID, ) def _initiate_request(self): """Initiate a request for credit from a provider. """ request = credit_api.create_credit_request( self.course.id, # pylint: disable=no-member self.PROVIDER_ID, self.USERNAME ) return request["parameters"]["request_uuid"] def _set_request_status(self, uuid, status): """Set the status of a request for credit, simulating the notification from the provider. """ credit_api.update_credit_request_status(uuid, self.PROVIDER_ID, status)
agpl-3.0
jakirkham/lazyflow
lazyflow/operators/opFeatureMatrixCache.py
1
12534
from functools import partial import logging logger = logging.getLogger(__name__) import numpy from lazyflow.graph import Operator, InputSlot, OutputSlot from lazyflow.request import RequestLock, Request, RequestPool from lazyflow.utility import OrderedSignal from lazyflow.roi import getBlockBounds, getIntersectingBlocks, determineBlockShape class OpFeatureMatrixCache(Operator): """ - Request features and labels in blocks - For nonzero label pixels in each block, extract the label image - Cache the feature matrix for each block separately - Output the concatenation of all feature matrices Note: This operator does not currently use the NonZeroLabelBlocks slot. Instead, it only requests labels for blocks that have been marked dirty via dirty notifications from the LabelImage slot. As a result, you MUST connect/configure this operator before you load your upstream label cache with values. This operator must already be "watching" when when the label operator is initialized with its first labels. """ FeatureImage = InputSlot() LabelImage = InputSlot() NonZeroLabelBlocks = InputSlot() # TODO: Eliminate this slot. It isn't used... # Output is a single 'value', which is a 2D ndarray. # The first row is labels, the rest are the features. # (As a consequence of this, labels are converted to float) LabelAndFeatureMatrix = OutputSlot() ProgressSignal = OutputSlot() # For convenience of passing several progress signals # to a downstream operator (such as OpConcatenateFeatureMatrices), # we provide the progressSignal member as an output slot. MAX_BLOCK_PIXELS = 1e6 def __init__(self, *args, **kwargs): super(OpFeatureMatrixCache, self).__init__(*args, **kwargs) self._lock = RequestLock() self.progressSignal = OrderedSignal() self._progress_lock = RequestLock() self._blockshape = None self._dirty_blocks = set() self._blockwise_feature_matrices = {} self._block_locks = {} # One lock per stored block self._init_blocks(None, None) def _init_blocks(self, input_shape, new_blockshape): old_blockshape = self._blockshape if new_blockshape == old_blockshape: # Nothing to do return if ( len(self._dirty_blocks) != 0 or len(self._blockwise_feature_matrices) != 0): raise RuntimeError("It's too late to change the dimensionality of your data after you've already started training.\n" "Delete all your labels and try again.") # In these set/dict members, the block id (dict key) # is simply the block's start coordinate (as a tuple) self._blockshape = new_blockshape logger.debug("Initialized with blockshape: {}".format(new_blockshape)) def setupOutputs(self): # We assume that channel the last axis assert self.FeatureImage.meta.getAxisKeys()[-1] == 'c' assert self.LabelImage.meta.getAxisKeys()[-1] == 'c' assert self.LabelImage.meta.shape[-1] == 1 # For now, we assume that the two input images have the same shape (except channel) # This constraint could be relaxed in the future if necessary assert self.FeatureImage.meta.shape[:-1] == self.LabelImage.meta.shape[:-1],\ "FeatureImage and LabelImage shapes do not match: {} vs {}"\ "".format( self.FeatureImage.meta.shape, self.LabelImage.meta.shape ) self.LabelAndFeatureMatrix.meta.shape = (1,) self.LabelAndFeatureMatrix.meta.dtype = object self.LabelAndFeatureMatrix.meta.channel_names = self.FeatureImage.meta.channel_names num_feature_channels = self.FeatureImage.meta.shape[-1] if num_feature_channels != self.LabelAndFeatureMatrix.meta.num_feature_channels: self.LabelAndFeatureMatrix.meta.num_feature_channels = num_feature_channels self.LabelAndFeatureMatrix.setDirty() self.ProgressSignal.meta.shape = (1,) self.ProgressSignal.meta.dtype = object self.ProgressSignal.setValue( self.progressSignal ) # Auto-choose a blockshape tagged_shape = self.LabelImage.meta.getTaggedShape() if 't' in tagged_shape: # A block should never span multiple time slices. # For txy volumes, that could lead to lots of extra features being computed. tagged_shape['t'] = 1 blockshape = determineBlockShape( tagged_shape.values(), OpFeatureMatrixCache.MAX_BLOCK_PIXELS ) # Don't span more than 256 px along any axis blockshape = tuple(min(x, 256) for x in blockshape) self._init_blocks(self.LabelImage.meta.shape, blockshape) def execute(self, slot, subindex, roi, result): assert slot == self.LabelAndFeatureMatrix self.progressSignal(0.0) # Technically, this could result in strange progress reporting if execute() # is called by multiple threads in parallel. # This could be fixed with some fancier progress state, but # (1) We don't expect that to by typical, and # (2) progress reporting is merely informational. num_dirty_blocks = len( self._dirty_blocks ) remaining_dirty = [num_dirty_blocks] def update_progress( result ): remaining_dirty[0] -= 1 percent_complete = 95.0*(num_dirty_blocks - remaining_dirty[0])/num_dirty_blocks self.progressSignal( percent_complete ) # Update all dirty blocks in the cache logger.debug( "Updating {} dirty blocks".format(num_dirty_blocks) ) # Before updating the blocks, ensure that the necessary block locks exist # It's better to do this now instead of inside each request # to avoid contention over self._lock with self._lock: for block_start in self._dirty_blocks: if block_start not in self._block_locks: self._block_locks[block_start] = RequestLock() # Update each block in its own request. pool = RequestPool() reqs = {} for block_start in self._dirty_blocks: req = Request( partial(self._get_features_for_block, block_start ) ) req.notify_finished( update_progress ) reqs[block_start] = req pool.add( req ) pool.wait() # Now store the results we got. # It's better to store the blocks here -- rather than within each request -- to # avoid contention over self._lock from within every block's request. with self._lock: for block_start, req in reqs.items(): if req.result is None: # 'None' means the block wasn't dirty. No need to update. continue labels_and_features_matrix = req.result self._dirty_blocks.remove(block_start) if labels_and_features_matrix.shape[0] > 0: # Update the block entry with the new matrix. self._blockwise_feature_matrices[block_start] = labels_and_features_matrix else: # All labels were removed from the block, # So the new feature matrix is empty. # Just delete its entry from our list. try: del self._blockwise_feature_matrices[block_start] except KeyError: pass # Concatenate the all blockwise results if self._blockwise_feature_matrices: total_feature_matrix = numpy.concatenate( self._blockwise_feature_matrices.values(), axis=0 ) else: # No label points at all. # Return an empty label&feature matrix (of the correct shape) num_feature_channels = self.FeatureImage.meta.shape[-1] total_feature_matrix = numpy.ndarray( shape=(0, 1 + num_feature_channels), dtype=numpy.float32 ) self.progressSignal(100.0) logger.debug( "After update, there are {} clean blocks".format( len(self._blockwise_feature_matrices) ) ) result[0] = total_feature_matrix def propagateDirty(self, slot, subindex, roi): if slot == self.NonZeroLabelBlocks: # Label changes will be handled via labelimage dirtyness propagation return assert slot == self.FeatureImage or slot == self.LabelImage # Our blocks are tracked by label roi (1 channel) roi = roi.copy() roi.start[-1] = 0 roi.stop[-1] = 1 # Bookkeeping: Track the dirty blocks block_starts = getIntersectingBlocks( self._blockshape, (roi.start, roi.stop) ) block_starts = map( tuple, block_starts ) # # If the features were dirty (not labels), we only really care about # the blocks that are actually stored already # For big dirty rois (e.g. the entire image), # we avoid a lot of unnecessary entries in self._dirty_blocks if slot == self.FeatureImage: block_starts = set( block_starts ).intersection( self._blockwise_feature_matrices.keys() ) with self._lock: self._dirty_blocks.update( block_starts ) # Output has no notion of roi. It's all dirty. self.LabelAndFeatureMatrix.setDirty() def _get_features_for_block(self, block_start): """ Computes the feature matrix for the given block IFF the block is dirty. Otherwise, returns None. """ # Caller must ensure that the lock for this block already exists! with self._block_locks[block_start]: if block_start not in self._dirty_blocks: # Nothing to do if this block isn't actually dirty # (For parallel requests, its theoretically possible.) return None block_roi = getBlockBounds( self.LabelImage.meta.shape, self._blockshape, block_start ) # TODO: Shrink the requested roi using the nonzero blocks slot... # ...or just get rid of the nonzero blocks slot... labels_and_features_matrix = self._extract_feature_matrix(block_roi) return labels_and_features_matrix def _extract_feature_matrix(self, label_block_roi): num_feature_channels = self.FeatureImage.meta.shape[-1] labels = self.LabelImage(label_block_roi[0], label_block_roi[1]).wait() label_block_positions = numpy.nonzero(labels[...,0].view(numpy.ndarray)) labels_matrix = labels[label_block_positions].astype(numpy.float32).view(numpy.ndarray) if len(label_block_positions) == 0 or len(label_block_positions[0]) == 0: # No label points in this roi. # Return an empty label&feature matrix (of the correct shape) return numpy.ndarray( shape=(0, 1 + num_feature_channels), dtype=numpy.float32 ) # Shrink the roi to the bounding box of nonzero labels block_bounding_box_start = numpy.array( map( numpy.min, label_block_positions ) ) block_bounding_box_stop = 1 + numpy.array( map( numpy.max, label_block_positions ) ) global_bounding_box_start = block_bounding_box_start + label_block_roi[0][:-1] global_bounding_box_stop = block_bounding_box_stop + label_block_roi[0][:-1] # Since we're just requesting the bounding box, offset the feature positions by the box start bounding_box_positions = numpy.transpose( numpy.transpose(label_block_positions) - numpy.array(block_bounding_box_start) ) bounding_box_positions = tuple(bounding_box_positions) # Append channel roi (all feature channels) feature_roi_start = list(global_bounding_box_start) + [0] feature_roi_stop = list(global_bounding_box_stop) + [num_feature_channels] # Request features (bounding box only) features = self.FeatureImage(feature_roi_start, feature_roi_stop).wait() # Cast as plain ndarray (not VigraArray), since we don't need/want axistags features_matrix = features[bounding_box_positions].view(numpy.ndarray) return numpy.concatenate( (labels_matrix, features_matrix), axis=1)
lgpl-3.0
kidburglar/youtube-dl
youtube_dl/extractor/rtp.py
50
3090
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class RTPIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?rtp\.pt/play/p(?P<program_id>[0-9]+)/(?P<id>[^/?#]+)/?' _TESTS = [{ 'url': 'http://www.rtp.pt/play/p405/e174042/paixoes-cruzadas', 'md5': 'e736ce0c665e459ddb818546220b4ef8', 'info_dict': { 'id': 'e174042', 'ext': 'mp3', 'title': 'Paixões Cruzadas', 'description': 'As paixões musicais de António Cartaxo e António Macedo', 'thumbnail': r're:^https?://.*\.jpg', }, 'params': { # rtmp download 'skip_download': True, }, }, { 'url': 'http://www.rtp.pt/play/p831/a-quimica-das-coisas', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) title = self._html_search_meta( 'twitter:title', webpage, display_name='title', fatal=True) description = self._html_search_meta('description', webpage) thumbnail = self._og_search_thumbnail(webpage) player_config = self._search_regex( r'(?s)RTPPLAY\.player\.newPlayer\(\s*(\{.*?\})\s*\)', webpage, 'player config') config = self._parse_json(player_config, video_id) path, ext = config.get('file').rsplit('.', 1) formats = [{ 'format_id': 'rtmp', 'ext': ext, 'vcodec': config.get('type') == 'audio' and 'none' or None, 'preference': -2, 'url': 'rtmp://{streamer:s}/{application:s}'.format(**config), 'app': config.get('application'), 'play_path': '{ext:s}:{path:s}'.format(ext=ext, path=path), 'page_url': url, 'rtmp_live': config.get('live', False), 'player_url': 'http://programas.rtp.pt/play/player.swf?v3', 'rtmp_real_time': True, }] # Construct regular HTTP download URLs replacements = { 'audio': { 'format_id': 'mp3', 'pattern': r'^nas2\.share/wavrss/', 'repl': 'http://rsspod.rtp.pt/podcasts/', 'vcodec': 'none', }, 'video': { 'format_id': 'mp4_h264', 'pattern': r'^nas2\.share/h264/', 'repl': 'http://rsspod.rtp.pt/videocasts/', 'vcodec': 'h264', }, } r = replacements[config['type']] if re.match(r['pattern'], config['file']) is not None: formats.append({ 'format_id': r['format_id'], 'url': re.sub(r['pattern'], r['repl'], config['file']), 'vcodec': r['vcodec'], }) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'formats': formats, 'description': description, 'thumbnail': thumbnail, }
unlicense
reorder/cgminer_keccak_3.6
api-example.py
54
1334
#!/usr/bin/env python2.7 # Copyright 2013 Setkeh Mkfr # # 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. See COPYING for more details. #Short Python Example for connecting to The Cgminer API #Written By: setkeh <https://github.com/setkeh> #Thanks to Jezzz for all his Support. #NOTE: When adding a param with a pipe | in bash or ZSH you must wrap the arg in quotes #E.G "pga|0" import socket import json import sys def linesplit(socket): buffer = socket.recv(4096) done = False while not done: more = socket.recv(4096) if not more: done = True else: buffer = buffer+more if buffer: return buffer api_command = sys.argv[1].split('|') if len(sys.argv) < 3: api_ip = '127.0.0.1' api_port = 4028 else: api_ip = sys.argv[2] api_port = sys.argv[3] s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((api_ip,int(api_port))) if len(api_command) == 2: s.send(json.dumps({"command":api_command[0],"parameter":api_command[1]})) else: s.send(json.dumps({"command":api_command[0]})) response = linesplit(s) response = response.replace('\x00','') response = json.loads(response) print response s.close()
gpl-3.0
hehongliang/tensorflow
tensorflow/python/kernel_tests/sparse_reshape_op_test.py
5
13690
# 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 SparseReshape.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.platform import test class SparseReshapeTest(test.TestCase): def _SparseTensorPlaceholder(self): return sparse_tensor.SparseTensor( array_ops.placeholder(dtypes.int64), array_ops.placeholder(dtypes.float64), array_ops.placeholder(dtypes.int64)) def _SparseTensorValue_5x6(self): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]).astype(np.int64) val = np.array([0, 10, 13, 14, 32, 33]).astype(np.float64) shape = np.array([5, 6]).astype(np.int64) return sparse_tensor.SparseTensorValue(ind, val, shape) def _SparseTensorValue_2x3x4(self): ind = np.array([[0, 0, 1], [0, 1, 0], [0, 1, 2], [1, 0, 3], [1, 1, 1], [1, 1, 3], [1, 2, 2]]) val = np.array([1, 10, 12, 103, 111, 113, 122]) shape = np.array([2, 3, 4]) return sparse_tensor.SparseTensorValue(ind, val, shape) def testStaticShapeInfoPreserved(self): sp_input = sparse_tensor.SparseTensor.from_value( self._SparseTensorValue_5x6()) self.assertAllEqual((5, 6), sp_input.get_shape()) sp_output = sparse_ops.sparse_reshape(sp_input, shape=(1, 5, 2, 3)) self.assertAllEqual((1, 5, 2, 3), sp_output.get_shape()) def testStaticShapeInfoPreservedWithInferredDims(self): sp_input = sparse_tensor.SparseTensor.from_value( self._SparseTensorValue_2x3x4()) self.assertAllEqual((2, 3, 4), sp_input.get_shape()) sp_output = sparse_ops.sparse_reshape(sp_input, shape=(2, -1)) self.assertAllEqual((2, 3 * 4), sp_output.get_shape()) def testRaisesIfMoreThanOneInferredDim(self): sp_input = sparse_tensor.SparseTensor.from_value( self._SparseTensorValue_2x3x4()) with self.assertRaisesRegexp(ValueError, "At most one dimension can"): sparse_ops.sparse_reshape(sp_input, shape=(-1, 2, -1)) def testRaisesIfInferredShapeNotPossible(self): sp_input = sparse_tensor.SparseTensor.from_value( self._SparseTensorValue_2x3x4()) with self.assertRaisesRegexp(ValueError, "Cannot reshape"): sparse_ops.sparse_reshape(sp_input, shape=(-1, 7)) def testSameShape(self): with self.session(use_gpu=False) as sess: input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(input_val, [5, 6]) output_val = sess.run(sp_output) self.assertAllEqual(output_val.indices, input_val.indices) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, input_val.dense_shape) def testFeedSameShape(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [5, 6]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, input_val.indices) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, input_val.dense_shape) def testWorksWellWithTfShape(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() shape = array_ops.shape(sp_input) # tf.shape generates int32 output sp_output = sparse_ops.sparse_reshape(sp_input, shape) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, input_val.indices) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, input_val.dense_shape) def testFeedSameShapeWithInferredDim(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [-1, 6]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, input_val.indices) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, input_val.dense_shape) def testFeedNewShapeSameRank(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [3, 10]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 0], [0, 6], [0, 9], [1, 0], [2, 0], [2, 1]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [3, 10]) def testFeedNewShapeSameRankWithInferredDim(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [3, -1]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 0], [0, 6], [0, 9], [1, 0], [2, 0], [2, 1]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [3, 10]) def testUpRank(self): with self.session(use_gpu=False) as sess: input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(input_val, [2, 3, 5]) output_val = sess.run(sp_output) self.assertAllEqual(output_val.indices, np.array([[0, 0, 0], [0, 1, 1], [0, 1, 4], [0, 2, 0], [1, 1, 0], [1, 1, 1]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [2, 3, 5]) def testFeedUpRank(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [2, 3, 5]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 0, 0], [0, 1, 1], [0, 1, 4], [0, 2, 0], [1, 1, 0], [1, 1, 1]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [2, 3, 5]) def testFeedUpRankWithInferredDim(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [2, -1, 5]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 0, 0], [0, 1, 1], [0, 1, 4], [0, 2, 0], [1, 1, 0], [1, 1, 1]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [2, 3, 5]) def testFeedDownRank(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_2x3x4() sp_output = sparse_ops.sparse_reshape(sp_input, [6, 4]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 1], [1, 0], [1, 2], [3, 3], [4, 1], [4, 3], [5, 2]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [6, 4]) def testFeedDownRankWithInferredDim(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_2x3x4() sp_output = sparse_ops.sparse_reshape(sp_input, [6, -1]) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, np.array([[0, 1], [1, 0], [1, 2], [3, 3], [4, 1], [4, 3], [5, 2]])) self.assertAllEqual(output_val.values, input_val.values) self.assertAllEqual(output_val.dense_shape, [6, 4]) def testFeedMultipleInferredDims(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [4, -1, -1]) with self.assertRaisesOpError("only one output dimension may be -1"): sess.run(sp_output, {sp_input: input_val}) def testProvideStaticallyMismatchedSizes(self): input_val = self._SparseTensorValue_5x6() sp_input = sparse_tensor.SparseTensor.from_value(input_val) with self.assertRaisesRegexp(ValueError, "Cannot reshape"): sparse_ops.sparse_reshape(sp_input, [4, 7]) def testFeedMismatchedSizes(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [4, 7]) with self.assertRaisesOpError( "Input to reshape is a tensor with 30 dense values"): sess.run(sp_output, {sp_input: input_val}) def testFeedMismatchedSizesWithInferredDim(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input_val = self._SparseTensorValue_5x6() sp_output = sparse_ops.sparse_reshape(sp_input, [4, -1]) with self.assertRaisesOpError("requested shape requires a multiple"): sess.run(sp_output, {sp_input: input_val}) def testFeedPartialShapes(self): with self.session(use_gpu=False): # Incorporate new rank into shape information if known sp_input = self._SparseTensorPlaceholder() sp_output = sparse_ops.sparse_reshape(sp_input, [2, 3, 5]) self.assertListEqual(sp_output.indices.get_shape().as_list(), [None, 3]) self.assertListEqual(sp_output.dense_shape.get_shape().as_list(), [3]) # Incorporate known shape information about input indices in output # indices sp_input = self._SparseTensorPlaceholder() sp_input.indices.set_shape([5, None]) sp_output = sparse_ops.sparse_reshape(sp_input, [2, 3, 5]) self.assertListEqual(sp_output.indices.get_shape().as_list(), [5, 3]) self.assertListEqual(sp_output.dense_shape.get_shape().as_list(), [3]) # Even if new_shape has no shape information, we know the ranks of # output indices and shape sp_input = self._SparseTensorPlaceholder() sp_input.indices.set_shape([5, None]) new_shape = array_ops.placeholder(dtypes.int64) sp_output = sparse_ops.sparse_reshape(sp_input, new_shape) self.assertListEqual(sp_output.indices.get_shape().as_list(), [5, None]) self.assertListEqual(sp_output.dense_shape.get_shape().as_list(), [None]) def testFeedDenseReshapeSemantics(self): with self.session(use_gpu=False) as sess: # Compute a random rank-5 initial shape and new shape, randomly sparsify # it, and check that the output of SparseReshape has the same semantics # as a dense reshape. factors = np.array([2] * 4 + [3] * 4 + [5] * 4) # 810k total elements orig_rank = np.random.randint(2, 7) orig_map = np.random.randint(orig_rank, size=factors.shape) orig_shape = [np.prod(factors[orig_map == d]) for d in range(orig_rank)] new_rank = np.random.randint(2, 7) new_map = np.random.randint(new_rank, size=factors.shape) new_shape = [np.prod(factors[new_map == d]) for d in range(new_rank)] orig_dense = np.random.uniform(size=orig_shape) orig_indices = np.transpose(np.nonzero(orig_dense < 0.5)) orig_values = orig_dense[orig_dense < 0.5] new_dense = np.reshape(orig_dense, new_shape) new_indices = np.transpose(np.nonzero(new_dense < 0.5)) new_values = new_dense[new_dense < 0.5] sp_input = self._SparseTensorPlaceholder() input_val = sparse_tensor.SparseTensorValue(orig_indices, orig_values, orig_shape) sp_output = sparse_ops.sparse_reshape(sp_input, new_shape) output_val = sess.run(sp_output, {sp_input: input_val}) self.assertAllEqual(output_val.indices, new_indices) self.assertAllEqual(output_val.values, new_values) self.assertAllEqual(output_val.dense_shape, new_shape) if __name__ == "__main__": test.main()
apache-2.0
dxmahata/InformativeTweetCollection
requests_oauthlib/oauth1_session.py
6
16132
from __future__ import unicode_literals try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import logging from oauthlib.common import add_params_to_uri from oauthlib.common import urldecode as _urldecode from oauthlib.oauth1 import ( SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_TYPE_AUTH_HEADER ) import requests from . import OAuth1 import sys if sys.version > "3": unicode = str log = logging.getLogger(__name__) def urldecode(body): """Parse query or json to python dictionary""" try: return _urldecode(body) except: import json return json.loads(body) class TokenRequestDenied(ValueError): def __init__(self, message, status_code): super(TokenRequestDenied, self).__init__(message) self.status_code = status_code class TokenMissing(ValueError): def __init__(self, message, response): super(TokenMissing, self).__init__(message) self.response = response class VerifierMissing(ValueError): pass class OAuth1Session(requests.Session): """Request signing and convenience methods for the oauth dance. What is the difference between OAuth1Session and OAuth1? OAuth1Session actually uses OAuth1 internally and it's purpose is to assist in the OAuth workflow through convenience methods to prepare authorization URLs and parse the various token and redirection responses. It also provide rudimentary validation of responses. An example of the OAuth workflow using a basic CLI app and Twitter. >>> # Credentials obtained during the registration. >>> client_key = 'client key' >>> client_secret = 'secret' >>> callback_uri = 'https://127.0.0.1/callback' >>> >>> # Endpoints found in the OAuth provider API documentation >>> request_token_url = 'https://api.twitter.com/oauth/request_token' >>> authorization_url = 'https://api.twitter.com/oauth/authorize' >>> access_token_url = 'https://api.twitter.com/oauth/access_token' >>> >>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri) >>> >>> # First step, fetch the request token. >>> oauth_session.fetch_request_token(request_token_url) { 'oauth_token': 'kjerht2309u', 'oauth_token_secret': 'lsdajfh923874', } >>> >>> # Second step. Follow this link and authorize >>> oauth_session.authorization_url(authorization_url) 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback' >>> >>> # Third step. Fetch the access token >>> redirect_response = raw_input('Paste the full redirect URL here.') >>> oauth_session.parse_authorization_response(redirect_response) { 'oauth_token: 'kjerht2309u', 'oauth_token_secret: 'lsdajfh923874', 'oauth_verifier: 'w34o8967345', } >>> oauth_session.fetch_access_token(access_token_url) { 'oauth_token': 'sdf0o9823sjdfsdf', 'oauth_token_secret': '2kjshdfp92i34asdasd', } >>> # Done. You can now make OAuth requests. >>> status_url = 'http://api.twitter.com/1/statuses/update.json' >>> new_status = {'status': 'hello world!'} >>> oauth_session.post(status_url, data=new_status) <Response [200]> """ def __init__(self, client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method=SIGNATURE_HMAC, signature_type=SIGNATURE_TYPE_AUTH_HEADER, rsa_key=None, verifier=None, client_class=None, force_include_body=False, **kwargs): """Construct the OAuth 1 session. :param client_key: A client specific identifier. :param client_secret: A client specific secret used to create HMAC and plaintext signatures. :param resource_owner_key: A resource owner key, also referred to as request token or access token depending on when in the workflow it is used. :param resource_owner_secret: A resource owner secret obtained with either a request or access token. Often referred to as token secret. :param callback_uri: The URL the user is redirect back to after authorization. :param signature_method: Signature methods determine how the OAuth signature is created. The three options are oauthlib.oauth1.SIGNATURE_HMAC (default), oauthlib.oauth1.SIGNATURE_RSA and oauthlib.oauth1.SIGNATURE_PLAIN. :param signature_type: Signature type decides where the OAuth parameters are added. Either in the Authorization header (default) or to the URL query parameters or the request body. Defined as oauthlib.oauth1.SIGNATURE_TYPE_AUTH_HEADER, oauthlib.oauth1.SIGNATURE_TYPE_QUERY and oauthlib.oauth1.SIGNATURE_TYPE_BODY respectively. :param rsa_key: The private RSA key as a string. Can only be used with signature_method=oauthlib.oauth1.SIGNATURE_RSA. :param verifier: A verifier string to prove authorization was granted. :param client_class: A subclass of `oauthlib.oauth1.Client` to use with `requests_oauthlib.OAuth1` instead of the default :param force_include_body: Always include the request body in the signature creation. :param **kwargs: Additional keyword arguments passed to `OAuth1` """ super(OAuth1Session, self).__init__() self._client = OAuth1(client_key, client_secret=client_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, callback_uri=callback_uri, signature_method=signature_method, signature_type=signature_type, rsa_key=rsa_key, verifier=verifier, client_class=client_class, force_include_body=force_include_body, **kwargs) self.auth = self._client @property def authorized(self): """Boolean that indicates whether this session has an OAuth token or not. If `self.authorized` is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If `self.authorized` is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed. """ if self._client.client.signature_method == SIGNATURE_RSA: # RSA only uses resource_owner_key return bool(self._client.client.resource_owner_key) else: # other methods of authentication use all three pieces return ( bool(self._client.client.client_secret) and bool(self._client.client.resource_owner_key) and bool(self._client.client.resource_owner_secret) ) def authorization_url(self, url, request_token=None, **kwargs): """Create an authorization URL by appending request_token and optional kwargs to url. This is the second step in the OAuth 1 workflow. The user should be redirected to this authorization URL, grant access to you, and then be redirected back to you. The redirection back can either be specified during client registration or by supplying a callback URI per request. :param url: The authorization endpoint URL. :param request_token: The previously obtained request token. :param kwargs: Optional parameters to append to the URL. :returns: The authorization URL with new parameters embedded. An example using a registered default callback URI. >>> request_token_url = 'https://api.twitter.com/oauth/request_token' >>> authorization_url = 'https://api.twitter.com/oauth/authorize' >>> oauth_session = OAuth1Session('client-key', client_secret='secret') >>> oauth_session.fetch_request_token(request_token_url) { 'oauth_token': 'sdf0o9823sjdfsdf', 'oauth_token_secret': '2kjshdfp92i34asdasd', } >>> oauth_session.authorization_url(authorization_url) 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf' >>> oauth_session.authorization_url(authorization_url, foo='bar') 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar' An example using an explicit callback URI. >>> request_token_url = 'https://api.twitter.com/oauth/request_token' >>> authorization_url = 'https://api.twitter.com/oauth/authorize' >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback') >>> oauth_session.fetch_request_token(request_token_url) { 'oauth_token': 'sdf0o9823sjdfsdf', 'oauth_token_secret': '2kjshdfp92i34asdasd', } >>> oauth_session.authorization_url(authorization_url) 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback' """ kwargs['oauth_token'] = request_token or self._client.client.resource_owner_key log.debug('Adding parameters %s to url %s', kwargs, url) return add_params_to_uri(url, kwargs.items()) def fetch_request_token(self, url, realm=None): """Fetch a request token. This is the first step in the OAuth 1 workflow. A request token is obtained by making a signed post request to url. The token is then parsed from the application/x-www-form-urlencoded response and ready to be used to construct an authorization url. :param url: The request token endpoint URL. :param realm: A list of realms to request access to. :returns: The response in dict format. Note that a previously set callback_uri will be reset for your convenience, or else signature creation will be incorrect on consecutive requests. >>> request_token_url = 'https://api.twitter.com/oauth/request_token' >>> oauth_session = OAuth1Session('client-key', client_secret='secret') >>> oauth_session.fetch_request_token(request_token_url) { 'oauth_token': 'sdf0o9823sjdfsdf', 'oauth_token_secret': '2kjshdfp92i34asdasd', } """ self._client.client.realm = ' '.join(realm) if realm else None token = self._fetch_token(url) log.debug('Resetting callback_uri and realm (not needed in next phase).') self._client.client.callback_uri = None self._client.client.realm = None return token def fetch_access_token(self, url, verifier=None): """Fetch an access token. This is the final step in the OAuth 1 workflow. An access token is obtained using all previously obtained credentials, including the verifier from the authorization step. Note that a previously set verifier will be reset for your convenience, or else signature creation will be incorrect on consecutive requests. >>> access_token_url = 'https://api.twitter.com/oauth/access_token' >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345' >>> oauth_session = OAuth1Session('client-key', client_secret='secret') >>> oauth_session.parse_authorization_response(redirect_response) { 'oauth_token: 'kjerht2309u', 'oauth_token_secret: 'lsdajfh923874', 'oauth_verifier: 'w34o8967345', } >>> oauth_session.fetch_access_token(access_token_url) { 'oauth_token': 'sdf0o9823sjdfsdf', 'oauth_token_secret': '2kjshdfp92i34asdasd', } """ if verifier: self._client.client.verifier = verifier if not getattr(self._client.client, 'verifier', None): raise VerifierMissing('No client verifier has been set.') token = self._fetch_token(url) log.debug('Resetting verifier attribute, should not be used anymore.') self._client.client.verifier = None return token def parse_authorization_response(self, url): """Extract parameters from the post authorization redirect response URL. :param url: The full URL that resulted from the user being redirected back from the OAuth provider to you, the client. :returns: A dict of parameters extracted from the URL. >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345' >>> oauth_session = OAuth1Session('client-key', client_secret='secret') >>> oauth_session.parse_authorization_response(redirect_response) { 'oauth_token: 'kjerht2309u', 'oauth_token_secret: 'lsdajfh923874', 'oauth_verifier: 'w34o8967345', } """ log.debug('Parsing token from query part of url %s', url) token = dict(urldecode(urlparse(url).query)) log.debug('Updating internal client token attribute.') self._populate_attributes(token) return token def _populate_attributes(self, token): if 'oauth_token' in token: self._client.client.resource_owner_key = token['oauth_token'] else: raise TokenMissing( 'Response does not contain a token: {resp}'.format(resp=token), token, ) if 'oauth_token_secret' in token: self._client.client.resource_owner_secret = ( token['oauth_token_secret']) if 'oauth_verifier' in token: self._client.client.verifier = token['oauth_verifier'] def _fetch_token(self, url): log.debug('Fetching token from %s using client %s', url, self._client.client) r = self.post(url) if r.status_code >= 400: error = "Token request failed with code %s, response was '%s'." raise TokenRequestDenied(error % (r.status_code, r.text), r.status_code) log.debug('Decoding token from response "%s"', r.text) try: token = dict(urldecode(r.text)) except ValueError as e: error = ("Unable to decode token from token response. " "This is commonly caused by an unsuccessful request where" " a non urlencoded error message is returned. " "The decoding error was %s""" % e) raise ValueError(error) log.debug('Obtained token %s', token) log.debug('Updating internal client attributes from token data.') self._populate_attributes(token) return token def rebuild_auth(self, prepared_request, response): """ When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec. """ if 'Authorization' in prepared_request.headers: # If we get redirected to a new host, we should strip out # any authentication headers. prepared_request.headers.pop('Authorization', True) prepared_request.prepare_auth(self.auth) return
apache-2.0
onitake/ansible
lib/ansible/modules/network/junos/junos_interface.py
22
12307
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # 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': 'network'} DOCUMENTATION = """ --- module: junos_interface version_added: "2.4" author: "Ganesh Nalawade (@ganeshrn)" short_description: Manage Interface on Juniper JUNOS network devices description: - This module provides declarative management of Interfaces on Juniper JUNOS network devices. options: name: description: - Name of the Interface. required: true description: description: - Description of Interface. enabled: description: - Configure interface link status. speed: description: - Interface link speed. mtu: description: - Maximum size of transmit packet. duplex: description: - Interface link status. default: auto choices: ['full', 'half', 'auto'] tx_rate: description: - Transmit rate in bits per second (bps). - This is state check parameter only. - Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html) rx_rate: description: - Receiver rate in bits per second (bps). - This is state check parameter only. - Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html) neighbors: description: - Check the operational state of given interface C(name) for LLDP neighbor. - The following suboptions are available. suboptions: host: description: - "LLDP neighbor host for given interface C(name)." port: description: - "LLDP neighbor port to which given interface C(name) is connected." delay: description: - Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state argument which are I(state) with values C(up)/C(down), I(tx_rate) and I(rx_rate). default: 10 aggregate: description: List of Interfaces definitions. state: description: - State of the Interface configuration, C(up) idicates present and operationally up and C(down) indicates present and operationally C(down) default: present choices: ['present', 'absent', 'up', 'down'] active: description: - Specifies whether or not the configuration is active or deactivated default: True type: bool requirements: - ncclient (>=v0.5.2) notes: - This module requires the netconf system service be enabled on the remote device being managed. - Tested against vSRX JUNOS version 15.1X49-D15.4, vqfx-10000 JUNOS Version 15.1X53-D60.4. - Recommended connection is C(netconf). See L(the Junos OS Platform Options,../network/user_guide/platform_junos.html). - This module also works with C(local) connections for legacy playbooks. extends_documentation_fragment: junos """ EXAMPLES = """ - name: configure interface junos_interface: name: ge-0/0/1 description: test-interface - name: remove interface junos_interface: name: ge-0/0/1 state: absent - name: make interface down junos_interface: name: ge-0/0/1 enabled: False - name: make interface up junos_interface: name: ge-0/0/1 enabled: True - name: Deactivate interface config junos_interface: name: ge-0/0/1 state: present active: False - name: Activate interface config net_interface: name: ge-0/0/1 state: present active: True - name: Configure interface speed, mtu, duplex junos_interface: name: ge-0/0/1 state: present speed: 1g mtu: 256 duplex: full - name: Create interface using aggregate junos_interface: aggregate: - name: ge-0/0/1 description: test-interface-1 - name: ge-0/0/2 description: test-interface-2 speed: 1g duplex: full mtu: 512 - name: Delete interface using aggregate junos_interface: aggregate: - name: ge-0/0/1 - name: ge-0/0/2 state: absent - name: Check intent arguments junos_interface: name: "{{ name }}" state: up tx_rate: ge(0) rx_rate: le(0) - name: Check neighbor intent junos_interface: name: xe-0/1/1 neighbors: - port: Ethernet1/0/1 host: netdev - name: Config + intent junos_interface: name: "{{ name }}" enabled: False state: down """ RETURN = """ diff.prepared: description: Configuration difference before and after applying change. returned: when configuration is changed and diff option is enabled. type: string sample: > [edit interfaces] + ge-0/0/1 { + description test-interface; + } """ import collections from copy import deepcopy from time import sleep from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.netconf import exec_rpc from ansible.module_utils.network.common.utils import remove_default_spec from ansible.module_utils.network.common.utils import conditional from ansible.module_utils.network.junos.junos import junos_argument_spec, tostring from ansible.module_utils.network.junos.junos import load_config, map_params_to_obj, map_obj_to_ele from ansible.module_utils.network.junos.junos import commit_configuration, discard_changes, locked_config, to_param_list try: from lxml.etree import Element, SubElement except ImportError: from xml.etree.ElementTree import Element, SubElement USE_PERSISTENT_CONNECTION = True def validate_mtu(value, module): if value and not 256 <= value <= 9192: module.fail_json(msg='mtu must be between 256 and 9192') def validate_param_values(module, obj, param=None): if not param: param = module.params for key in obj: # validate the param value (if validator func exists) validator = globals().get('validate_%s' % key) if callable(validator): validator(param.get(key), module) def main(): """ main entry point for module execution """ neighbors_spec = dict( host=dict(), port=dict() ) element_spec = dict( name=dict(), description=dict(), enabled=dict(default=True, type='bool'), speed=dict(), mtu=dict(type='int'), duplex=dict(choices=['full', 'half', 'auto']), tx_rate=dict(), rx_rate=dict(), neighbors=dict(type='list', elements='dict', options=neighbors_spec), delay=dict(default=10, type='int'), state=dict(default='present', choices=['present', 'absent', 'up', 'down']), active=dict(default=True, type='bool') ) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'interfaces/interface' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('name', {'xpath': 'name', 'is_key': True}), ('description', 'description'), ('speed', 'speed'), ('mtu', 'mtu'), ('duplex', 'link-mode'), ('disable', {'xpath': 'disable', 'tag_only': True}) ]) choice_to_value_map = { 'link-mode': {'full': 'full-duplex', 'half': 'half-duplex', 'auto': 'automatic'} } params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() state = item.get('state') item['disable'] = True if not item.get('enabled') else False if state in ('present', 'up', 'down'): item['state'] = 'present' validate_param_values(module, param_to_xpath_map, param=item) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, value_map=choice_to_value_map, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') # issue commit after last configuration change is done commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} failed_conditions = [] neighbors = None for item in params: state = item.get('state') tx_rate = item.get('tx_rate') rx_rate = item.get('rx_rate') want_neighbors = item.get('neighbors') if state not in ('up', 'down') and tx_rate is None and rx_rate is None and want_neighbors is None: continue element = Element('get-interface-information') intf_name = SubElement(element, 'interface-name') intf_name.text = item.get('name') if result['changed']: sleep(item.get('delay')) reply = exec_rpc(module, tostring(element), ignore_warning=False) if state in ('up', 'down'): admin_status = reply.xpath('interface-information/physical-interface/admin-status') if not admin_status or not conditional(state, admin_status[0].text.strip()): failed_conditions.append('state ' + 'eq(%s)' % state) if tx_rate: output_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/output-bps') if not output_bps or not conditional(tx_rate, output_bps[0].text.strip(), cast=int): failed_conditions.append('tx_rate ' + tx_rate) if rx_rate: input_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/input-bps') if not input_bps or not conditional(rx_rate, input_bps[0].text.strip(), cast=int): failed_conditions.append('rx_rate ' + rx_rate) if want_neighbors: if neighbors is None: element = Element('get-lldp-interface-neighbors') intf_name = SubElement(element, 'interface-device') intf_name.text = item.get('name') reply = exec_rpc(module, tostring(element), ignore_warning=False) have_host = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-system-name')] have_port = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-port-id')] for neighbor in want_neighbors: host = neighbor.get('host') port = neighbor.get('port') if host and host not in have_host: failed_conditions.append('host ' + host) if port and port not in have_port: failed_conditions.append('port ' + port) if failed_conditions: msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) module.exit_json(**result) if __name__ == "__main__": main()
gpl-3.0
Serag8/Bachelor
google_appengine/lib/django-1.2/django/contrib/admindocs/utils.py
314
3796
"Misc. utility functions/classes for admin documentation generator." import re from email.Parser import HeaderParser from email.Errors import HeaderParseError from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from django.utils.encoding import smart_str try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def trim_docstring(docstring): """ Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lines = docstring.expandtabs().splitlines() indent = min([len(line) - len(line.lstrip()) for line in lines if line.lstrip()]) trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] return "\n".join(trimmed).strip() def parse_docstring(docstring): """ Parse out the parts of a docstring. Returns (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None): """ Convert the string from reST to an XHTML fragment. """ overrides = { 'doctitle_xform' : True, 'inital_header_level' : 3, "default_reference_context" : default_reference_context, "link_base" : reverse('django-admindocs-docroot').rstrip('/') } if thing_being_parsed: thing_being_parsed = smart_str("<%s>" % thing_being_parsed) parts = docutils.core.publish_parts(text, source_path=thing_being_parsed, destination_path=None, writer_name='html', settings_overrides=overrides) return mark_safe(parts['fragment']) # # reST roles # ROLES = { 'model' : '%s/models/%s/', 'view' : '%s/views/%s/', 'template' : '%s/templates/%s/', 'filter' : '%s/filters/#%s', 'tag' : '%s/tags/#%s', } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] node = docutils.nodes.reference(rawtext, text, refuri=(urlbase % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] context = inliner.document.settings.default_reference_context node = docutils.nodes.reference(rawtext, text, refuri=(ROLES[context] % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE = 'cmsreference' for name, urlbase in ROLES.items(): create_reference_role(name, urlbase)
mit
hoaibang07/Webscrap
transcripture/sources/crawler_data.py
1
2804
# -*- encoding: utf-8 -*- import io from bs4 import BeautifulSoup from bs4 import SoupStrainer import urllib2 import urlparse def _remove_div_vdx(soup): for div in soup.find_all('div', class_='vidx'): div.extract() return soup def get_data(urlchuong_list, i): filename = 'urlsach/data/sach' + str(i) + '.txt' ftmp = io.open(filename, 'w', encoding='utf-8') try: hdrs = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Connection': 'keep-alive', 'Cookie': 'ipq_lip=20376774; ipq_set=1453874029; __atuvc=2%7C4; __utma=126044488.676620502.1453787537.1453787537.1453787537.1; __utmz=126044488.1453787537.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=ed3f4874b92a29b6ed036adfa5ad6fb3; ipcountry=us', 'Host': 'www.transcripture.com', 'Referer': 'http://www.transcripture.com/vietnamese-spanish-genesis-1.html', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:43.0) Gecko/20100101 Firefox/43.0' } for urlchuong in urlchuong_list: # urlchuong = 'http://www.transcripture.com/vietnamese-chinese-revelation-3.html' print urlchuong # create request req = urllib2.Request(urlchuong, headers=hdrs) # get response response = urllib2.urlopen(req) soup = BeautifulSoup(response.read()) soup = _remove_div_vdx(soup) # print soup table_tag = soup.find_all('table', attrs={'width':'100%', 'cellspacing':'0'})[0] tr_tags = table_tag.find_all('tr') _len = len(tr_tags) # in first tr tag: h2_class = tr_tags[0].find_all('h2', class_='cphd') ftmp.write(u'' + h2_class[0].get_text() + '|') ftmp.write(u'' + h2_class[1].get_text() + '\n') # print table_tag for x in xrange(1,_len): data = tr_tags[x].get_text('|') # print data # url_ec = url.encode('unicode','utf-8') ftmp.write(u'' + data + '\n') except Exception, e: print e # close file ftmp.close() def main(): for x in xrange(1,67): print('Dang get data sach %d'%x) urlchuong_list = [] filename = 'urlsach/sach' + str(x) + '.txt' urlchuong_file = open(filename, 'r') for line in urlchuong_file: # print(line) urlchuong_list.append(line.rstrip()) get_data(urlchuong_list, x) urlchuong_file.close() if __name__ == '__main__': main() # urlchuong_list = ['http://www.transcripture.com/vietnamese-chinese-revelation-3.html'] # get_data(urlchuong_list, 1)
gpl-2.0
bealdav/OCB
addons/document/test_cindex.py
444
1553
#!/usr/bin/python import sys import os import glob import time import logging from optparse import OptionParser logging.basicConfig(level=logging.DEBUG) parser = OptionParser() parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-C", "--content", action="store_true", dest="docontent", default=False, help="Disect content, rather than the file.") parser.add_option("--delay", action="store_true", dest="delay", default=False, help="delay after the operation, to inspect child processes") (options, args) = parser.parse_args() import content_index, std_index from content_index import cntIndex for fname in args: try: if options.docontent: fp = open(fname,'rb') content = fp.read() fp.close() res = cntIndex.doIndex(content, fname, None, None, True) else: res = cntIndex.doIndex(None, fname, None, fname,True) if options.verbose: for line in res[:5]: print line if options.delay: time.sleep(30) except Exception,e: import traceback tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)) except KeyboardInterrupt: print "Keyboard interrupt" #eof # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
stephanehenry27/Sickbeard-anime
lib/hachoir_parser/misc/bplist.py
90
11349
""" Apple/NeXT Binary Property List (BPLIST) parser. Also includes a .createXML() function which produces an XML representation of the object. Note that it will discard unknown objects, nulls and fill values, but should work for most files. Documents: - CFBinaryPList.c http://src.gnu-darwin.org/DarwinSourceArchive/expanded/CF/CF-299/Parsing.subproj/CFBinaryPList.c - ForFoundationOnly.h (for structure formats) http://src.gnu-darwin.org/DarwinSourceArchive/expanded/CF/CF-299/Base.subproj/ForFoundationOnly.h - XML <-> BPList converter http://scw.us/iPhone/plutil/plutil.pl Author: Robert Xiao Created: 2008-09-21 """ from lib.hachoir_parser import HachoirParser from lib.hachoir_core.field import (RootSeekableFieldSet, FieldSet, Enum, Bits, GenericInteger, Float32, Float64, UInt8, UInt64, Bytes, NullBytes, RawBytes, String) from lib.hachoir_core.endian import BIG_ENDIAN from lib.hachoir_core.text_handler import displayHandler from lib.hachoir_core.tools import humanDatetime from datetime import datetime, timedelta class BPListTrailer(FieldSet): def createFields(self): yield NullBytes(self, "unused", 6) yield UInt8(self, "offsetIntSize", "Size (in bytes) of offsets in the offset table") yield UInt8(self, "objectRefSize", "Size (in bytes) of object numbers in object references") yield UInt64(self, "numObjects", "Number of objects in this file") yield UInt64(self, "topObject", "Top-level object reference") yield UInt64(self, "offsetTableOffset", "File offset to the offset table") def createDescription(self): return "Binary PList trailer" class BPListOffsetTable(FieldSet): def createFields(self): size = self["../trailer/offsetIntSize"].value*8 for i in range(self["../trailer/numObjects"].value): yield Bits(self, "offset[]", size) class BPListSize(FieldSet): def createFields(self): yield Bits(self, "size", 4) if self['size'].value == 0xF: yield BPListObject(self, "fullsize") def createValue(self): if 'fullsize' in self: return self['fullsize'].value else: return self['size'].value class BPListObjectRef(GenericInteger): def __init__(self, parent, name, description=None): size = parent['/trailer/objectRefSize'].value*8 GenericInteger.__init__(self, parent, name, False, size, description) def getRef(self): return self.parent['/object[' + str(self.value) + ']'] def createDisplay(self): return self.getRef().display def createXML(self, prefix=''): return self.getRef().createXML(prefix) class BPListArray(FieldSet): def __init__(self, parent, name, size, description=None): FieldSet.__init__(self, parent, name, description=description) self.numels = size def createFields(self): for i in range(self.numels): yield BPListObjectRef(self, "ref[]") def createValue(self): return self.array('ref') def createDisplay(self): return '[' + ', '.join([x.display for x in self.value]) + ']' def createXML(self,prefix=''): return prefix + '<array>\n' + ''.join([x.createXML(prefix + '\t' ) + '\n' for x in self.value]) + prefix + '</array>' class BPListDict(FieldSet): def __init__(self, parent, name, size, description=None): FieldSet.__init__(self, parent, name, description=description) self.numels = size def createFields(self): for i in range(self.numels): yield BPListObjectRef(self, "keyref[]") for i in range(self.numels): yield BPListObjectRef(self, "valref[]") def createValue(self): return zip(self.array('keyref'),self.array('valref')) def createDisplay(self): return '{' + ', '.join(['%s: %s'%(k.display,v.display) for k,v in self.value]) + '}' def createXML(self, prefix=''): return prefix + '<dict>\n' + ''.join(['%s\t<key>%s</key>\n%s\n'%(prefix,k.getRef().value.encode('utf-8'),v.createXML(prefix + '\t')) for k,v in self.value]) + prefix + '</dict>' class BPListObject(FieldSet): def createFields(self): yield Enum(Bits(self, "marker_type", 4), {0: "Simple", 1: "Int", 2: "Real", 3: "Date", 4: "Data", 5: "ASCII String", 6: "UTF-16-BE String", 8: "UID", 10: "Array", 13: "Dict",}) markertype = self['marker_type'].value if markertype == 0: # Simple (Null) yield Enum(Bits(self, "value", 4), {0: "Null", 8: "False", 9: "True", 15: "Fill Byte",}) if self['value'].display == "False": self.xml=lambda prefix:prefix + "<false/>" elif self['value'].display == "True": self.xml=lambda prefix:prefix + "<true/>" else: self.xml=lambda prefix:prefix + "" elif markertype == 1: # Int yield Bits(self, "size", 4, "log2 of number of bytes") size=self['size'].value # 8-bit (size=0), 16-bit (size=1) and 32-bit (size=2) numbers are unsigned # 64-bit (size=3) numbers are signed yield GenericInteger(self, "value", (size>=3), (2**size)*8) self.xml=lambda prefix:prefix + "<integer>%s</integer>"%self['value'].value elif markertype == 2: # Real yield Bits(self, "size", 4, "log2 of number of bytes") if self['size'].value == 2: # 2**2 = 4 byte float yield Float32(self, "value") elif self['size'].value == 3: # 2**3 = 8 byte float yield Float64(self, "value") else: # FIXME: What is the format of the real? yield Bits(self, "value", (2**self['size'].value)*8) self.xml=lambda prefix:prefix + "<real>%s</real>"%self['value'].value elif markertype == 3: # Date yield Bits(self, "extra", 4, "Extra value, should be 3") cvt_time=lambda v:datetime(2001,1,1) + timedelta(seconds=v) yield displayHandler(Float64(self, "value"),lambda x:humanDatetime(cvt_time(x))) self.xml=lambda prefix:prefix + "<date>%s</date>"%(cvt_time(self['value'].value).isoformat()) elif markertype == 4: # Data yield BPListSize(self, "size") if self['size'].value: yield Bytes(self, "value", self['size'].value) self.xml=lambda prefix:prefix + "<data>\n%s\n%s</data>"%(self['value'].value.encode('base64').strip(),prefix) else: self.xml=lambda prefix:prefix + '<data></data>' elif markertype == 5: # ASCII String yield BPListSize(self, "size") if self['size'].value: yield String(self, "value", self['size'].value, charset="ASCII") self.xml=lambda prefix:prefix + "<string>%s</string>"%(self['value'].value.encode('iso-8859-1')) else: self.xml=lambda prefix:prefix + '<string></string>' elif markertype == 6: # UTF-16-BE String yield BPListSize(self, "size") if self['size'].value: yield String(self, "value", self['size'].value*2, charset="UTF-16-BE") self.xml=lambda prefix:prefix + "<string>%s</string>"%(self['value'].value.encode('utf-8')) else: self.xml=lambda prefix:prefix + '<string></string>' elif markertype == 8: # UID yield Bits(self, "size", 4, "Number of bytes minus 1") yield GenericInteger(self, "value", False, (self['size'].value + 1)*8) self.xml=lambda prefix:prefix + "" # no equivalent? elif markertype == 10: # Array yield BPListSize(self, "size") size = self['size'].value if size: yield BPListArray(self, "value", size) self.xml=lambda prefix:self['value'].createXML(prefix) elif markertype == 13: # Dict yield BPListSize(self, "size") yield BPListDict(self, "value", self['size'].value) self.xml=lambda prefix:self['value'].createXML(prefix) else: yield Bits(self, "value", 4) self.xml=lambda prefix:'' def createValue(self): if 'value' in self: return self['value'].value elif self['marker_type'].value in [4,5,6]: return u'' else: return None def createDisplay(self): if 'value' in self: return unicode(self['value'].display) elif self['marker_type'].value in [4,5,6]: return u'' else: return None def createXML(self, prefix=''): if 'value' in self: try: return self.xml(prefix) except AttributeError: return '' return '' def getFieldType(self): return '%s<%s>'%(FieldSet.getFieldType(self), self['marker_type'].display) class BPList(HachoirParser, RootSeekableFieldSet): endian = BIG_ENDIAN MAGIC = "bplist00" PARSER_TAGS = { "id": "bplist", "category": "misc", "file_ext": ("plist",), "magic": ((MAGIC, 0),), "min_size": 8 + 32, # bplist00 + 32-byte trailer "description": "Apple/NeXT Binary Property List", } def __init__(self, stream, **args): RootSeekableFieldSet.__init__(self, None, "root", stream, None, stream.askSize(self)) HachoirParser.__init__(self, stream, **args) def validate(self): if self.stream.readBytes(0, len(self.MAGIC)) != self.MAGIC: return "Invalid magic" return True def createFields(self): yield Bytes(self, "magic", 8, "File magic (bplist00)") if self.size: self.seekByte(self.size//8-32, True) else: # FIXME: UNTESTED while True: try: self.seekByte(1024) except: break self.seekByte(self.size//8-32) yield BPListTrailer(self, "trailer") self.seekByte(self['trailer/offsetTableOffset'].value) yield BPListOffsetTable(self, "offset_table") for i in self.array("offset_table/offset"): if self.current_size > i.value*8: self.seekByte(i.value) elif self.current_size < i.value*8: # try to detect files with gaps or unparsed content yield RawBytes(self, "padding[]", i.value-self.current_size//8) yield BPListObject(self, "object[]") def createXML(self, prefix=''): return '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> ''' + self['/object[' + str(self['/trailer/topObject'].value) + ']'].createXML(prefix) + ''' </plist>'''
gpl-3.0
porcobosso/spark-ec2
lib/boto-2.34.0/boto/cloudsearch2/search.py
16
13430
# Copyright (c) 2014 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from math import ceil from boto.compat import json, map, six import requests SIMPLE = 'simple' STRUCTURED = 'structured' LUCENE = 'lucene' DISMAX = 'dismax' class SearchServiceException(Exception): pass class SearchResults(object): def __init__(self, **attrs): self.rid = attrs['status']['rid'] self.time_ms = attrs['status']['time-ms'] self.hits = attrs['hits']['found'] self.docs = attrs['hits']['hit'] self.start = attrs['hits']['start'] self.query = attrs['query'] self.search_service = attrs['search_service'] self.facets = {} if 'facets' in attrs: for (facet, values) in attrs['facets'].items(): if 'buckets' in values: self.facets[facet] = dict((k, v) for (k, v) in map(lambda x: (x['value'], x['count']), values.get('buckets', []))) self.num_pages_needed = ceil(self.hits / self.query.real_size) def __len__(self): return len(self.docs) def __iter__(self): return iter(self.docs) def next_page(self): """Call Cloudsearch to get the next page of search results :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: the following page of search results """ if self.query.page <= self.num_pages_needed: self.query.start += self.query.real_size self.query.page += 1 return self.search_service(self.query) else: raise StopIteration class Query(object): RESULTS_PER_PAGE = 500 def __init__(self, q=None, parser=None, fq=None, expr=None, return_fields=None, size=10, start=0, sort=None, facet=None, highlight=None, partial=None, options=None): self.q = q self.parser = parser self.fq = fq self.expr = expr or {} self.sort = sort or [] self.return_fields = return_fields or [] self.start = start self.facet = facet or {} self.highlight = highlight or {} self.partial = partial self.options = options self.page = 0 self.update_size(size) def update_size(self, new_size): self.size = new_size self.real_size = Query.RESULTS_PER_PAGE if (self.size > Query.RESULTS_PER_PAGE or self.size == 0) else self.size def to_params(self): """Transform search parameters from instance properties to a dictionary :rtype: dict :return: search parameters """ params = {'start': self.start, 'size': self.real_size} if self.q: params['q'] = self.q if self.parser: params['q.parser'] = self.parser if self.fq: params['fq'] = self.fq if self.expr: for k, v in six.iteritems(self.expr): params['expr.%s' % k] = v if self.facet: for k, v in six.iteritems(self.facet): if not isinstance(v, six.string_types): v = json.dumps(v) params['facet.%s' % k] = v if self.highlight: for k, v in six.iteritems(self.highlight): params['highlight.%s' % k] = v if self.options: params['q.options'] = self.options if self.return_fields: params['return'] = ','.join(self.return_fields) if self.partial is not None: params['partial'] = self.partial if self.sort: params['sort'] = ','.join(self.sort) return params class SearchConnection(object): def __init__(self, domain=None, endpoint=None): self.domain = domain self.endpoint = endpoint self.session = requests.Session() # Copy proxy settings from connection if self.domain and self.domain.layer1 and self.domain.layer1.use_proxy: self.session.proxies['http'] = self.domain.layer1.get_proxy_url_with_auth() if not endpoint: self.endpoint = domain.search_service_endpoint def build_query(self, q=None, parser=None, fq=None, rank=None, return_fields=None, size=10, start=0, facet=None, highlight=None, sort=None, partial=None, options=None): return Query(q=q, parser=parser, fq=fq, expr=rank, return_fields=return_fields, size=size, start=start, facet=facet, highlight=highlight, sort=sort, partial=partial, options=options) def search(self, q=None, parser=None, fq=None, rank=None, return_fields=None, size=10, start=0, facet=None, highlight=None, sort=None, partial=None, options=None): """ Send a query to CloudSearch Each search query should use at least the q or bq argument to specify the search parameter. The other options are used to specify the criteria of the search. :type q: string :param q: A string to search the default search fields for. :type parser: string :param parser: The parser to use. 'simple', 'structured', 'lucene', 'dismax' :type fq: string :param fq: The filter query to use. :type sort: List of strings :param sort: A list of fields or rank expressions used to order the search results. Order is handled by adding 'desc' or 'asc' after the field name. ``['year desc', 'author asc']`` :type return_fields: List of strings :param return_fields: A list of fields which should be returned by the search. If this field is not specified, only IDs will be returned. ``['headline']`` :type size: int :param size: Number of search results to specify :type start: int :param start: Offset of the first search result to return (can be used for paging) :type facet: dict :param facet: Dictionary of fields for which facets should be returned The facet value is string of JSON options ``{'year': '{sort:"bucket", size:3}', 'genres': '{buckets:["Action","Adventure","Sci-Fi"]}'}`` :type highlight: dict :param highlight: Dictionary of fields for which highlights should be returned The facet value is string of JSON options ``{'genres': '{format:'text',max_phrases:2,pre_tag:'<b>',post_tag:'</b>'}'}`` :type partial: bool :param partial: Should partial results from a partioned service be returned if one or more index partitions are unreachable. :type options: str :param options: Options for the query parser specified in *parser*. Specified as a string in JSON format. ``{fields: ['title^5', 'description']}`` :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: Returns the results of this search The following examples all assume we have indexed a set of documents with fields: *author*, *date*, *headline* A simple search will look for documents whose default text search fields will contain the search word exactly: >>> search(q='Tim') # Return documents with the word Tim in them (but not Timothy) A simple search with more keywords will return documents whose default text search fields contain the search strings together or separately. >>> search(q='Tim apple') # Will match "tim" and "apple" More complex searches require the boolean search operator. Wildcard searches can be used to search for any words that start with the search string. >>> search(q="'Tim*'") # Return documents with words like Tim or Timothy) Search terms can also be combined. Allowed operators are "and", "or", "not", "field", "optional", "token", "phrase", or "filter" >>> search(q="(and 'Tim' (field author 'John Smith'))", parser='structured') Facets allow you to show classification information about the search results. For example, you can retrieve the authors who have written about Tim with a max of 3 >>> search(q='Tim', facet={'Author': '{sort:"bucket", size:3}'}) """ query = self.build_query(q=q, parser=parser, fq=fq, rank=rank, return_fields=return_fields, size=size, start=start, facet=facet, highlight=highlight, sort=sort, partial=partial, options=options) return self(query) def __call__(self, query): """Make a call to CloudSearch :type query: :class:`boto.cloudsearch2.search.Query` :param query: A group of search criteria :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: search results """ api_version = '2013-01-01' if self.domain: api_version = self.domain.layer1.APIVersion url = "http://%s/%s/search" % (self.endpoint, api_version) params = query.to_params() r = self.session.get(url, params=params) _body = r.content.decode('utf-8') try: data = json.loads(_body) except ValueError: if r.status_code == 403: msg = '' import re g = re.search('<html><body><h1>403 Forbidden</h1>([^<]+)<', _body) try: msg = ': %s' % (g.groups()[0].strip()) except AttributeError: pass raise SearchServiceException('Authentication error from Amazon%s' % msg) raise SearchServiceException("Got non-json response from Amazon. %s" % _body, query) if 'messages' in data and 'error' in data: for m in data['messages']: if m['severity'] == 'fatal': raise SearchServiceException("Error processing search %s " "=> %s" % (params, m['message']), query) elif 'error' in data: raise SearchServiceException("Unknown error processing search %s" % json.dumps(data), query) data['query'] = query data['search_service'] = self return SearchResults(**data) def get_all_paged(self, query, per_page): """Get a generator to iterate over all pages of search results :type query: :class:`boto.cloudsearch2.search.Query` :param query: A group of search criteria :type per_page: int :param per_page: Number of docs in each :class:`boto.cloudsearch2.search.SearchResults` object. :rtype: generator :return: Generator containing :class:`boto.cloudsearch2.search.SearchResults` """ query.update_size(per_page) page = 0 num_pages_needed = 0 while page <= num_pages_needed: results = self(query) num_pages_needed = results.num_pages_needed yield results query.start += query.real_size page += 1 def get_all_hits(self, query): """Get a generator to iterate over all search results Transparently handles the results paging from Cloudsearch search results so even if you have many thousands of results you can iterate over all results in a reasonably efficient manner. :type query: :class:`boto.cloudsearch2.search.Query` :param query: A group of search criteria :rtype: generator :return: All docs matching query """ page = 0 num_pages_needed = 0 while page <= num_pages_needed: results = self(query) num_pages_needed = results.num_pages_needed for doc in results: yield doc query.start += query.real_size page += 1 def get_num_hits(self, query): """Return the total number of hits for query :type query: :class:`boto.cloudsearch2.search.Query` :param query: a group of search criteria :rtype: int :return: Total number of hits for query """ query.update_size(1) return self(query).hits
apache-2.0
levigross/pyscanner
mytests/django/template/context.py
80
6146
from copy import copy from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Cache of actual callables. _standard_context_processors = None # We need the CSRF processor no matter what the user has in their settings, # because otherwise it is a security vulnerability, and we can't afford to leave # this to human error or failure to read migration instructions. _builtin_context_processors = ('django.core.context_processors.csrf',) class ContextPopException(Exception): "pop() has been called more times than push()" pass class BaseContext(object): def __init__(self, dict_=None): self._reset_dicts(dict_) def _reset_dicts(self, value=None): self.dicts = [value or {}] def __copy__(self): duplicate = copy(super(BaseContext, self)) duplicate.dicts = self.dicts[:] return duplicate def __repr__(self): return repr(self.dicts) def __iter__(self): for d in reversed(self.dicts): yield d def push(self): d = {} self.dicts.append(d) return d def pop(self): if len(self.dicts) == 1: raise ContextPopException return self.dicts.pop() def __setitem__(self, key, value): "Set a variable in the current context" self.dicts[-1][key] = value def __getitem__(self, key): "Get a variable's value, starting at the current context and going upward" for d in reversed(self.dicts): if key in d: return d[key] raise KeyError(key) def __delitem__(self, key): "Delete a variable from the current context" del self.dicts[-1][key] def has_key(self, key): for d in self.dicts: if key in d: return True return False def __contains__(self, key): return self.has_key(key) def get(self, key, otherwise=None): for d in reversed(self.dicts): if key in d: return d[key] return otherwise def new(self, values=None): """ Returns a new context with the same properties, but with only the values given in 'values' stored. """ new_context = copy(self) new_context._reset_dicts(values) return new_context class Context(BaseContext): "A stack container for variable context" def __init__(self, dict_=None, autoescape=True, current_app=None, use_l10n=None, use_tz=None): self.autoescape = autoescape self.current_app = current_app self.use_l10n = use_l10n self.use_tz = use_tz self.render_context = RenderContext() super(Context, self).__init__(dict_) def __copy__(self): duplicate = super(Context, self).__copy__() duplicate.render_context = copy(self.render_context) return duplicate def update(self, other_dict): "Pushes other_dict to the stack of dictionaries in the Context" if not hasattr(other_dict, '__getitem__'): raise TypeError('other_dict must be a mapping (dictionary-like) object.') self.dicts.append(other_dict) return other_dict class RenderContext(BaseContext): """ A stack container for storing Template state. RenderContext simplifies the implementation of template Nodes by providing a safe place to store state between invocations of a node's `render` method. The RenderContext also provides scoping rules that are more sensible for 'template local' variables. The render context stack is pushed before each template is rendered, creating a fresh scope with nothing in it. Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context. """ def __iter__(self): for d in self.dicts[-1]: yield d def has_key(self, key): return key in self.dicts[-1] def get(self, key, otherwise=None): d = self.dicts[-1] if key in d: return d[key] return otherwise # This is a function rather than module-level procedural code because we only # want it to execute if somebody uses RequestContext. def get_standard_processors(): from django.conf import settings global _standard_context_processors if _standard_context_processors is None: processors = [] collect = [] collect.extend(_builtin_context_processors) collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS) for path in collect: i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e)) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" callable request processor' % (module, attr)) processors.append(func) _standard_context_processors = tuple(processors) return _standard_context_processors class RequestContext(Context): """ This subclass of template.Context automatically populates itself using the processors defined in TEMPLATE_CONTEXT_PROCESSORS. Additional processors can be specified as a list of callables using the "processors" keyword argument. """ def __init__(self, request, dict_=None, processors=None, current_app=None, use_l10n=None, use_tz=None): Context.__init__(self, dict_, current_app=current_app, use_l10n=use_l10n, use_tz=use_tz) if processors is None: processors = () else: processors = tuple(processors) for processor in get_standard_processors() + processors: self.update(processor(request))
mit
maheshp/novatest
nova/virt/xenapi/vmops.py
1
74575
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2010 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. """ Management class for VM-related functions (spawn, reboot, etc). """ import functools import itertools import time from eventlet import greenthread import netaddr from oslo.config import cfg from nova import block_device from nova.compute import api as compute from nova.compute import instance_types from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_mode from nova import context as nova_context from nova import exception from nova.openstack.common import excutils from nova.openstack.common import importutils from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova.openstack.common import timeutils from nova import utils from nova.virt import configdrive from nova.virt import driver as virt_driver from nova.virt import firewall from nova.virt.xenapi import agent as xapi_agent from nova.virt.xenapi import pool_states from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils from nova.virt.xenapi import volumeops LOG = logging.getLogger(__name__) xenapi_vmops_opts = [ cfg.IntOpt('xenapi_running_timeout', default=60, help='number of seconds to wait for instance ' 'to go to running state'), cfg.StrOpt('xenapi_vif_driver', default='nova.virt.xenapi.vif.XenAPIBridgeDriver', help='The XenAPI VIF driver using XenServer Network APIs.'), cfg.StrOpt('xenapi_image_upload_handler', default='nova.virt.xenapi.imageupload.glance.GlanceStore', help='Object Store Driver used to handle image uploads.'), ] CONF = cfg.CONF CONF.register_opts(xenapi_vmops_opts) CONF.import_opt('host', 'nova.netconf') CONF.import_opt('vncserver_proxyclient_address', 'nova.vnc') DEFAULT_FIREWALL_DRIVER = "%s.%s" % ( firewall.__name__, firewall.IptablesFirewallDriver.__name__) RESIZE_TOTAL_STEPS = 5 DEVICE_ROOT = '0' DEVICE_RESCUE = '1' DEVICE_SWAP = '2' DEVICE_EPHEMERAL = '3' DEVICE_CD = '4' DEVICE_CONFIGDRIVE = '5' def cmp_version(a, b): """Compare two version strings (eg 0.0.1.10 > 0.0.1.9).""" a = a.split('.') b = b.split('.') # Compare each individual portion of both version strings for va, vb in zip(a, b): ret = int(va) - int(vb) if ret: return ret # Fallback to comparing length last return len(a) - len(b) def make_step_decorator(context, instance, instance_update): """Factory to create a decorator that records instance progress as a series of discrete steps. Each time the decorator is invoked we bump the total-step-count, so after:: @step def step1(): ... @step def step2(): ... we have a total-step-count of 2. Each time the step-function (not the step-decorator!) is invoked, we bump the current-step-count by 1, so after:: step1() the current-step-count would be 1 giving a progress of ``1 / 2 * 100`` or 50%. """ step_info = dict(total=0, current=0) def bump_progress(): step_info['current'] += 1 progress = round(float(step_info['current']) / step_info['total'] * 100) LOG.debug(_("Updating progress to %(progress)d"), locals(), instance=instance) instance_update(context, instance['uuid'], {'progress': progress}) def step_decorator(f): step_info['total'] += 1 @functools.wraps(f) def inner(*args, **kwargs): rv = f(*args, **kwargs) bump_progress() return rv return inner return step_decorator class VMOps(object): """ Management class for VM-related tasks """ def __init__(self, session, virtapi): self.compute_api = compute.API() self._session = session self._virtapi = virtapi self._volumeops = volumeops.VolumeOps(self._session) self.firewall_driver = firewall.load_driver( DEFAULT_FIREWALL_DRIVER, self._virtapi, xenapi_session=self._session) vif_impl = importutils.import_class(CONF.xenapi_vif_driver) self.vif_driver = vif_impl(xenapi_session=self._session) self.default_root_dev = '/dev/sda' msg = _("Importing image upload handler: %s") LOG.debug(msg % CONF.xenapi_image_upload_handler) self.image_upload_handler = importutils.import_object( CONF.xenapi_image_upload_handler) @property def agent_enabled(self): return not CONF.xenapi_disable_agent def _get_agent(self, instance, vm_ref): if self.agent_enabled: return xapi_agent.XenAPIBasedAgent(self._session, self._virtapi, instance, vm_ref) raise exception.NovaException(_("Error: Agent is disabled")) def list_instances(self): """List VM instances.""" # TODO(justinsb): Should we just always use the details method? # Seems to be the same number of API calls.. name_labels = [] for vm_ref, vm_rec in vm_utils.list_vms(self._session): name_labels.append(vm_rec["name_label"]) return name_labels def confirm_migration(self, migration, instance, network_info): name_label = self._get_orig_vm_name_label(instance) vm_ref = vm_utils.lookup(self._session, name_label) return self._destroy(instance, vm_ref, network_info=network_info) def _attach_mapped_block_devices(self, instance, block_device_info): # We are attaching these volumes before start (no hotplugging) # because some guests (windows) don't load PV drivers quickly block_device_mapping = virt_driver.block_device_info_get_mapping( block_device_info) for vol in block_device_mapping: connection_info = vol['connection_info'] mount_device = vol['mount_device'].rpartition("/")[2] self._volumeops.attach_volume(connection_info, instance['name'], mount_device, hotplug=False) def finish_revert_migration(self, instance, block_device_info=None): # NOTE(sirp): the original vm was suffixed with '-orig'; find it using # the old suffix, remove the suffix, then power it back on. name_label = self._get_orig_vm_name_label(instance) vm_ref = vm_utils.lookup(self._session, name_label) # NOTE(danms): if we're reverting migration in the failure case, # make sure we don't have a conflicting vm still running here, # as might be the case in a failed migrate-to-same-host situation new_ref = vm_utils.lookup(self._session, instance['name']) if vm_ref is not None: if new_ref is not None: self._destroy(instance, new_ref) # Remove the '-orig' suffix (which was added in case the # resized VM ends up on the source host, common during # testing) name_label = instance['name'] vm_utils.set_vm_name_label(self._session, vm_ref, name_label) self._attach_mapped_block_devices(instance, block_device_info) elif new_ref is not None: # We crashed before the -orig backup was made vm_ref = new_ref self._start(instance, vm_ref) def finish_migration(self, context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info=None): root_vdi = vm_utils.move_disks(self._session, instance, disk_info) if resize_instance: self._resize_instance(instance, root_vdi) # Check if kernel and ramdisk are external kernel_file = None ramdisk_file = None name_label = instance['name'] if instance['kernel_id']: vdis = vm_utils.create_kernel_image(context, self._session, instance, name_label, instance['kernel_id'], vm_utils.ImageType.KERNEL) kernel_file = vdis['kernel'].get('file') if instance['ramdisk_id']: vdis = vm_utils.create_kernel_image(context, self._session, instance, name_label, instance['ramdisk_id'], vm_utils.ImageType.RAMDISK) ramdisk_file = vdis['ramdisk'].get('file') disk_image_type = vm_utils.determine_disk_image_type(image_meta) vm_ref = self._create_vm(context, instance, instance['name'], {'root': root_vdi}, disk_image_type, network_info, kernel_file, ramdisk_file) self._attach_mapped_block_devices(instance, block_device_info) # 5. Start VM self._start(instance, vm_ref=vm_ref) self._update_instance_progress(context, instance, step=5, total_steps=RESIZE_TOTAL_STEPS) def _start(self, instance, vm_ref=None, bad_volumes_callback=None): """Power on a VM instance.""" vm_ref = vm_ref or self._get_vm_opaque_ref(instance) LOG.debug(_("Starting instance"), instance=instance) # Attached volumes that have become non-responsive will prevent a VM # from starting, so scan for these before attempting to start # # In order to make sure this detach is consistent (virt, BDM, cinder), # we only detach in the virt-layer if a callback is provided. if bad_volumes_callback: bad_devices = self._volumeops.find_bad_volumes(vm_ref) for device_name in bad_devices: self._volumeops.detach_volume( None, instance['name'], device_name) self._session.call_xenapi('VM.start_on', vm_ref, self._session.get_xenapi_host(), False, False) # Allow higher-layers a chance to detach bad-volumes as well (in order # to cleanup BDM entries and detach in Cinder) if bad_volumes_callback and bad_devices: bad_volumes_callback(bad_devices) def _create_disks(self, context, instance, name_label, disk_image_type, image_meta, block_device_info=None): vdis = vm_utils.get_vdis_for_instance(context, self._session, instance, name_label, image_meta.get('id'), disk_image_type, block_device_info=block_device_info) # Just get the VDI ref once for vdi in vdis.itervalues(): vdi['ref'] = self._session.call_xenapi('VDI.get_by_uuid', vdi['uuid']) root_vdi = vdis.get('root') if root_vdi: self._resize_instance(instance, root_vdi) return vdis def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None, name_label=None, rescue=False): if name_label is None: name_label = instance['name'] step = make_step_decorator(context, instance, self._virtapi.instance_update) @step def determine_disk_image_type_step(undo_mgr): return vm_utils.determine_disk_image_type(image_meta) @step def create_disks_step(undo_mgr, disk_image_type, image_meta): vdis = self._create_disks(context, instance, name_label, disk_image_type, image_meta, block_device_info=block_device_info) def undo_create_disks(): vdi_refs = [vdi['ref'] for vdi in vdis.values() if not vdi.get('osvol')] vm_utils.safe_destroy_vdis(self._session, vdi_refs) undo_mgr.undo_with(undo_create_disks) return vdis @step def create_kernel_ramdisk_step(undo_mgr): kernel_file = None ramdisk_file = None if instance['kernel_id']: vdis = vm_utils.create_kernel_image(context, self._session, instance, name_label, instance['kernel_id'], vm_utils.ImageType.KERNEL) kernel_file = vdis['kernel'].get('file') if instance['ramdisk_id']: vdis = vm_utils.create_kernel_image(context, self._session, instance, name_label, instance['ramdisk_id'], vm_utils.ImageType.RAMDISK) ramdisk_file = vdis['ramdisk'].get('file') def undo_create_kernel_ramdisk(): if kernel_file or ramdisk_file: LOG.debug(_("Removing kernel/ramdisk files from dom0"), instance=instance) vm_utils.destroy_kernel_ramdisk( self._session, kernel_file, ramdisk_file) undo_mgr.undo_with(undo_create_kernel_ramdisk) return kernel_file, ramdisk_file @step def create_vm_record_step(undo_mgr, vdis, disk_image_type, kernel_file, ramdisk_file): vm_ref = self._create_vm_record(context, instance, name_label, vdis, disk_image_type, kernel_file, ramdisk_file) def undo_create_vm(): self._destroy(instance, vm_ref, network_info=network_info) undo_mgr.undo_with(undo_create_vm) return vm_ref @step def attach_disks_step(undo_mgr, vm_ref, vdis, disk_image_type): self._attach_disks(instance, vm_ref, name_label, vdis, disk_image_type, admin_password, injected_files) if rescue: # NOTE(johannes): Attach root disk to rescue VM now, before # booting the VM, since we can't hotplug block devices # on non-PV guests @step def attach_root_disk_step(undo_mgr, vm_ref): orig_vm_ref = vm_utils.lookup(self._session, instance['name']) vdi_ref = self._find_root_vdi_ref(orig_vm_ref) vm_utils.create_vbd(self._session, vm_ref, vdi_ref, DEVICE_RESCUE, bootable=False) @step def setup_network_step(undo_mgr, vm_ref, vdis): self._setup_vm_networking(instance, vm_ref, vdis, network_info, rescue) @step def inject_metadata_step(undo_mgr, vm_ref): self.inject_instance_metadata(instance, vm_ref) @step def prepare_security_group_filters_step(undo_mgr): try: self.firewall_driver.setup_basic_filtering( instance, network_info) except NotImplementedError: # NOTE(salvatore-orlando): setup_basic_filtering might be # empty or not implemented at all, as basic filter could # be implemented with VIF rules created by xapi plugin pass self.firewall_driver.prepare_instance_filter(instance, network_info) @step def boot_instance_step(undo_mgr, vm_ref): self._boot_new_instance(instance, vm_ref, injected_files, admin_password) @step def apply_security_group_filters_step(undo_mgr): self.firewall_driver.apply_instance_filter(instance, network_info) @step def bdev_set_default_root(undo_mgr): if block_device_info: LOG.debug(_("Block device information present: %s") % block_device_info, instance=instance) if block_device_info and not block_device_info['root_device_name']: block_device_info['root_device_name'] = self.default_root_dev undo_mgr = utils.UndoManager() try: # NOTE(sirp): The create_disks() step will potentially take a # *very* long time to complete since it has to fetch the image # over the network and images can be several gigs in size. To # avoid progress remaining at 0% for too long, make sure the # first step is something that completes rather quickly. bdev_set_default_root(undo_mgr) disk_image_type = determine_disk_image_type_step(undo_mgr) vdis = create_disks_step(undo_mgr, disk_image_type, image_meta) kernel_file, ramdisk_file = create_kernel_ramdisk_step(undo_mgr) vm_ref = create_vm_record_step(undo_mgr, vdis, disk_image_type, kernel_file, ramdisk_file) attach_disks_step(undo_mgr, vm_ref, vdis, disk_image_type) setup_network_step(undo_mgr, vm_ref, vdis) inject_metadata_step(undo_mgr, vm_ref) prepare_security_group_filters_step(undo_mgr) if rescue: attach_root_disk_step(undo_mgr, vm_ref) boot_instance_step(undo_mgr, vm_ref) apply_security_group_filters_step(undo_mgr) except Exception: msg = _("Failed to spawn, rolling back") undo_mgr.rollback_and_reraise(msg=msg, instance=instance) def _create_vm(self, context, instance, name_label, vdis, disk_image_type, network_info, kernel_file=None, ramdisk_file=None, rescue=False): """Create VM instance.""" vm_ref = self._create_vm_record(context, instance, name_label, vdis, disk_image_type, kernel_file, ramdisk_file) self._attach_disks(instance, vm_ref, name_label, vdis, disk_image_type) self._setup_vm_networking(instance, vm_ref, vdis, network_info, rescue) # NOTE(mikal): file injection only happens if we are _not_ using a # configdrive. if not configdrive.required_by(instance): self.inject_instance_metadata(instance, vm_ref) return vm_ref def _setup_vm_networking(self, instance, vm_ref, vdis, network_info, rescue): # Alter the image before VM start for network injection. if CONF.flat_injected: vm_utils.preconfigure_instance(self._session, instance, vdis['root']['ref'], network_info) self._create_vifs(vm_ref, instance, network_info) self.inject_network_info(instance, network_info, vm_ref) hostname = instance['hostname'] if rescue: hostname = 'RESCUE-%s' % hostname self.inject_hostname(instance, vm_ref, hostname) def _create_vm_record(self, context, instance, name_label, vdis, disk_image_type, kernel_file, ramdisk_file): """Create the VM record in Xen, making sure that we do not create a duplicate name-label. Also do a rough sanity check on memory to try to short-circuit a potential failure later. (The memory check only accounts for running VMs, so it can miss other builds that are in progress.) """ vm_ref = vm_utils.lookup(self._session, name_label) if vm_ref is not None: raise exception.InstanceExists(name=name_label) # Ensure enough free memory is available if not vm_utils.ensure_free_mem(self._session, instance): raise exception.InsufficientFreeMemory(uuid=instance['uuid']) mode = vm_mode.get_from_instance(instance) if mode == vm_mode.XEN: use_pv_kernel = True elif mode == vm_mode.HVM: use_pv_kernel = False else: use_pv_kernel = vm_utils.determine_is_pv(self._session, vdis['root']['ref'], disk_image_type, instance['os_type']) mode = use_pv_kernel and vm_mode.XEN or vm_mode.HVM if instance['vm_mode'] != mode: # Update database with normalized (or determined) value self._virtapi.instance_update(context, instance['uuid'], {'vm_mode': mode}) vm_ref = vm_utils.create_vm(self._session, instance, name_label, kernel_file, ramdisk_file, use_pv_kernel) return vm_ref def _attach_disks(self, instance, vm_ref, name_label, vdis, disk_image_type, admin_password=None, files=None): ctx = nova_context.get_admin_context() instance_type = instance_types.extract_instance_type(instance) # Attach (required) root disk if disk_image_type == vm_utils.ImageType.DISK_ISO: # DISK_ISO needs two VBDs: the ISO disk and a blank RW disk LOG.debug(_("Detected ISO image type, creating blank VM " "for install"), instance=instance) cd_vdi = vdis.pop('root') root_vdi = vm_utils.fetch_blank_disk(self._session, instance_type['id']) vdis['root'] = root_vdi vm_utils.create_vbd(self._session, vm_ref, root_vdi['ref'], DEVICE_ROOT, bootable=False) vm_utils.create_vbd(self._session, vm_ref, cd_vdi['ref'], DEVICE_CD, vbd_type='CD', bootable=True) else: root_vdi = vdis['root'] if instance['auto_disk_config']: LOG.debug(_("Auto configuring disk, attempting to " "resize partition..."), instance=instance) vm_utils.auto_configure_disk(self._session, root_vdi['ref'], instance_type['root_gb']) vm_utils.create_vbd(self._session, vm_ref, root_vdi['ref'], DEVICE_ROOT, bootable=True, osvol=root_vdi.get('osvol')) # Attach (optional) additional block-devices for type_, vdi_info in vdis.items(): # Additional block-devices for boot use their device-name as the # type. if not type_.startswith('/dev'): continue # Convert device name to userdevice number, e.g. /dev/xvdb -> 1 userdevice = ord(block_device.strip_prefix(type_)) - ord('a') vm_utils.create_vbd(self._session, vm_ref, vdi_info['ref'], userdevice, bootable=False, osvol=vdi_info.get('osvol')) # Attach (optional) swap disk swap_mb = instance_type['swap'] if swap_mb: vm_utils.generate_swap(self._session, instance, vm_ref, DEVICE_SWAP, name_label, swap_mb) # Attach (optional) ephemeral disk ephemeral_gb = instance_type['ephemeral_gb'] if ephemeral_gb: vm_utils.generate_ephemeral(self._session, instance, vm_ref, DEVICE_EPHEMERAL, name_label, ephemeral_gb) # Attach (optional) configdrive v2 disk if configdrive.required_by(instance): vm_utils.generate_configdrive(self._session, instance, vm_ref, DEVICE_CONFIGDRIVE, admin_password=admin_password, files=files) def _boot_new_instance(self, instance, vm_ref, injected_files, admin_password): """Boot a new instance and configure it.""" LOG.debug(_('Starting VM'), instance=instance) self._start(instance, vm_ref) ctx = nova_context.get_admin_context() # Wait for boot to finish LOG.debug(_('Waiting for instance state to become running'), instance=instance) expiration = time.time() + CONF.xenapi_running_timeout while time.time() < expiration: state = self.get_info(instance, vm_ref)['state'] if state == power_state.RUNNING: break greenthread.sleep(0.5) if self.agent_enabled: agent_build = self._virtapi.agent_build_get_by_triple( ctx, 'xen', instance['os_type'], instance['architecture']) if agent_build: LOG.info(_('Latest agent build for %(hypervisor)s/%(os)s' '/%(architecture)s is %(version)s') % agent_build) else: LOG.info(_('No agent build found for %(hypervisor)s/%(os)s' '/%(architecture)s') % { 'hypervisor': 'xen', 'os': instance['os_type'], 'architecture': instance['architecture']}) # Update agent, if necessary # This also waits until the agent starts agent = self._get_agent(instance, vm_ref) version = agent.get_agent_version() if version: LOG.info(_('Instance agent version: %s'), version, instance=instance) if (version and agent_build and cmp_version(version, agent_build['version']) < 0): agent.agent_update(agent_build) # if the guest agent is not available, configure the # instance, but skip the admin password configuration no_agent = version is None # Inject ssh key. agent.inject_ssh_key() # Inject files, if necessary if injected_files: # Inject any files, if specified for path, contents in injected_files: agent.inject_file(path, contents) # Set admin password, if necessary if admin_password and not no_agent: agent.set_admin_password(admin_password) # Reset network config agent.resetnetwork() # Set VCPU weight instance_type = instance_types.extract_instance_type(instance) vcpu_weight = instance_type['vcpu_weight'] if vcpu_weight is not None: LOG.debug(_("Setting VCPU weight"), instance=instance) self._session.call_xenapi('VM.add_to_VCPUs_params', vm_ref, 'weight', str(vcpu_weight)) def _get_vm_opaque_ref(self, instance): """Get xapi OpaqueRef from a db record.""" vm_ref = vm_utils.lookup(self._session, instance['name']) if vm_ref is None: raise exception.NotFound(_('Could not find VM with name %s') % instance['name']) return vm_ref def _acquire_bootlock(self, vm): """Prevent an instance from booting.""" self._session.call_xenapi( "VM.set_blocked_operations", vm, {"start": ""}) def _release_bootlock(self, vm): """Allow an instance to boot.""" self._session.call_xenapi( "VM.remove_from_blocked_operations", vm, "start") def snapshot(self, context, instance, image_id, update_task_state): """Create snapshot from a running VM instance. :param context: request context :param instance: instance to be snapshotted :param image_id: id of image to upload to Steps involved in a XenServer snapshot: 1. XAPI-Snapshot: Snapshotting the instance using XenAPI. This creates: Snapshot (Template) VM, Snapshot VBD, Snapshot VDI, Snapshot VHD 2. Wait-for-coalesce: The Snapshot VDI and Instance VDI both point to a 'base-copy' VDI. The base_copy is immutable and may be chained with other base_copies. If chained, the base_copies coalesce together, so, we must wait for this coalescing to occur to get a stable representation of the data on disk. 3. Push-to-data-store: Once coalesced, we call a plugin on the XenServer that will bundle the VHDs together and then push the bundle. Depending on the configured value of 'xenapi_image_upload_handler', image data may be pushed to Glance or the specified data store. """ vm_ref = self._get_vm_opaque_ref(instance) label = "%s-snapshot" % instance['name'] with vm_utils.snapshot_attached_here( self._session, instance, vm_ref, label, update_task_state) as vdi_uuids: update_task_state(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD) self.image_upload_handler.upload_image(context, self._session, instance, vdi_uuids, image_id) LOG.debug(_("Finished snapshot and upload for VM"), instance=instance) def _migrate_vhd(self, instance, vdi_uuid, dest, sr_path, seq_num): LOG.debug(_("Migrating VHD '%(vdi_uuid)s' with seq_num %(seq_num)d"), locals(), instance=instance) instance_uuid = instance['uuid'] try: self._session.call_plugin_serialized('migration', 'transfer_vhd', instance_uuid=instance_uuid, host=dest, vdi_uuid=vdi_uuid, sr_path=sr_path, seq_num=seq_num) except self._session.XenAPI.Failure: msg = _("Failed to transfer vhd to new host") raise exception.MigrationError(reason=msg) def _get_orig_vm_name_label(self, instance): return instance['name'] + '-orig' def _update_instance_progress(self, context, instance, step, total_steps): """Update instance progress percent to reflect current step number """ # FIXME(sirp): for now we're taking a KISS approach to instance # progress: # Divide the action's workflow into discrete steps and "bump" the # instance's progress field as each step is completed. # # For a first cut this should be fine, however, for large VM images, # the _create_disks step begins to dominate the equation. A # better approximation would use the percentage of the VM image that # has been streamed to the destination host. progress = round(float(step) / total_steps * 100) LOG.debug(_("Updating progress to %(progress)d"), locals(), instance=instance) self._virtapi.instance_update(context, instance['uuid'], {'progress': progress}) def _migrate_disk_resizing_down(self, context, instance, dest, instance_type, vm_ref, sr_path): # 1. NOOP since we're not transmitting the base-copy separately self._update_instance_progress(context, instance, step=1, total_steps=RESIZE_TOTAL_STEPS) vdi_ref, vm_vdi_rec = vm_utils.get_vdi_for_vm_safely( self._session, vm_ref) vdi_uuid = vm_vdi_rec['uuid'] old_gb = instance['root_gb'] new_gb = instance_type['root_gb'] LOG.debug(_("Resizing down VDI %(vdi_uuid)s from " "%(old_gb)dGB to %(new_gb)dGB"), locals(), instance=instance) # 2. Power down the instance before resizing if not vm_utils.clean_shutdown_vm(self._session, instance, vm_ref): LOG.debug(_("Clean shutdown did not complete successfully, " "trying hard shutdown."), instance=instance) vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) self._update_instance_progress(context, instance, step=2, total_steps=RESIZE_TOTAL_STEPS) # 3. Copy VDI, resize partition and filesystem, forget VDI, # truncate VHD new_ref, new_uuid = vm_utils.resize_disk(self._session, instance, vdi_ref, instance_type) self._update_instance_progress(context, instance, step=3, total_steps=RESIZE_TOTAL_STEPS) # 4. Transfer the new VHD self._migrate_vhd(instance, new_uuid, dest, sr_path, 0) self._update_instance_progress(context, instance, step=4, total_steps=RESIZE_TOTAL_STEPS) # Clean up VDI now that it's been copied vm_utils.destroy_vdi(self._session, new_ref) def _migrate_disk_resizing_up(self, context, instance, dest, vm_ref, sr_path): # 1. Create Snapshot label = "%s-snapshot" % instance['name'] with vm_utils.snapshot_attached_here( self._session, instance, vm_ref, label) as vdi_uuids: self._update_instance_progress(context, instance, step=1, total_steps=RESIZE_TOTAL_STEPS) # 2. Transfer the immutable VHDs (base-copies) # # The first VHD will be the leaf (aka COW) that is being used by # the VM. For this step, we're only interested in the immutable # VHDs which are all of the parents of the leaf VHD. for seq_num, vdi_uuid in itertools.islice( enumerate(vdi_uuids), 1, None): self._migrate_vhd(instance, vdi_uuid, dest, sr_path, seq_num) self._update_instance_progress(context, instance, step=2, total_steps=RESIZE_TOTAL_STEPS) # 3. Now power down the instance if not vm_utils.clean_shutdown_vm(self._session, instance, vm_ref): LOG.debug(_("Clean shutdown did not complete successfully, " "trying hard shutdown."), instance=instance) vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) self._update_instance_progress(context, instance, step=3, total_steps=RESIZE_TOTAL_STEPS) # 4. Transfer the COW VHD vdi_ref, vm_vdi_rec = vm_utils.get_vdi_for_vm_safely( self._session, vm_ref) cow_uuid = vm_vdi_rec['uuid'] self._migrate_vhd(instance, cow_uuid, dest, sr_path, 0) self._update_instance_progress(context, instance, step=4, total_steps=RESIZE_TOTAL_STEPS) def migrate_disk_and_power_off(self, context, instance, dest, instance_type): """Copies a VHD from one host machine to another, possibly resizing filesystem before hand. :param instance: the instance that owns the VHD in question. :param dest: the destination host machine. :param instance_type: instance_type to resize to """ vm_ref = self._get_vm_opaque_ref(instance) sr_path = vm_utils.get_sr_path(self._session) resize_down = instance['root_gb'] > instance_type['root_gb'] if resize_down and not instance['auto_disk_config']: reason = _('Resize down not allowed without auto_disk_config') raise exception.ResizeError(reason=reason) # 0. Zero out the progress to begin self._update_instance_progress(context, instance, step=0, total_steps=RESIZE_TOTAL_STEPS) # NOTE(sirp): in case we're resizing to the same host (for dev # purposes), apply a suffix to name-label so the two VM records # extant until a confirm_resize don't collide. name_label = self._get_orig_vm_name_label(instance) vm_utils.set_vm_name_label(self._session, vm_ref, name_label) if resize_down: self._migrate_disk_resizing_down( context, instance, dest, instance_type, vm_ref, sr_path) else: self._migrate_disk_resizing_up( context, instance, dest, vm_ref, sr_path) # NOTE(sirp): disk_info isn't used by the xenapi driver, instead it # uses a staging-area (/images/instance<uuid>) and sequence-numbered # VHDs to figure out how to reconstruct the VDI chain after syncing disk_info = {} return disk_info def _resize_instance(self, instance, root_vdi): """Resize an instances root disk.""" new_disk_size = instance['root_gb'] * 1024 * 1024 * 1024 if not new_disk_size: return # Get current size of VDI virtual_size = self._session.call_xenapi('VDI.get_virtual_size', root_vdi['ref']) virtual_size = int(virtual_size) old_gb = virtual_size / (1024 * 1024 * 1024) new_gb = instance['root_gb'] if virtual_size < new_disk_size: # Resize up. Simple VDI resize will do the trick vdi_uuid = root_vdi['uuid'] LOG.debug(_("Resizing up VDI %(vdi_uuid)s from %(old_gb)dGB to " "%(new_gb)dGB"), locals(), instance=instance) resize_func_name = self.check_resize_func_name() self._session.call_xenapi(resize_func_name, root_vdi['ref'], str(new_disk_size)) LOG.debug(_("Resize complete"), instance=instance) def check_resize_func_name(self): """Check the function name used to resize an instance based on product_brand and product_version.""" brand = self._session.product_brand version = self._session.product_version # To maintain backwards compatibility. All recent versions # should use VDI.resize if bool(version) and bool(brand): xcp = brand == 'XCP' r1_2_or_above = ( ( version[0] == 1 and version[1] > 1 ) or version[0] > 1) xenserver = brand == 'XenServer' r6_or_above = version[0] > 5 if (xcp and not r1_2_or_above) or (xenserver and not r6_or_above): return 'VDI.resize_online' return 'VDI.resize' def reboot(self, instance, reboot_type, bad_volumes_callback=None): """Reboot VM instance.""" # Note (salvatore-orlando): security group rules are not re-enforced # upon reboot, since this action on the XenAPI drivers does not # remove existing filters vm_ref = self._get_vm_opaque_ref(instance) try: if reboot_type == "HARD": self._session.call_xenapi('VM.hard_reboot', vm_ref) else: self._session.call_xenapi('VM.clean_reboot', vm_ref) except self._session.XenAPI.Failure, exc: details = exc.details if (details[0] == 'VM_BAD_POWER_STATE' and details[-1] == 'halted'): LOG.info(_("Starting halted instance found during reboot"), instance=instance) self._start(instance, vm_ref=vm_ref, bad_volumes_callback=bad_volumes_callback) return elif details[0] == 'SR_BACKEND_FAILURE_46': LOG.warn(_("Reboot failed due to bad volumes, detaching bad" " volumes and starting halted instance"), instance=instance) self._start(instance, vm_ref=vm_ref, bad_volumes_callback=bad_volumes_callback) return else: raise def set_admin_password(self, instance, new_pass): """Set the root/admin password on the VM instance.""" if self.agent_enabled: vm_ref = self._get_vm_opaque_ref(instance) agent = self._get_agent(instance, vm_ref) agent.set_admin_password(new_pass) else: raise NotImplementedError() def inject_file(self, instance, path, contents): """Write a file to the VM instance.""" if self.agent_enabled: vm_ref = self._get_vm_opaque_ref(instance) agent = self._get_agent(instance, vm_ref) agent.inject_file(path, contents) else: raise NotImplementedError() @staticmethod def _sanitize_xenstore_key(key): """ Xenstore only allows the following characters as keys: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789-/_@ So convert the others to _ Also convert / to _, because that is somewhat like a path separator. """ allowed_chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789-_@") return ''.join([x in allowed_chars and x or '_' for x in key]) def inject_instance_metadata(self, instance, vm_ref): """Inject instance metadata into xenstore.""" def store_meta(topdir, data_list): for item in data_list: key = self._sanitize_xenstore_key(item['key']) value = item['value'] or '' self._add_to_param_xenstore(vm_ref, '%s/%s' % (topdir, key), jsonutils.dumps(value)) # Store user metadata store_meta('vm-data/user-metadata', instance['metadata']) def change_instance_metadata(self, instance, diff): """Apply changes to instance metadata to xenstore.""" vm_ref = self._get_vm_opaque_ref(instance) for key, change in diff.items(): key = self._sanitize_xenstore_key(key) location = 'vm-data/user-metadata/%s' % key if change[0] == '-': self._remove_from_param_xenstore(vm_ref, location) try: self._delete_from_xenstore(instance, location, vm_ref=vm_ref) except KeyError: # catch KeyError for domid if instance isn't running pass elif change[0] == '+': self._add_to_param_xenstore(vm_ref, location, jsonutils.dumps(change[1])) try: self._write_to_xenstore(instance, location, change[1], vm_ref=vm_ref) except KeyError: # catch KeyError for domid if instance isn't running pass def _find_root_vdi_ref(self, vm_ref): """Find and return the root vdi ref for a VM.""" if not vm_ref: return None vbd_refs = self._session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_uuid in vbd_refs: vbd = self._session.call_xenapi("VBD.get_record", vbd_uuid) if vbd["userdevice"] == DEVICE_ROOT: return vbd["VDI"] raise exception.NotFound(_("Unable to find root VBD/VDI for VM")) def _destroy_vdis(self, instance, vm_ref): """Destroys all VDIs associated with a VM.""" LOG.debug(_("Destroying VDIs"), instance=instance) vdi_refs = vm_utils.lookup_vm_vdis(self._session, vm_ref) if not vdi_refs: return for vdi_ref in vdi_refs: try: vm_utils.destroy_vdi(self._session, vdi_ref) except volume_utils.StorageError as exc: LOG.error(exc) def _destroy_kernel_ramdisk(self, instance, vm_ref): """Three situations can occur: 1. We have neither a ramdisk nor a kernel, in which case we are a RAW image and can omit this step 2. We have one or the other, in which case, we should flag as an error 3. We have both, in which case we safely remove both the kernel and the ramdisk. """ instance_uuid = instance['uuid'] if not instance['kernel_id'] and not instance['ramdisk_id']: # 1. No kernel or ramdisk LOG.debug(_("Using RAW or VHD, skipping kernel and ramdisk " "deletion"), instance=instance) return if not (instance['kernel_id'] and instance['ramdisk_id']): # 2. We only have kernel xor ramdisk raise exception.InstanceUnacceptable(instance_id=instance_uuid, reason=_("instance has a kernel or ramdisk but not both")) # 3. We have both kernel and ramdisk (kernel, ramdisk) = vm_utils.lookup_kernel_ramdisk(self._session, vm_ref) if kernel or ramdisk: vm_utils.destroy_kernel_ramdisk(self._session, kernel, ramdisk) LOG.debug(_("kernel/ramdisk files removed"), instance=instance) def _destroy_rescue_instance(self, rescue_vm_ref, original_vm_ref): """Destroy a rescue instance.""" # Shutdown Rescue VM vm_rec = self._session.call_xenapi("VM.get_record", rescue_vm_ref) state = vm_utils.compile_info(vm_rec)['state'] if state != power_state.SHUTDOWN: self._session.call_xenapi("VM.hard_shutdown", rescue_vm_ref) # Destroy Rescue VDIs vdi_refs = vm_utils.lookup_vm_vdis(self._session, rescue_vm_ref) root_vdi_ref = self._find_root_vdi_ref(original_vm_ref) vdi_refs = [vdi_ref for vdi_ref in vdi_refs if vdi_ref != root_vdi_ref] vm_utils.safe_destroy_vdis(self._session, vdi_refs) # Destroy Rescue VM self._session.call_xenapi("VM.destroy", rescue_vm_ref) def destroy(self, instance, network_info, block_device_info=None, destroy_disks=True): """Destroy VM instance. This is the method exposed by xenapi_conn.destroy(). The rest of the destroy_* methods are internal. """ LOG.info(_("Destroying VM"), instance=instance) # We don't use _get_vm_opaque_ref because the instance may # truly not exist because of a failure during build. A valid # vm_ref is checked correctly where necessary. vm_ref = vm_utils.lookup(self._session, instance['name']) rescue_vm_ref = vm_utils.lookup(self._session, "%s-rescue" % instance['name']) if rescue_vm_ref: self._destroy_rescue_instance(rescue_vm_ref, vm_ref) # NOTE(sirp): `block_device_info` is not used, information about which # volumes should be detached is determined by the # VBD.other_config['osvol'] attribute return self._destroy(instance, vm_ref, network_info=network_info, destroy_disks=destroy_disks) def _destroy(self, instance, vm_ref, network_info=None, destroy_disks=True): """Destroys VM instance by performing: 1. A shutdown 2. Destroying associated VDIs. 3. Destroying kernel and ramdisk files (if necessary). 4. Destroying that actual VM record. """ if vm_ref is None: LOG.warning(_("VM is not present, skipping destroy..."), instance=instance) return vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) if destroy_disks: self._volumeops.detach_all(vm_ref) self._destroy_vdis(instance, vm_ref) self._destroy_kernel_ramdisk(instance, vm_ref) vm_utils.destroy_vm(self._session, instance, vm_ref) self.unplug_vifs(instance, network_info) self.firewall_driver.unfilter_instance( instance, network_info=network_info) def pause(self, instance): """Pause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.pause', vm_ref) def unpause(self, instance): """Unpause VM instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._session.call_xenapi('VM.unpause', vm_ref) def suspend(self, instance): """Suspend the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._acquire_bootlock(vm_ref) self._session.call_xenapi('VM.suspend', vm_ref) def resume(self, instance): """Resume the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._release_bootlock(vm_ref) self._session.call_xenapi('VM.resume', vm_ref, False, True) def rescue(self, context, instance, network_info, image_meta, rescue_password): """Rescue the specified instance. - shutdown the instance VM. - set 'bootlock' to prevent the instance from starting in rescue. - spawn a rescue VM (the vm name-label will be instance-N-rescue). """ rescue_name_label = '%s-rescue' % instance['name'] rescue_vm_ref = vm_utils.lookup(self._session, rescue_name_label) if rescue_vm_ref: raise RuntimeError(_("Instance is already in Rescue Mode: %s") % instance['name']) vm_ref = self._get_vm_opaque_ref(instance) vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) self._acquire_bootlock(vm_ref) self.spawn(context, instance, image_meta, [], rescue_password, network_info, name_label=rescue_name_label, rescue=True) def unrescue(self, instance): """Unrescue the specified instance. - unplug the instance VM's disk from the rescue VM. - teardown the rescue VM. - release the bootlock to allow the instance VM to start. """ rescue_vm_ref = vm_utils.lookup(self._session, "%s-rescue" % instance['name']) if not rescue_vm_ref: raise exception.InstanceNotInRescueMode( instance_id=instance['uuid']) original_vm_ref = self._get_vm_opaque_ref(instance) self._destroy_rescue_instance(rescue_vm_ref, original_vm_ref) self._release_bootlock(original_vm_ref) self._start(instance, original_vm_ref) def soft_delete(self, instance): """Soft delete the specified instance.""" try: vm_ref = self._get_vm_opaque_ref(instance) except exception.NotFound: LOG.warning(_("VM is not present, skipping soft delete..."), instance=instance) else: vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) self._acquire_bootlock(vm_ref) def restore(self, instance): """Restore the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._release_bootlock(vm_ref) self._start(instance, vm_ref) def power_off(self, instance): """Power off the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) vm_utils.hard_shutdown_vm(self._session, instance, vm_ref) def power_on(self, instance): """Power on the specified instance.""" vm_ref = self._get_vm_opaque_ref(instance) self._start(instance, vm_ref) def _cancel_stale_tasks(self, timeout, task): """Cancel the given tasks that are older than the given timeout.""" task_refs = self._session.call_xenapi("task.get_by_name_label", task) for task_ref in task_refs: task_rec = self._session.call_xenapi("task.get_record", task_ref) task_created = timeutils.parse_strtime(task_rec["created"].value, "%Y%m%dT%H:%M:%SZ") if timeutils.is_older_than(task_created, timeout): self._session.call_xenapi("task.cancel", task_ref) def poll_rebooting_instances(self, timeout, instances): """Look for expirable rebooting instances. - issue a "hard" reboot to any instance that has been stuck in a reboot state for >= the given timeout """ # NOTE(jk0): All existing clean_reboot tasks must be cancelled before # we can kick off the hard_reboot tasks. self._cancel_stale_tasks(timeout, 'VM.clean_reboot') ctxt = nova_context.get_admin_context() instances_info = dict(instance_count=len(instances), timeout=timeout) if instances_info["instance_count"] > 0: LOG.info(_("Found %(instance_count)d hung reboots " "older than %(timeout)d seconds") % instances_info) for instance in instances: LOG.info(_("Automatically hard rebooting"), instance=instance) self.compute_api.reboot(ctxt, instance, "HARD") def get_info(self, instance, vm_ref=None): """Return data about VM instance.""" vm_ref = vm_ref or self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) return vm_utils.compile_info(vm_rec) def get_diagnostics(self, instance): """Return data about VM diagnostics.""" vm_ref = self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) return vm_utils.compile_diagnostics(vm_rec) def _get_vif_device_map(self, vm_rec): vif_map = {} for vif in [self._session.call_xenapi("VIF.get_record", vrec) for vrec in vm_rec['VIFs']]: vif_map[vif['device']] = vif['MAC'] return vif_map def get_all_bw_counters(self): """Return running bandwidth counter for each interface on each running VM""" counters = vm_utils.fetch_bandwidth(self._session) bw = {} for vm_ref, vm_rec in vm_utils.list_vms(self._session): vif_map = self._get_vif_device_map(vm_rec) name = vm_rec['name_label'] if 'nova_uuid' not in vm_rec['other_config']: continue dom = vm_rec.get('domid') if dom is None or dom not in counters: continue vifs_bw = bw.setdefault(name, {}) for vif_num, vif_data in counters[dom].iteritems(): mac = vif_map[vif_num] vif_data['mac_address'] = mac vifs_bw[mac] = vif_data return bw def get_console_output(self, instance): """Return snapshot of console.""" # TODO(armando-migliaccio): implement this to fix pylint! return 'FAKE CONSOLE OUTPUT of instance' def get_vnc_console(self, instance): """Return connection info for a vnc console.""" try: vm_ref = self._get_vm_opaque_ref(instance) except exception.NotFound: # The compute manager expects InstanceNotFound for this case. raise exception.InstanceNotFound(instance_id=instance['uuid']) session_id = self._session.get_session_id() path = "/console?ref=%s&session_id=%s" % (str(vm_ref), session_id) # NOTE: XS5.6sp2+ use http over port 80 for xenapi com return {'host': CONF.vncserver_proxyclient_address, 'port': 80, 'internal_access_path': path} def _vif_xenstore_data(self, vif): """convert a network info vif to injectable instance data.""" def get_ip(ip): if not ip: return None return ip['address'] def fixed_ip_dict(ip, subnet): if ip['version'] == 4: netmask = str(subnet.as_netaddr().netmask) else: netmask = subnet.as_netaddr()._prefixlen return {'ip': ip['address'], 'enabled': '1', 'netmask': netmask, 'gateway': get_ip(subnet['gateway'])} def convert_route(route): return {'route': str(netaddr.IPNetwork(route['cidr']).network), 'netmask': str(netaddr.IPNetwork(route['cidr']).netmask), 'gateway': get_ip(route['gateway'])} network = vif['network'] v4_subnets = [subnet for subnet in network['subnets'] if subnet['version'] == 4] v6_subnets = [subnet for subnet in network['subnets'] if subnet['version'] == 6] # NOTE(tr3buchet): routes and DNS come from all subnets routes = [convert_route(route) for subnet in network['subnets'] for route in subnet['routes']] dns = [get_ip(ip) for subnet in network['subnets'] for ip in subnet['dns']] info_dict = {'label': network['label'], 'mac': vif['address']} if v4_subnets: # NOTE(tr3buchet): gateway and broadcast from first subnet # primary IP will be from first subnet # subnets are generally unordered :( info_dict['gateway'] = get_ip(v4_subnets[0]['gateway']) info_dict['broadcast'] = str(v4_subnets[0].as_netaddr().broadcast) info_dict['ips'] = [fixed_ip_dict(ip, subnet) for subnet in v4_subnets for ip in subnet['ips']] if v6_subnets: # NOTE(tr3buchet): gateway from first subnet # primary IP will be from first subnet # subnets are generally unordered :( info_dict['gateway_v6'] = get_ip(v6_subnets[0]['gateway']) info_dict['ip6s'] = [fixed_ip_dict(ip, subnet) for subnet in v6_subnets for ip in subnet['ips']] if routes: info_dict['routes'] = routes if dns: info_dict['dns'] = list(set(dns)) return info_dict def inject_network_info(self, instance, network_info, vm_ref=None): """ Generate the network info and make calls to place it into the xenstore and the xenstore param list. vm_ref can be passed in because it will sometimes be different than what vm_utils.lookup(session, instance['name']) will find (ex: rescue) """ vm_ref = vm_ref or self._get_vm_opaque_ref(instance) LOG.debug(_("Injecting network info to xenstore"), instance=instance) for vif in network_info: xs_data = self._vif_xenstore_data(vif) location = ('vm-data/networking/%s' % vif['address'].replace(':', '')) self._add_to_param_xenstore(vm_ref, location, jsonutils.dumps(xs_data)) try: self._write_to_xenstore(instance, location, xs_data, vm_ref=vm_ref) except KeyError: # catch KeyError for domid if instance isn't running pass def _create_vifs(self, vm_ref, instance, network_info): """Creates vifs for an instance.""" LOG.debug(_("Creating vifs"), instance=instance) # this function raises if vm_ref is not a vm_opaque_ref self._session.call_xenapi("VM.get_record", vm_ref) for device, vif in enumerate(network_info): vif_rec = self.vif_driver.plug(instance, vif, vm_ref=vm_ref, device=device) network_ref = vif_rec['network'] LOG.debug(_('Creating VIF for network %(network_ref)s'), locals(), instance=instance) vif_ref = self._session.call_xenapi('VIF.create', vif_rec) LOG.debug(_('Created VIF %(vif_ref)s, network %(network_ref)s'), locals(), instance=instance) def plug_vifs(self, instance, network_info): """Set up VIF networking on the host.""" for device, vif in enumerate(network_info): self.vif_driver.plug(instance, vif, device=device) def unplug_vifs(self, instance, network_info): if network_info: for vif in network_info: self.vif_driver.unplug(instance, vif) def reset_network(self, instance): """Calls resetnetwork method in agent.""" if self.agent_enabled: vm_ref = self._get_vm_opaque_ref(instance) agent = self._get_agent(instance, vm_ref) agent.resetnetwork() else: raise NotImplementedError() def inject_hostname(self, instance, vm_ref, hostname): """Inject the hostname of the instance into the xenstore.""" if instance['os_type'] == "windows": # NOTE(jk0): Windows hostnames can only be <= 15 chars. hostname = hostname[:15] LOG.debug(_("Injecting hostname to xenstore"), instance=instance) self._add_to_param_xenstore(vm_ref, 'vm-data/hostname', hostname) def _write_to_xenstore(self, instance, path, value, vm_ref=None): """ Writes the passed value to the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the write process. """ return self._make_plugin_call('xenstore.py', 'write_record', instance, vm_ref=vm_ref, path=path, value=jsonutils.dumps(value)) def _delete_from_xenstore(self, instance, path, vm_ref=None): """ Deletes the value from the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the delete process. """ return self._make_plugin_call('xenstore.py', 'delete_record', instance, vm_ref=vm_ref, path=path) def _make_plugin_call(self, plugin, method, instance, vm_ref=None, **addl_args): """ Abstracts out the process of calling a method of a xenapi plugin. Any errors raised by the plugin will in turn raise a RuntimeError here. """ vm_ref = vm_ref or self._get_vm_opaque_ref(instance) vm_rec = self._session.call_xenapi("VM.get_record", vm_ref) args = {'dom_id': vm_rec['domid']} args.update(addl_args) try: return self._session.call_plugin(plugin, method, args) except self._session.XenAPI.Failure, e: err_msg = e.details[-1].splitlines()[-1] if 'TIMEOUT:' in err_msg: LOG.error(_('TIMEOUT: The call to %(method)s timed out. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'timeout', 'message': err_msg} elif 'NOT IMPLEMENTED:' in err_msg: LOG.error(_('NOT IMPLEMENTED: The call to %(method)s is not' ' supported by the agent. args=%(args)r'), locals(), instance=instance) return {'returncode': 'notimplemented', 'message': err_msg} else: LOG.error(_('The call to %(method)s returned an error: %(e)s. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'error', 'message': err_msg} return None def _add_to_param_xenstore(self, vm_ref, key, val): """ Takes a key/value pair and adds it to the xenstore parameter record for the given vm instance. If the key exists in xenstore, it is overwritten """ self._remove_from_param_xenstore(vm_ref, key) self._session.call_xenapi('VM.add_to_xenstore_data', vm_ref, key, val) def _remove_from_param_xenstore(self, vm_ref, key): """ Takes a single key and removes it from the xenstore parameter record data for the given VM. If the key doesn't exist, the request is ignored. """ self._session.call_xenapi('VM.remove_from_xenstore_data', vm_ref, key) def refresh_security_group_rules(self, security_group_id): """recreates security group rules for every instance.""" self.firewall_driver.refresh_security_group_rules(security_group_id) def refresh_security_group_members(self, security_group_id): """recreates security group rules for every instance.""" self.firewall_driver.refresh_security_group_members(security_group_id) def refresh_instance_security_rules(self, instance): """recreates security group rules for specified instance.""" self.firewall_driver.refresh_instance_security_rules(instance) def refresh_provider_fw_rules(self): self.firewall_driver.refresh_provider_fw_rules() def unfilter_instance(self, instance_ref, network_info): """Removes filters for each VIF of the specified instance.""" self.firewall_driver.unfilter_instance(instance_ref, network_info=network_info) def _get_host_uuid_from_aggregate(self, context, hostname): current_aggregate = self._virtapi.aggregate_get_by_host( context, CONF.host, key=pool_states.POOL_FLAG)[0] if not current_aggregate: raise exception.AggregateHostNotFound(host=CONF.host) try: return current_aggregate.metadetails[hostname] except KeyError: reason = _('Destination host:%(hostname)s must be in the same ' 'aggregate as the source server') raise exception.MigrationError(reason=reason % locals()) def _ensure_host_in_aggregate(self, context, hostname): self._get_host_uuid_from_aggregate(context, hostname) def _get_host_opaque_ref(self, context, hostname): host_uuid = self._get_host_uuid_from_aggregate(context, hostname) return self._session.call_xenapi("host.get_by_uuid", host_uuid) def _migrate_receive(self, ctxt): destref = self._session.get_xenapi_host() # Get the network to for migrate. # This is the one associated with the pif marked management. From cli: # uuid=`xe pif-list --minimal management=true` # xe pif-param-get param-name=network-uuid uuid=$uuid expr = 'field "management" = "true"' pifs = self._session.call_xenapi('PIF.get_all_records_where', expr) if len(pifs) != 1: raise exception.MigrationError('No suitable network for migrate') nwref = pifs[pifs.keys()[0]]['network'] try: options = {} migrate_data = self._session.call_xenapi("host.migrate_receive", destref, nwref, options) except self._session.XenAPI.Failure as exc: LOG.exception(exc) raise exception.MigrationError(_('Migrate Receive failed')) return migrate_data def check_can_live_migrate_destination(self, ctxt, instance_ref, block_migration=False, disk_over_commit=False): """Check if it is possible to execute live migration. :param context: security context :param instance_ref: nova.db.sqlalchemy.models.Instance object :param block_migration: if true, prepare for block migration :param disk_over_commit: if true, allow disk over commit """ if block_migration: migrate_send_data = self._migrate_receive(ctxt) destination_sr_ref = vm_utils.safe_find_sr(self._session) dest_check_data = { "block_migration": block_migration, "migrate_data": {"migrate_send_data": migrate_send_data, "destination_sr_ref": destination_sr_ref}} return dest_check_data else: src = instance_ref['host'] self._ensure_host_in_aggregate(ctxt, src) # TODO(johngarbutt) we currently assume # instance is on a SR shared with other destination # block migration work will be able to resolve this return None def check_can_live_migrate_source(self, ctxt, instance_ref, dest_check_data): """Check if it's possible to execute live migration on the source side. :param context: security context :param instance_ref: nova.db.sqlalchemy.models.Instance object :param dest_check_data: data returned by the check on the destination, includes block_migration flag """ if dest_check_data and 'migrate_data' in dest_check_data: vm_ref = self._get_vm_opaque_ref(instance_ref) migrate_data = dest_check_data['migrate_data'] try: self._call_live_migrate_command( "VM.assert_can_migrate", vm_ref, migrate_data) return dest_check_data except self._session.XenAPI.Failure as exc: LOG.exception(exc) raise exception.MigrationError(_('VM.assert_can_migrate' 'failed')) def _generate_vdi_map(self, destination_sr_ref, vm_ref): """generate a vdi_map for _call_live_migrate_command.""" sr_ref = vm_utils.safe_find_sr(self._session) vm_vdis = vm_utils.get_instance_vdis_for_sr(self._session, vm_ref, sr_ref) return dict((vdi, destination_sr_ref) for vdi in vm_vdis) def _call_live_migrate_command(self, command_name, vm_ref, migrate_data): """unpack xapi specific parameters, and call a live migrate command.""" destination_sr_ref = migrate_data['destination_sr_ref'] migrate_send_data = migrate_data['migrate_send_data'] vdi_map = self._generate_vdi_map(destination_sr_ref, vm_ref) vif_map = {} options = {} self._session.call_xenapi(command_name, vm_ref, migrate_send_data, True, vdi_map, vif_map, options) def live_migrate(self, context, instance, destination_hostname, post_method, recover_method, block_migration, migrate_data=None): try: vm_ref = self._get_vm_opaque_ref(instance) if block_migration: if not migrate_data: raise exception.InvalidParameterValue('Block Migration ' 'requires migrate data from destination') try: self._call_live_migrate_command( "VM.migrate_send", vm_ref, migrate_data) except self._session.XenAPI.Failure as exc: LOG.exception(exc) raise exception.MigrationError(_('Migrate Send failed')) else: host_ref = self._get_host_opaque_ref(context, destination_hostname) self._session.call_xenapi("VM.pool_migrate", vm_ref, host_ref, {}) post_method(context, instance, destination_hostname, block_migration) except Exception: with excutils.save_and_reraise_exception(): recover_method(context, instance, destination_hostname, block_migration) def get_per_instance_usage(self): """Get usage info about each active instance.""" usage = {} def _is_active(vm_rec): power_state = vm_rec['power_state'].lower() return power_state in ['running', 'paused'] def _get_uuid(vm_rec): other_config = vm_rec['other_config'] return other_config.get('nova_uuid', None) for vm_ref, vm_rec in vm_utils.list_vms(self._session): uuid = _get_uuid(vm_rec) if _is_active(vm_rec) and uuid is not None: memory_mb = int(vm_rec['memory_static_max']) / 1024 / 1024 usage[uuid] = {'memory_mb': memory_mb, 'uuid': uuid} return usage
apache-2.0
sullivat/Markov-Twitter-Bot
src/mybot.test.py
1
1257
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime as dt import logging import time import tweepy from tweet_builder import * from credentials import * # Housekeeping: do not edit logging.basicConfig(filename='tweet_test.log', level=logging.DEBUG) auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth) INTERVALS = [1, 1, 1, 5, 10] # What the bot will tweet def gen_tweet(): """Generate a tweet from markovify.""" return str(create_tweet(authors[pick_author()])) def is_tweet_safe(tweet): """using Mark Twain text inevitably leads to tweets with offensive langueage""" vulgarities = ['nigger', 'fuck'] for vulg in vulgarities: if vulg in tweet.lower(): return False else: return True def main_no_tweet(): while True: t = gen_tweet() if is_tweet_safe(t): # api.update_status(t) # DON'T TWEET logging.info("On {0} -- Tweeted: {1}".format(dt.datetime.today(), t)) time.sleep(random.choice(INTERVALS)) print("Tweeting: {}".format(t)) print('...\nAll done!') if __name__ == '__main__': #main() main_no_tweet()
bsd-2-clause
devGregA/code
scrapy/tests/test_middleware.py
43
2341
from twisted.trial import unittest from scrapy.settings import Settings from scrapy.exceptions import NotConfigured from scrapy.middleware import MiddlewareManager class M1(object): def open_spider(self, spider): pass def close_spider(self, spider): pass def process(self, response, request, spider): pass class M2(object): def open_spider(self, spider): pass def close_spider(self, spider): pass pass class M3(object): def process(self, response, request, spider): pass class MOff(object): def open_spider(self, spider): pass def close_spider(self, spider): pass def __init__(self): raise NotConfigured class TestMiddlewareManager(MiddlewareManager): @classmethod def _get_mwlist_from_settings(cls, settings): return ['scrapy.tests.test_middleware.%s' % x for x in ['M1', 'MOff', 'M3']] def _add_middleware(self, mw): super(TestMiddlewareManager, self)._add_middleware(mw) if hasattr(mw, 'process'): self.methods['process'].append(mw.process) class MiddlewareManagerTest(unittest.TestCase): def test_init(self): m1, m2, m3 = M1(), M2(), M3() mwman = TestMiddlewareManager(m1, m2, m3) self.assertEqual(mwman.methods['open_spider'], [m1.open_spider, m2.open_spider]) self.assertEqual(mwman.methods['close_spider'], [m2.close_spider, m1.close_spider]) self.assertEqual(mwman.methods['process'], [m1.process, m3.process]) def test_methods(self): mwman = TestMiddlewareManager(M1(), M2(), M3()) self.assertEqual([x.im_class for x in mwman.methods['open_spider']], [M1, M2]) self.assertEqual([x.im_class for x in mwman.methods['close_spider']], [M2, M1]) self.assertEqual([x.im_class for x in mwman.methods['process']], [M1, M3]) def test_enabled(self): m1, m2, m3 = M1(), M2(), M3() mwman = MiddlewareManager(m1, m2, m3) self.failUnlessEqual(mwman.middlewares, (m1, m2, m3)) def test_enabled_from_settings(self): settings = Settings() mwman = TestMiddlewareManager.from_settings(settings) classes = [x.__class__ for x in mwman.middlewares] self.failUnlessEqual(classes, [M1, M3])
bsd-3-clause
devs4v/devs4v-information-retrieval15
project/venv/lib/python2.7/site-packages/django/db/models/fields/files.py
58
19311
import datetime import os import warnings from inspect import getargspec from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import default_storage from django.db.models import signals from django.db.models.fields import Field from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_str, force_text from django.utils.translation import ugettext_lazy as _ class FieldFile(File): def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) def _get_file(self): self._require_file() if not hasattr(self, '_file') or self._file is None: self._file = self.storage.open(self.name, 'rb') return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) def _get_path(self): self._require_file() return self.storage.path(self.name) path = property(_get_path) def _get_url(self): self._require_file() return self.storage.url(self.name) url = property(_get_url) def _get_size(self): self._require_file() if not self._committed: return self.file.size return self.storage.size(self.name) size = property(_get_size) def open(self, mode='rb'): self._require_file() self.file.open(mode) # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) args, varargs, varkw, defaults = getargspec(self.storage.save) if 'max_length' in args: self.name = self.storage.save(name, content, max_length=self.field.max_length) else: warnings.warn( 'Backwards compatibility for storage backends without ' 'support for the `max_length` argument in ' 'Storage.save() will be removed in Django 2.0.', RemovedInDjango20Warning, stacklevel=2 ) self.name = self.storage.save(name, content) setattr(self.instance, self.field.name, self.name) # Update the filesize cache self._size = content.size self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): if not self: return # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.name, self.name) # Delete the filesize cache if hasattr(self, '_size'): del self._size self._committed = False if save: self.instance.save() delete.alters_data = True def _get_closed(self): file = getattr(self, '_file', None) return file is None or file.closed closed = property(_get_closed) def close(self): file = getattr(self, '_file', None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field and an instance # it's attached to in order to work properly, but the only necessary # data to be pickled is the file's name itself. Everything else will # be restored later, by FileDescriptor below. return {'name': self.name, 'closed': False, '_committed': True, '_file': None} class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size Assigns a file object on assignment so you can do:: >>> with open('/tmp/hello.world', 'r') as f: ... instance.file = File(f) """ def __init__(self, field): self.field = field def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) # This is slightly complicated, so worth an explanation. # instance.file`needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = instance.__dict__[self.field.name] # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, six.string_types) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.name] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to them. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, 'field'): file.instance = instance file.field = self.field file.storage = self.field.storage # That was fun, wasn't it? return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File") def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): self._primary_key_set_explicitly = 'primary_key' in kwargs self._unique_set_explicitly = 'unique' in kwargs self.storage = storage or default_storage self.upload_to = upload_to if callable(upload_to): self.generate_filename = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super(FileField, self).check(**kwargs) errors.extend(self._check_unique()) errors.extend(self._check_primary_key()) return errors def _check_unique(self): if self._unique_set_explicitly: return [ checks.Error( "'unique' is not a valid argument for a %s." % self.__class__.__name__, hint=None, obj=self, id='fields.E200', ) ] else: return [] def _check_primary_key(self): if self._primary_key_set_explicitly: return [ checks.Error( "'primary_key' is not a valid argument for a %s." % self.__class__.__name__, hint=None, obj=self, id='fields.E201', ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super(FileField, self).deconstruct() if kwargs.get("max_length", None) == 100: del kwargs["max_length"] kwargs['upload_to'] = self.upload_to if self.storage is not default_storage: kwargs['storage'] = self.storage return name, path, args, kwargs def get_internal_type(self): return "FileField" def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'name'): value = value.name return super(FileField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = super(FileField, self).get_prep_value(value) # Need to convert File objects provided via a form to unicode for database insertion if value is None: return None return six.text_type(value) def pre_save(self, model_instance, add): "Returns field's value just before saving." file = super(FileField, self).pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file, save=False) return file def contribute_to_class(self, cls, name, **kwargs): super(FileField, self).contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, self.descriptor_class(self)) def get_directory_name(self): return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to)))) def get_filename(self, filename): return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) def generate_filename(self, instance, filename): return os.path.join(self.get_directory_name(), self.get_filename(filename)) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to unicode and stored in the # database, so leaving False as-is is not acceptable. if not data: data = '' setattr(instance, self.name, data) def formfield(self, **kwargs): defaults = {'form_class': forms.FileField, 'max_length': self.max_length} # If a file has been provided previously, then the form doesn't require # that a new file is provided this time. # The code to mark the form field as not required is used by # form_for_instance, but can probably be removed once form_for_instance # is gone. ModelForm uses a different method to check for an existing file. if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return super(FileField, self).formfield(**defaults) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field super(ImageField, self).__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super(ImageField, self).check(**kwargs) errors.extend(self._check_image_library_installed()) return errors def _check_image_library_installed(self): try: from PIL import Image # NOQA except ImportError: return [ checks.Error( 'Cannot use ImageField because Pillow is not installed.', hint=('Get Pillow at https://pypi.python.org/pypi/Pillow ' 'or run command "pip install Pillow".'), obj=self, id='fields.E210', ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super(ImageField, self).deconstruct() if self.width_field: kwargs['width_field'] = self.width_field if self.height_field: kwargs['height_field'] = self.height_field return name, path, args, kwargs def contribute_to_class(self, cls, name, **kwargs): super(ImageField, self).contribute_to_class(cls, name, **kwargs) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. # Only run post-initialization dimension update on non-abstract models if not cls._meta.abstract: signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Updates field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field doesn't have dimension fields. has_dimension_fields = self.width_field or self.height_field if not has_dimension_fields: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) return super(ImageField, self).formfield(**defaults)
mit
alphagov/notifications-api
migrations/versions/0151_refactor_letter_rates.py
1
3140
""" Revision ID: 0151_refactor_letter_rates Revises: 0150_another_letter_org Create Date: 2017-12-05 10:24:41.232128 """ import uuid from datetime import datetime from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = '0151_refactor_letter_rates' down_revision = '0150_another_letter_org' def upgrade(): op.drop_table('letter_rate_details') op.drop_table('letter_rates') op.create_table('letter_rates', sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False), sa.Column('start_date', sa.DateTime(), nullable=False), sa.Column('end_date', sa.DateTime(), nullable=True), sa.Column('sheet_count', sa.Integer(), nullable=False), sa.Column('rate', sa.Numeric(), nullable=False), sa.Column('crown', sa.Boolean(), nullable=False), sa.Column('post_class', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id') ) start_date = datetime(2016, 3, 31, 23, 00, 00) op.execute("insert into letter_rates values('{}', '{}', null, 1, 0.30, True, 'second')".format( str(uuid.uuid4()), start_date) ) op.execute("insert into letter_rates values('{}', '{}', null, 2, 0.33, True, 'second')".format( str(uuid.uuid4()), start_date) ) op.execute("insert into letter_rates values('{}', '{}', null, 3, 0.36, True, 'second')".format( str(uuid.uuid4()), start_date) ) op.execute("insert into letter_rates values('{}', '{}', null, 1, 0.33, False, 'second')".format( str(uuid.uuid4()), start_date) ) op.execute("insert into letter_rates values('{}', '{}', null, 2, 0.39, False, 'second')".format( str(uuid.uuid4()), start_date) ) op.execute("insert into letter_rates values('{}', '{}', null, 3, 0.45, False, 'second')".format( str(uuid.uuid4()), start_date) ) def downgrade(): op.drop_table('letter_rates') op.create_table('letter_rates', sa.Column('id', postgresql.UUID(), autoincrement=False, nullable=False), sa.Column('valid_from', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.PrimaryKeyConstraint('id', name='letter_rates_pkey'), postgresql_ignore_search_path=False ) op.create_table('letter_rate_details', sa.Column('id', postgresql.UUID(), autoincrement=False, nullable=False), sa.Column('letter_rate_id', postgresql.UUID(), autoincrement=False, nullable=False), sa.Column('page_total', sa.INTEGER(), autoincrement=False, nullable=False), sa.Column('rate', sa.NUMERIC(), autoincrement=False, nullable=False), sa.ForeignKeyConstraint(['letter_rate_id'], ['letter_rates.id'], name='letter_rate_details_letter_rate_id_fkey'), sa.PrimaryKeyConstraint('id', name='letter_rate_details_pkey') )
mit
mat12/mytest
lib/python/Plugins/SystemPlugins/PositionerSetup/rotor_calc.py
103
3251
import math f = 1.00 / 298.257 # Earth flattning factor r_sat = 42164.57 # Distance from earth centre to satellite r_eq = 6378.14 # Earth radius def calcElevation(SatLon, SiteLat, SiteLon, Height_over_ocean = 0): a0 = 0.58804392 a1 = -0.17941557 a2 = 0.29906946E-1 a3 = -0.25187400E-2 a4 = 0.82622101E-4 sinRadSiteLat = math.sin(math.radians(SiteLat)) cosRadSiteLat = math.cos(math.radians(SiteLat)) Rstation = r_eq / (math.sqrt( 1.00 - f * (2.00 - f) * sinRadSiteLat **2)) Ra = (Rstation + Height_over_ocean) * cosRadSiteLat Rz = Rstation * (1.00 - f) * (1.00 - f) * sinRadSiteLat alfa_rx = r_sat * math.cos(math.radians(SatLon - SiteLon)) - Ra alfa_ry = r_sat * math.sin(math.radians(SatLon - SiteLon)) alfa_rz = -Rz alfa_r_north = -alfa_rx * sinRadSiteLat + alfa_rz * cosRadSiteLat alfa_r_zenith = alfa_rx * cosRadSiteLat + alfa_rz * sinRadSiteLat den = alfa_r_north **2 + alfa_ry **2 if den > 0: El_geometric = math.degrees(math.atan(alfa_r_zenith / math.sqrt(den))) else: El_geometric = 90 x = math.fabs(El_geometric + 0.589) refraction = math.fabs(a0 + (a1 + (a2 + (a3 + a4 * x) * x) * x) * x) if El_geometric > 10.2: El_observed = El_geometric + 0.01617 * (math.cos(math.radians(math.fabs(El_geometric)))/math.sin(math.radians(math.fabs(El_geometric))) ) else: El_observed = El_geometric + refraction if alfa_r_zenith < -3000: El_observed = -99 return El_observed def calcAzimuth(SatLon, SiteLat, SiteLon, Height_over_ocean = 0): def rev(number): return number - math.floor(number / 360.0) * 360 sinRadSiteLat = math.sin(math.radians(SiteLat)) cosRadSiteLat = math.cos(math.radians(SiteLat)) Rstation = r_eq / (math.sqrt(1 - f * (2 - f) * sinRadSiteLat **2)) Ra = (Rstation + Height_over_ocean) * cosRadSiteLat Rz = Rstation * (1 - f) ** 2 * sinRadSiteLat alfa_rx = r_sat * math.cos(math.radians(SatLon - SiteLon)) - Ra alfa_ry = r_sat * math.sin(math.radians(SatLon - SiteLon)) alfa_rz = -Rz alfa_r_north = -alfa_rx * sinRadSiteLat + alfa_rz * cosRadSiteLat if alfa_r_north < 0: Azimuth = 180 + math.degrees(math.atan(alfa_ry / alfa_r_north)) elif alfa_r_north > 0: Azimuth = rev(360 + math.degrees(math.atan(alfa_ry / alfa_r_north))) else: Azimuth = 0 return Azimuth def calcDeclination(SiteLat, Azimuth, Elevation): return math.degrees(math.asin(math.sin(math.radians(Elevation)) * \ math.sin(math.radians(SiteLat)) + \ math.cos(math.radians(Elevation)) * \ math.cos(math.radians(SiteLat)) + \ math.cos(math.radians(Azimuth)) \ )) def calcSatHourangle(SatLon, SiteLat, SiteLon): Azimuth = calcAzimuth(SatLon, SiteLat, SiteLon ) Elevation = calcElevation(SatLon, SiteLat, SiteLon) a = - math.cos(math.radians(Elevation)) * math.sin(math.radians(Azimuth)) b = math.sin(math.radians(Elevation)) * math.cos(math.radians(SiteLat)) - \ math.cos(math.radians(Elevation)) * math.sin(math.radians(SiteLat)) * \ math.cos(math.radians(Azimuth)) # Works for all azimuths (northern & southern hemisphere) returnvalue = 180 + math.degrees(math.atan(a / b)) if Azimuth > 270: returnvalue += 180 if returnvalue > 360: returnvalue = 720 - returnvalue if Azimuth < 90: returnvalue = 180 - returnvalue return returnvalue
gpl-2.0
jpscaletti/rev-assets
rev_assets/__init__.py
1
1570
""" =========================== RevAssets =========================== Makes possible for python web apps to work with hashed static assets generated by other tools like Gulp or Webpack. It does so by reading the manifest generated by the revision tool. """ import json import io __version__ = '1.0.3' class AssetNotFound(Exception): pass class RevAssets(object): """ Map the source -> hashed assets :param base_url: From where the hashed assets are served. :param reload: Reload the manifest each time an asset is requested. :param manifest: Path and filename of the manifest file. :param quiet: If False, a missing asset will raise an exception """ def __init__(self, base_url='/static', reload=False, manifest='manifest.json', quiet=True): self.base_url = base_url.rstrip('/') self.reload = reload self.manifest = manifest self.assets = {} self.quiet = quiet def _load_manifest(self): with io.open(self.manifest, 'rt', encoding='utf-8') as mf: return json.loads(mf.read()) def asset_url(self, asset): if not self.assets or self.reload: self.assets = self._load_manifest() asset = asset.strip('/') path = self.assets.get(asset) if not path: if self.quiet: return '' msg = 'Asset file {!r} not found'.format(asset) raise AssetNotFound(msg) return '{}/{}'.format( self.base_url, path.lstrip('/'), )
bsd-3-clause
vikas1885/test1
lms/djangoapps/mobile_api/test_milestones.py
80
5550
""" Milestone related tests for the mobile_api """ from mock import patch from courseware.access_response import MilestoneError from courseware.tests.helpers import get_request_for_user from courseware.tests.test_entrance_exam import answer_entrance_exam_problem, add_entrance_exam_milestone from util.milestones_helpers import ( add_prerequisite_course, fulfill_course_milestone, seed_milestone_relationship_types, ) from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory class MobileAPIMilestonesMixin(object): """ Tests the Mobile API decorators for milestones. The two milestones currently supported in these tests are entrance exams and pre-requisite courses. If either of these milestones are unfulfilled, the mobile api will appropriately block content until the milestone is fulfilled. """ ALLOW_ACCESS_TO_MILESTONE_COURSE = False # pylint: disable=invalid-name @patch.dict('django.conf.settings.FEATURES', {'ENABLE_PREREQUISITE_COURSES': True, 'MILESTONES_APP': True}) def test_unfulfilled_prerequisite_course(self): """ Tests the case for an unfulfilled pre-requisite course """ self._add_prerequisite_course() self.init_course_access() self._verify_unfulfilled_milestone_response() @patch.dict('django.conf.settings.FEATURES', {'ENABLE_PREREQUISITE_COURSES': True, 'MILESTONES_APP': True}) def test_unfulfilled_prerequisite_course_for_staff(self): self._add_prerequisite_course() self.user.is_staff = True self.user.save() self.init_course_access() self.api_response() @patch.dict('django.conf.settings.FEATURES', {'ENABLE_PREREQUISITE_COURSES': True, 'MILESTONES_APP': True}) def test_fulfilled_prerequisite_course(self): """ Tests the case when a user fulfills existing pre-requisite course """ self._add_prerequisite_course() add_prerequisite_course(self.course.id, self.prereq_course.id) fulfill_course_milestone(self.prereq_course.id, self.user) self.init_course_access() self.api_response() @patch.dict('django.conf.settings.FEATURES', {'ENTRANCE_EXAMS': True, 'MILESTONES_APP': True}) def test_unpassed_entrance_exam(self): """ Tests the case where the user has not passed the entrance exam """ self._add_entrance_exam() self.init_course_access() self._verify_unfulfilled_milestone_response() @patch.dict('django.conf.settings.FEATURES', {'ENTRANCE_EXAMS': True, 'MILESTONES_APP': True}) def test_unpassed_entrance_exam_for_staff(self): self._add_entrance_exam() self.user.is_staff = True self.user.save() self.init_course_access() self.api_response() @patch.dict('django.conf.settings.FEATURES', {'ENTRANCE_EXAMS': True, 'MILESTONES_APP': True}) def test_passed_entrance_exam(self): """ Tests access when user has passed the entrance exam """ self._add_entrance_exam() self._pass_entrance_exam() self.init_course_access() self.api_response() def _add_entrance_exam(self): """ Sets up entrance exam """ seed_milestone_relationship_types() self.course.entrance_exam_enabled = True self.entrance_exam = ItemFactory.create( # pylint: disable=attribute-defined-outside-init parent=self.course, category="chapter", display_name="Entrance Exam Chapter", is_entrance_exam=True, in_entrance_exam=True ) self.problem_1 = ItemFactory.create( # pylint: disable=attribute-defined-outside-init parent=self.entrance_exam, category='problem', display_name="The Only Exam Problem", graded=True, in_entrance_exam=True ) add_entrance_exam_milestone(self.course, self.entrance_exam) self.course.entrance_exam_minimum_score_pct = 0.50 self.course.entrance_exam_id = unicode(self.entrance_exam.location) modulestore().update_item(self.course, self.user.id) def _add_prerequisite_course(self): """ Helper method to set up the prerequisite course """ seed_milestone_relationship_types() self.prereq_course = CourseFactory.create() # pylint: disable=attribute-defined-outside-init add_prerequisite_course(self.course.id, self.prereq_course.id) def _pass_entrance_exam(self): """ Helper function to pass the entrance exam """ request = get_request_for_user(self.user) answer_entrance_exam_problem(self.course, request, self.problem_1) def _verify_unfulfilled_milestone_response(self): """ Verifies the response depending on ALLOW_ACCESS_TO_MILESTONE_COURSE Since different endpoints will have different behaviours towards milestones, setting ALLOW_ACCESS_TO_MILESTONE_COURSE (default is False) to True, will not return a 404. For example, when getting a list of courses a user is enrolled in, although a user may have unfulfilled milestones, the course should still show up in the course enrollments list. """ if self.ALLOW_ACCESS_TO_MILESTONE_COURSE: self.api_response() else: response = self.api_response(expected_response_code=404) self.assertEqual(response.data, MilestoneError().to_json())
agpl-3.0
mpetyx/palmdrop
venv/lib/python2.7/site-packages/cms/migrations/0017_author_removed.py
385
19523
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Dummy migration pass def backwards(self, orm): # Dummy migration pass models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': { 'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ( 'django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ( 'django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ( 'django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.globalpagepermission': { 'Meta': {'object_name': 'GlobalPagePermission'}, 'can_add': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_moderate': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_recover_page': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sites': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['sites.Site']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.page': { 'Meta': {'ordering': "('site', 'tree_id', 'lft')", 'object_name': 'Page'}, 'changed_by': ( 'django.db.models.fields.CharField', [], {'max_length': '70'}), 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'created_by': ( 'django.db.models.fields.CharField', [], {'max_length': '70'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_navigation': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'limit_visibility_in_menu': ( 'django.db.models.fields.SmallIntegerField', [], {'default': 'None', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'login_required': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'moderator_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'blank': 'True'}), 'navigation_extenders': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}), 'placeholders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cms.Placeholder']", 'symmetrical': 'False'}), 'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'publication_end_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'published': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'publisher_public': ( 'django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Page']"}), 'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}), 'reverse_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '40', 'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}), 'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'template': ( 'django.db.models.fields.CharField', [], {'max_length': '100'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.pagemoderator': { 'Meta': {'object_name': 'PageModerator'}, 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moderate_children': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'moderate_descendants': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'moderate_page': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'cms.pagemoderatorstate': { 'Meta': {'ordering': "('page', 'action', '-created')", 'object_name': 'PageModeratorState'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}) }, 'cms.pagepermission': { 'Meta': {'object_name': 'PagePermission'}, 'can_add': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_change_advanced_settings': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_change_permissions': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_delete': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_moderate': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_move_page': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_publish': ( 'django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_view': ( 'django.db.models.fields.BooleanField', [], {'default': 'False'}), 'grant_on': ( 'django.db.models.fields.IntegerField', [], {'default': '5'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Page']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'cms.pageuser': { 'Meta': {'object_name': 'PageUser', '_ormbases': ['auth.User']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_users'", 'to': "orm['auth.User']"}), 'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.pageusergroup': { 'Meta': {'object_name': 'PageUserGroup', '_ormbases': ['auth.Group']}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_usergroups'", 'to': "orm['auth.User']"}), 'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ( 'django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}) }, 'cms.title': { 'Meta': {'unique_together': "(('language', 'page'),)", 'object_name': 'Title'}, 'application_urls': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'has_url_overwrite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'menu_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'meta_description': ('django.db.models.fields.TextField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'meta_keywords': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'title_set'", 'to': "orm['cms.Page']"}), 'page_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'redirect': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'slug': ( 'django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ( 'django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ( 'django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ( 'django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ( 'django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['cms']
apache-2.0
frankiecjunle/yunblog
venv/lib/python2.7/site-packages/mako/filters.py
61
6003
# mako/filters.py # Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file> # # This module is part of Mako and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import re import codecs from mako.compat import quote_plus, unquote_plus, codepoint2name, \ name2codepoint from mako import compat xml_escapes = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&#34;', # also &quot; in html-only "'": '&#39;' # also &apos; in html-only } # XXX: &quot; is valid in HTML and XML # &apos; is not valid HTML, but is valid XML def legacy_html_escape(s): """legacy HTML escape for non-unicode mode.""" s = s.replace("&", "&amp;") s = s.replace(">", "&gt;") s = s.replace("<", "&lt;") s = s.replace('"', "&#34;") s = s.replace("'", "&#39;") return s try: import markupsafe html_escape = markupsafe.escape except ImportError: html_escape = legacy_html_escape def xml_escape(string): return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string) def url_escape(string): # convert into a list of octets string = string.encode("utf8") return quote_plus(string) def legacy_url_escape(string): # convert into a list of octets return quote_plus(string) def url_unescape(string): text = unquote_plus(string) if not is_ascii_str(text): text = text.decode("utf8") return text def trim(string): return string.strip() class Decode(object): def __getattr__(self, key): def decode(x): if isinstance(x, compat.text_type): return x elif not isinstance(x, compat.binary_type): return decode(str(x)) else: return compat.text_type(x, encoding=key) return decode decode = Decode() _ASCII_re = re.compile(r'\A[\x00-\x7f]*\Z') def is_ascii_str(text): return isinstance(text, str) and _ASCII_re.match(text) ################################################################ class XMLEntityEscaper(object): def __init__(self, codepoint2name, name2codepoint): self.codepoint2entity = dict([(c, compat.text_type('&%s;' % n)) for c, n in codepoint2name.items()]) self.name2codepoint = name2codepoint def escape_entities(self, text): """Replace characters with their character entity references. Only characters corresponding to a named entity are replaced. """ return compat.text_type(text).translate(self.codepoint2entity) def __escape(self, m): codepoint = ord(m.group()) try: return self.codepoint2entity[codepoint] except (KeyError, IndexError): return '&#x%X;' % codepoint __escapable = re.compile(r'["&<>]|[^\x00-\x7f]') def escape(self, text): """Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII. """ return self.__escapable.sub(self.__escape, compat.text_type(text) ).encode('ascii') # XXX: This regexp will not match all valid XML entity names__. # (It punts on details involving involving CombiningChars and Extenders.) # # .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef __characterrefs = re.compile(r'''& (?: \#(\d+) | \#x([\da-f]+) | ( (?!\d) [:\w] [-.:\w]+ ) ) ;''', re.X | re.UNICODE) def __unescape(self, m): dval, hval, name = m.groups() if dval: codepoint = int(dval) elif hval: codepoint = int(hval, 16) else: codepoint = self.name2codepoint.get(name, 0xfffd) # U+FFFD = "REPLACEMENT CHARACTER" if codepoint < 128: return chr(codepoint) return chr(codepoint) def unescape(self, text): """Unescape character references. All character references (both entity references and numerical character references) are unescaped. """ return self.__characterrefs.sub(self.__unescape, text) _html_entities_escaper = XMLEntityEscaper(codepoint2name, name2codepoint) html_entities_escape = _html_entities_escaper.escape_entities html_entities_unescape = _html_entities_escaper.unescape def htmlentityreplace_errors(ex): """An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') 'The cost was &euro;12.' """ if isinstance(ex, UnicodeEncodeError): # Handle encoding errors bad_text = ex.object[ex.start:ex.end] text = _html_entities_escaper.escape(bad_text) return (compat.text_type(text), ex.end) raise ex codecs.register_error('htmlentityreplace', htmlentityreplace_errors) # TODO: options to make this dynamic per-compilation will be added in a later # release DEFAULT_ESCAPES = { 'x': 'filters.xml_escape', 'h': 'filters.html_escape', 'u': 'filters.url_escape', 'trim': 'filters.trim', 'entity': 'filters.html_entities_escape', 'unicode': 'unicode', 'decode': 'decode', 'str': 'str', 'n': 'n' } if compat.py3k: DEFAULT_ESCAPES.update({ 'unicode': 'str' }) NON_UNICODE_ESCAPES = DEFAULT_ESCAPES.copy() NON_UNICODE_ESCAPES['h'] = 'filters.legacy_html_escape' NON_UNICODE_ESCAPES['u'] = 'filters.legacy_url_escape'
mit
titilambert/alignak
alignak/macroresolver.py
2
23875
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors # # This file is part of Alignak. # # Alignak 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. # # Alignak 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 Alignak. If not, see <http://www.gnu.org/licenses/>. # # # This file incorporates work covered by the following copyright and # permission notice: # # Copyright (C) 2009-2014: # Hartmut Goebel, h.goebel@goebel-consult.de # Nicolas Dupeux, nicolas@dupeux.net # Gerhard Lausser, gerhard.lausser@consol.de # Grégory Starck, g.starck@gmail.com # Frédéric Pégé, frederic.pege@gmail.com # Sebastien Coavoux, s.coavoux@free.fr # Olivier Hanesse, olivier.hanesse@gmail.com # Jean Gabes, naparuba@gmail.com # Zoran Zaric, zz@zoranzaric.de # David Gil, david.gil.marcos@gmail.com # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>. """ This class resolve Macro in commands by looking at the macros list in Class of elements. It give a property that call be callable or not. It not callable, it's a simple property and replace the macro with the value If callable, it's a method that is called to get the value. for example, to get the number of service in a host, you call a method to get the len(host.services) """ import re import time from alignak.borg import Borg class MacroResolver(Borg): """MacroResolver class is used to resolve macros (in command call). See above for details""" my_type = 'macroresolver' # Global macros macros = { 'TOTALHOSTSUP': '_get_total_hosts_up', 'TOTALHOSTSDOWN': '_get_total_hosts_down', 'TOTALHOSTSUNREACHABLE': '_get_total_hosts_unreachable', 'TOTALHOSTSDOWNUNHANDLED': '_get_total_hosts_unhandled', 'TOTALHOSTSUNREACHABLEUNHANDLED': '_get_total_hosts_unreachable_unhandled', 'TOTALHOSTPROBLEMS': '_get_total_host_problems', 'TOTALHOSTPROBLEMSUNHANDLED': '_get_total_host_problems_unhandled', 'TOTALSERVICESOK': '_get_total_service_ok', 'TOTALSERVICESWARNING': '_get_total_services_warning', 'TOTALSERVICESCRITICAL': '_get_total_services_critical', 'TOTALSERVICESUNKNOWN': '_get_total_services_unknown', 'TOTALSERVICESWARNINGUNHANDLED': '_get_total_services_warning_unhandled', 'TOTALSERVICESCRITICALUNHANDLED': '_get_total_services_critical_unhandled', 'TOTALSERVICESUNKNOWNUNHANDLED': '_get_total_services_unknown_unhandled', 'TOTALSERVICEPROBLEMS': '_get_total_service_problems', 'TOTALSERVICEPROBLEMSUNHANDLED': '_get_total_service_problems_unhandled', 'LONGDATETIME': '_get_long_date_time', 'SHORTDATETIME': '_get_short_date_time', 'DATE': '_get_date', 'TIME': '_get_time', 'TIMET': '_get_timet', 'PROCESSSTARTTIME': '_get_process_start_time', 'EVENTSTARTTIME': '_get_events_start_time', } output_macros = [ 'HOSTOUTPUT', 'HOSTPERFDATA', 'HOSTACKAUTHOR', 'HOSTACKCOMMENT', 'SERVICEOUTPUT', 'SERVICEPERFDATA', 'SERVICEACKAUTHOR', 'SERVICEACKCOMMENT' ] def init(self, conf): """Init macroresolver instance with conf. Must be called once. :param conf: conf to load :type conf: :return: None """ # For searching class and elements for ondemand # we need link to types self.conf = conf self.lists_on_demand = [] self.hosts = conf.hosts # For special void host_name handling... self.host_class = self.hosts.inner_class self.lists_on_demand.append(self.hosts) self.services = conf.services self.contacts = conf.contacts self.lists_on_demand.append(self.contacts) self.hostgroups = conf.hostgroups self.lists_on_demand.append(self.hostgroups) self.commands = conf.commands self.servicegroups = conf.servicegroups self.lists_on_demand.append(self.servicegroups) self.contactgroups = conf.contactgroups self.lists_on_demand.append(self.contactgroups) self.illegal_macro_output_chars = conf.illegal_macro_output_chars # Try cache :) # self.cache = {} def _get_macros(self, chain): """Get all macros of a chain Cut '$' char and create a dict with the following structure:: { 'MacroSTR1' : {'val': '', 'type': 'unknown'} 'MacroSTR2' : {'val': '', 'type': 'unknown'} } :param chain: chain to parse :type chain: str :return: dict with macro parsed as key :rtype: dict """ # if chain in self.cache: # return self.cache[chain] regex = re.compile(r'(\$)') elts = regex.split(chain) macros = {} in_macro = False for elt in elts: if elt == '$': in_macro = not in_macro elif in_macro: macros[elt] = {'val': '', 'type': 'unknown'} # self.cache[chain] = macros if '' in macros: del macros[''] return macros def _get_value_from_element(self, elt, prop): """Get value from a element's property the property may be a function to call. :param elt: element :type elt: object :param prop: element property :type prop: str :return: getattr(elt, prop) or getattr(elt, prop)() (call) :rtype: str """ try: value = getattr(elt, prop) if callable(value): return unicode(value()) else: return unicode(value) except AttributeError, exp: # Return no value return '' except UnicodeError, exp: if isinstance(value, str): return unicode(value, 'utf8', errors='ignore') else: return '' def _delete_unwanted_caracters(self, chain): """Remove not wanted char from chain unwanted char are illegal_macro_output_chars attribute :param chain: chain to remove char from :type chain: str :return: chain cleaned :rtype: str """ for char in self.illegal_macro_output_chars: chain = chain.replace(char, '') return chain def get_env_macros(self, data): """Get all environment macros from data For each object in data :: * Fetch all macros in object.__class__.macros * Fetch all customs macros in o.custom :param data: data to get macro :type data: :return: dict with macro name as key and macro value as value :rtype: dict """ env = {} for obj in data: cls = obj.__class__ macros = cls.macros for macro in macros: if macro.startswith("USER"): break prop = macros[macro] value = self._get_value_from_element(obj, prop) env['NAGIOS_%s' % macro] = value if hasattr(obj, 'customs'): # make NAGIOS__HOSTMACADDR from _MACADDR for cmacro in obj.customs: new_env_name = 'NAGIOS__' + obj.__class__.__name__.upper() + cmacro[1:].upper() env[new_env_name] = obj.customs[cmacro] return env def resolve_simple_macros_in_string(self, c_line, data, args=None): """Replace macro in the command line with the real value :param c_line: command line to modify :type c_line: str :param data: objects list, use to look for a specific macro :type data: :param args: args given to the command line, used to get "ARGN" macros. :type args: :return: command line with '$MACRO$' replaced with values :rtype: str """ # Now we prepare the classes for looking at the class.macros data.append(self) # For getting global MACROS if hasattr(self, 'conf'): data.append(self.conf) # For USERN macros clss = [d.__class__ for d in data] # we should do some loops for nested macros # like $USER1$ hiding like a ninja in a $ARG2$ Macro. And if # $USER1$ is pointing to $USER34$ etc etc, we should loop # until we reach the bottom. So the last loop is when we do # not still have macros :) still_got_macros = True nb_loop = 0 while still_got_macros: nb_loop += 1 # Ok, we want the macros in the command line macros = self._get_macros(c_line) # We can get out if we do not have macros this loop still_got_macros = (len(macros) != 0) # print "Still go macros:", still_got_macros # Put in the macros the type of macro for all macros self._get_type_of_macro(macros, clss) # Now we get values from elements for macro in macros: # If type ARGN, look at ARGN cutting if macros[macro]['type'] == 'ARGN' and args is not None: macros[macro]['val'] = self._resolve_argn(macro, args) macros[macro]['type'] = 'resolved' # If class, get value from properties if macros[macro]['type'] == 'class': cls = macros[macro]['class'] for elt in data: if elt is not None and elt.__class__ == cls: prop = cls.macros[macro] macros[macro]['val'] = self._get_value_from_element(elt, prop) # Now check if we do not have a 'output' macro. If so, we must # delete all special characters that can be dangerous if macro in self.output_macros: macros[macro]['val'] = \ self._delete_unwanted_caracters(macros[macro]['val']) if macros[macro]['type'] == 'CUSTOM': cls_type = macros[macro]['class'] # Beware : only cut the first _HOST value, so the macro name can have it on it.. macro_name = re.split('_' + cls_type, macro, 1)[1].upper() # Ok, we've got the macro like MAC_ADDRESS for _HOSTMAC_ADDRESS # Now we get the element in data that have the type HOST # and we check if it got the custom value for elt in data: if elt is not None and elt.__class__.my_type.upper() == cls_type: if '_' + macro_name in elt.customs: macros[macro]['val'] = elt.customs['_' + macro_name] # Then look on the macromodulations, in reserver order, so # the last to set, will be the firt to have. (yes, don't want to play # with break and such things sorry...) mms = getattr(elt, 'macromodulations', []) for macromod in mms[::-1]: # Look if the modulation got the value, # but also if it's currently active if '_' + macro_name in macromod.customs and macromod.is_active(): macros[macro]['val'] = macromod.customs['_' + macro_name] if macros[macro]['type'] == 'ONDEMAND': macros[macro]['val'] = self._resolve_ondemand(macro, data) # We resolved all we can, now replace the macro in the command call for macro in macros: c_line = c_line.replace('$' + macro + '$', macros[macro]['val']) # A $$ means we want a $, it's not a macro! # We replace $$ by a big dirty thing to be sure to not misinterpret it c_line = c_line.replace("$$", "DOUBLEDOLLAR") if nb_loop > 32: # too much loop, we exit still_got_macros = False # We now replace the big dirty token we made by only a simple $ c_line = c_line.replace("DOUBLEDOLLAR", "$") # print "Retuning c_line", c_line.strip() return c_line.strip() def resolve_command(self, com, data): """Resolve command macros with data :param com: check / event handler or command call object :type com: object :param data: objects list, use to look for a specific macro :type data: :return: command line with '$MACRO$' replaced with values :rtype: str """ c_line = com.command.command_line return self.resolve_simple_macros_in_string(c_line, data, args=com.args) def _get_type_of_macro(self, macros, clss): r"""Set macros types Example:: ARG\d -> ARGN, HOSTBLABLA -> class one and set Host in class) _HOSTTOTO -> HOST CUSTOM MACRO TOTO SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1 :param macros: macros list :type macros: list[str] :param clss: classes list, used to tag class macros :type clss: :return: None """ for macro in macros: # ARGN Macros if re.match(r'ARG\d', macro): macros[macro]['type'] = 'ARGN' continue # USERN macros # are managed in the Config class, so no # need to look that here elif re.match(r'_HOST\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'HOST' continue elif re.match(r'_SERVICE\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'SERVICE' # value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1] continue elif re.match(r'_CONTACT\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'CONTACT' continue # On demand macro elif len(macro.split(':')) > 1: macros[macro]['type'] = 'ONDEMAND' continue # OK, classical macro... for cls in clss: if macro in cls.macros: macros[macro]['type'] = 'class' macros[macro]['class'] = cls continue def _resolve_argn(self, macro, args): """Get argument from macro name ie : $ARG3$ -> args[2] :param macro: macro to parse :type macro: :param args: args given to command line :type args: :return: argument at position N-1 in args table (where N is the int parsed) :rtype: None | str """ # first, get the number of args _id = None matches = re.search(r'ARG(?P<id>\d+)', macro) if matches is not None: _id = int(matches.group('id')) - 1 try: return args[_id] except IndexError: return '' def _resolve_ondemand(self, macro, data): """Get on demand macro value :param macro: macro to parse :type macro: :param data: data to get value from :type data: :return: macro value :rtype: str """ # print "\nResolving macro", macro elts = macro.split(':') nb_parts = len(elts) macro_name = elts[0] # Len 3 == service, 2 = all others types... if nb_parts == 3: val = '' # print "Got a Service on demand asking...", elts (host_name, service_description) = (elts[1], elts[2]) # host_name can be void, so it's the host in data # that is important. We use our self.host_class to # find the host in the data :) if host_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: host_name = elt.host_name # Ok now we get service serv = self.services.find_srv_by_name_and_hostname(host_name, service_description) if serv is not None: cls = serv.__class__ prop = cls.macros[macro_name] val = self._get_value_from_element(serv, prop) # print "Got val:", val return val # Ok, service was easy, now hard part else: val = '' elt_name = elts[1] # Special case: elt_name can be void # so it's the host where it apply if elt_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: elt_name = elt.host_name for od_list in self.lists_on_demand: cls = od_list.inner_class # We search our type by looking at the macro if macro_name in cls.macros: prop = cls.macros[macro_name] i = od_list.find_by_name(elt_name) if i is not None: val = self._get_value_from_element(i, prop) # Ok we got our value :) break return val return '' def _get_long_date_time(self): """Get long date time Example : Fri 15 May 11:42:39 CEST 2009 :return: long date local time :rtype: str TODO: Should be moved to util TODO: Should consider timezone """ return time.strftime("%a %d %b %H:%M:%S %Z %Y").decode('UTF-8', 'ignore') def _get_short_date_time(self): """Get short date time Example : 10-13-2000 00:30:28 :return: short date local time :rtype: str TODO: Should be moved to util TODO: Should consider timezone """ return time.strftime("%d-%m-%Y %H:%M:%S") def _get_date(self): """Get date Example : 10-13-2000 :return: local date :rtype: str TODO: Should be moved to util TODO: Should consider timezone """ return time.strftime("%d-%m-%Y") def _get_time(self): """Get date time Example : 00:30:28 :return: date local time :rtype: str TODO: Should be moved to util TODO: Should consider timezone """ return time.strftime("%H:%M:%S") def _get_timet(self): """Get epoch time Example : 1437143291 :return: timestamp :rtype: str TODO: Should be moved to util TODO: Should consider timezone """ return str(int(time.time())) def _tot_hosts_by_state(self, state): """Generic function to get the number of host in the specified state :param state: state to filter on :type state: :return: number of host in state *state* :rtype: int TODO: Should be moved """ return sum(1 for h in self.hosts if h.state == state) _get_total_hosts_up = lambda s: s._tot_hosts_by_state('UP') _get_total_hosts_down = lambda s: s._tot_hosts_by_state('DOWN') _get_total_hosts_unreachable = lambda s: s._tot_hosts_by_state('UNREACHABLE') def _get_total_hosts_unreachable_unhandled(self): """DOES NOTHING( Should get the number of unreachable hosts not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_total_hosts_problems(self): """Get the number of hosts that are a problem :return: number of hosts with is_problem attribute True :rtype: int """ return sum(1 for h in self.hosts if h.is_problem) def _get_total_hosts_problems_unhandled(self): """DOES NOTHING( Should get the number of host problems not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _tot_services_by_state(self, state): """Generic function to get the number of service in the specified state :param state: state to filter on :type state: :return: number of service in state *state* :rtype: int TODO: Should be moved """ return sum(1 for s in self.services if s.state == state) _get_total_service_ok = lambda s: s._tot_services_by_state('OK') _get_total_service_warning = lambda s: s._tot_services_by_state('WARNING') _get_total_service_critical = lambda s: s._tot_services_by_state('CRITICAL') _get_total_service_unknown = lambda s: s._tot_services_by_state('UNKNOWN') def _get_total_services_warning_unhandled(self): """DOES NOTHING (Should get the number of warning services not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_total_services_critical_unhandled(self): """DOES NOTHING (Should get the number of critical services not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_total_services_unknown_unhandled(self): """DOES NOTHING (Should get the number of unknown services not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_total_service_problems(self): """Get the number of services that are a problem :return: number of services with is_problem attribute True :rtype: int """ return sum(1 for s in self.services if s.is_problem) def _get_total_service_problems_unhandled(self): """DOES NOTHING (Should get the number of service problems not handled) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_process_start_time(self): """DOES NOTHING ( Should get process start time) :return: 0 always :rtype: int TODO: Implement this """ return 0 def _get_events_start_time(self): """DOES NOTHING ( Should get events start time) :return: 0 always :rtype: int TODO: Implement this """ return 0
agpl-3.0
SamuelDSR/YouCompleteMe-Win7-GVIM
third_party/bottle/plugins/sqlite/bottle_sqlite.py
7
3437
''' Bottle-sqlite is a plugin that integrates SQLite3 with your Bottle application. It automatically connects to a database at the beginning of a request, passes the database handle to the route callback and closes the connection afterwards. To automatically detect routes that need a database connection, the plugin searches for route callbacks that require a `db` keyword argument (configurable) and skips routes that do not. This removes any overhead for routes that don't need a database connection. Usage Example:: import bottle from bottle.ext import sqlite app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='/tmp/test.db') app.install(plugin) @app.route('/show/:item') def show(item, db): row = db.execute('SELECT * from items where name=?', item).fetchone() if row: return template('showitem', page=row) return HTTPError(404, "Page not found") ''' __author__ = "Marcel Hellkamp" __version__ = '0.1.1' __license__ = 'MIT' ### CUT HERE (see setup.py) import sqlite3 import inspect from bottle import HTTPError, PluginError class SQLitePlugin(object): ''' This plugin passes an sqlite3 database handle to route callbacks that accept a `db` keyword argument. If a callback does not expect such a parameter, no connection is made. You can override the database settings on a per-route basis. ''' name = 'sqlite' api = 2 def __init__(self, dbfile=':memory:', autocommit=True, dictrows=True, keyword='db'): self.dbfile = dbfile self.autocommit = autocommit self.dictrows = dictrows self.keyword = keyword def setup(self, app): ''' Make sure that other installed plugins don't affect the same keyword argument.''' for other in app.plugins: if not isinstance(other, SQLitePlugin): continue if other.keyword == self.keyword: raise PluginError("Found another sqlite plugin with "\ "conflicting settings (non-unique keyword).") def apply(self, callback, route): # Override global configuration with route-specific values. conf = route.config.get('sqlite') or {} dbfile = conf.get('dbfile', self.dbfile) autocommit = conf.get('autocommit', self.autocommit) dictrows = conf.get('dictrows', self.dictrows) keyword = conf.get('keyword', self.keyword) # Test if the original callback accepts a 'db' keyword. # Ignore it if it does not need a database handle. args = inspect.getargspec(route.callback)[0] if keyword not in args: return callback def wrapper(*args, **kwargs): # Connect to the database db = sqlite3.connect(dbfile) # This enables column access by name: row['column_name'] if dictrows: db.row_factory = sqlite3.Row # Add the connection handle as a keyword argument. kwargs[keyword] = db try: rv = callback(*args, **kwargs) if autocommit: db.commit() except sqlite3.IntegrityError, e: db.rollback() raise HTTPError(500, "Database Error", e) finally: db.close() return rv # Replace the route callback with the wrapped one. return wrapper Plugin = SQLitePlugin
gpl-3.0
google/google-ctf
third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_sgmllib.py
14
16167
import pprint import re import unittest from test import test_support sgmllib = test_support.import_module('sgmllib', deprecated=True) class EventCollector(sgmllib.SGMLParser): def __init__(self): self.events = [] self.append = self.events.append sgmllib.SGMLParser.__init__(self) def get_events(self): # Normalize the list of events so that buffer artefacts don't # separate runs of contiguous characters. L = [] prevtype = None for event in self.events: type = event[0] if type == prevtype == "data": L[-1] = ("data", L[-1][1] + event[1]) else: L.append(event) prevtype = type self.events = L return L # structure markup def unknown_starttag(self, tag, attrs): self.append(("starttag", tag, attrs)) def unknown_endtag(self, tag): self.append(("endtag", tag)) # all other markup def handle_comment(self, data): self.append(("comment", data)) def handle_charref(self, data): self.append(("charref", data)) def handle_data(self, data): self.append(("data", data)) def handle_decl(self, decl): self.append(("decl", decl)) def handle_entityref(self, data): self.append(("entityref", data)) def handle_pi(self, data): self.append(("pi", data)) def unknown_decl(self, decl): self.append(("unknown decl", decl)) class CDATAEventCollector(EventCollector): def start_cdata(self, attrs): self.append(("starttag", "cdata", attrs)) self.setliteral() class HTMLEntityCollector(EventCollector): entity_or_charref = re.compile('(?:&([a-zA-Z][-.a-zA-Z0-9]*)' '|&#(x[0-9a-zA-Z]+|[0-9]+))(;?)') def convert_charref(self, name): self.append(("charref", "convert", name)) if name[0] != "x": return EventCollector.convert_charref(self, name) def convert_codepoint(self, codepoint): self.append(("codepoint", "convert", codepoint)) EventCollector.convert_codepoint(self, codepoint) def convert_entityref(self, name): self.append(("entityref", "convert", name)) return EventCollector.convert_entityref(self, name) # These to record that they were called, then pass the call along # to the default implementation so that it's actions can be # recorded. def handle_charref(self, data): self.append(("charref", data)) sgmllib.SGMLParser.handle_charref(self, data) def handle_entityref(self, data): self.append(("entityref", data)) sgmllib.SGMLParser.handle_entityref(self, data) class SGMLParserTestCase(unittest.TestCase): collector = EventCollector def get_events(self, source): parser = self.collector() try: for s in source: parser.feed(s) parser.close() except: #self.events = parser.events raise return parser.get_events() def check_events(self, source, expected_events): try: events = self.get_events(source) except: #import sys #print >>sys.stderr, pprint.pformat(self.events) raise if events != expected_events: self.fail("received events did not match expected events\n" "Expected:\n" + pprint.pformat(expected_events) + "\nReceived:\n" + pprint.pformat(events)) def check_parse_error(self, source): parser = EventCollector() try: parser.feed(source) parser.close() except sgmllib.SGMLParseError: pass else: self.fail("expected SGMLParseError for %r\nReceived:\n%s" % (source, pprint.pformat(parser.get_events()))) def test_doctype_decl_internal(self): inside = """\ DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN' SYSTEM 'http://www.w3.org/TR/html401/strict.dtd' [ <!ELEMENT html - O EMPTY> <!ATTLIST html version CDATA #IMPLIED profile CDATA 'DublinCore'> <!NOTATION datatype SYSTEM 'http://xml.python.org/notations/python-module'> <!ENTITY myEntity 'internal parsed entity'> <!ENTITY anEntity SYSTEM 'http://xml.python.org/entities/something.xml'> <!ENTITY % paramEntity 'name|name|name'> %paramEntity; <!-- comment --> ]""" self.check_events(["<!%s>" % inside], [ ("decl", inside), ]) def test_doctype_decl_external(self): inside = "DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'" self.check_events("<!%s>" % inside, [ ("decl", inside), ]) def test_underscore_in_attrname(self): # SF bug #436621 """Make sure attribute names with underscores are accepted""" self.check_events("<a has_under _under>", [ ("starttag", "a", [("has_under", "has_under"), ("_under", "_under")]), ]) def test_underscore_in_tagname(self): # SF bug #436621 """Make sure tag names with underscores are accepted""" self.check_events("<has_under></has_under>", [ ("starttag", "has_under", []), ("endtag", "has_under"), ]) def test_quotes_in_unquoted_attrs(self): # SF bug #436621 """Be sure quotes in unquoted attributes are made part of the value""" self.check_events("<a href=foo'bar\"baz>", [ ("starttag", "a", [("href", "foo'bar\"baz")]), ]) def test_xhtml_empty_tag(self): """Handling of XHTML-style empty start tags""" self.check_events("<br />text<i></i>", [ ("starttag", "br", []), ("data", "text"), ("starttag", "i", []), ("endtag", "i"), ]) def test_processing_instruction_only(self): self.check_events("<?processing instruction>", [ ("pi", "processing instruction"), ]) def test_bad_nesting(self): self.check_events("<a><b></a></b>", [ ("starttag", "a", []), ("starttag", "b", []), ("endtag", "a"), ("endtag", "b"), ]) def test_bare_ampersands(self): self.check_events("this text & contains & ampersands &", [ ("data", "this text & contains & ampersands &"), ]) def test_bare_pointy_brackets(self): self.check_events("this < text > contains < bare>pointy< brackets", [ ("data", "this < text > contains < bare>pointy< brackets"), ]) def test_attr_syntax(self): output = [ ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", "e")]) ] self.check_events("""<a b='v' c="v" d=v e>""", output) self.check_events("""<a b = 'v' c = "v" d = v e>""", output) self.check_events("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output) self.check_events("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output) def test_attr_values(self): self.check_events("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""", [("starttag", "a", [("b", "xxx\n\txxx"), ("c", "yyy\t\nyyy"), ("d", "\txyz\n")]) ]) self.check_events("""<a b='' c="">""", [ ("starttag", "a", [("b", ""), ("c", "")]), ]) # URL construction stuff from RFC 1808: safe = "$-_.+" extra = "!*'()," reserved = ";/?:@&=" url = "http://example.com:8080/path/to/file?%s%s%s" % ( safe, extra, reserved) self.check_events("""<e a=%s>""" % url, [ ("starttag", "e", [("a", url)]), ]) # Regression test for SF patch #669683. self.check_events("<e a=rgb(1,2,3)>", [ ("starttag", "e", [("a", "rgb(1,2,3)")]), ]) def test_attr_values_entities(self): """Substitution of entities and charrefs in attribute values""" # SF bug #1452246 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; ' f="&xxx;" g='&#32;&#33;' h='&#500;' i='x?a=b&c=d;' j='&amp;#42;' k='&#38;#42;'>""", [("starttag", "a", [("b", "<"), ("c", "<>"), ("d", "&lt->"), ("e", "< "), ("f", "&xxx;"), ("g", " !"), ("h", "&#500;"), ("i", "x?a=b&c=d;"), ("j", "&#42;"), ("k", "&#42;"), ])]) def test_convert_overrides(self): # This checks that the character and entity reference # conversion helpers are called at the documented times. No # attempt is made to really change what the parser accepts. # self.collector = HTMLEntityCollector self.check_events(('<a title="&ldquo;test&#x201d;">foo</a>' '&foobar;&#42;'), [ ('entityref', 'convert', 'ldquo'), ('charref', 'convert', 'x201d'), ('starttag', 'a', [('title', '&ldquo;test&#x201d;')]), ('data', 'foo'), ('endtag', 'a'), ('entityref', 'foobar'), ('entityref', 'convert', 'foobar'), ('charref', '42'), ('charref', 'convert', '42'), ('codepoint', 'convert', 42), ]) def test_attr_funky_names(self): self.check_events("""<a a.b='v' c:d=v e-f=v>""", [ ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]), ]) def test_attr_value_ip6_url(self): # http://www.python.org/sf/853506 self.check_events(("<a href='http://[1080::8:800:200C:417A]/'>" "<a href=http://[1080::8:800:200C:417A]/>"), [ ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]), ("starttag", "a", [("href", "http://[1080::8:800:200C:417A]/")]), ]) def test_weird_starttags(self): self.check_events("<a<a>", [ ("starttag", "a", []), ("starttag", "a", []), ]) self.check_events("</a<a>", [ ("endtag", "a"), ("starttag", "a", []), ]) def test_declaration_junk_chars(self): self.check_parse_error("<!DOCTYPE foo $ >") def test_get_starttag_text(self): s = """<foobar \n one="1"\ttwo=2 >""" self.check_events(s, [ ("starttag", "foobar", [("one", "1"), ("two", "2")]), ]) def test_cdata_content(self): s = ("<cdata> <!-- not a comment --> &not-an-entity-ref; </cdata>" "<notcdata> <!-- comment --> </notcdata>") self.collector = CDATAEventCollector self.check_events(s, [ ("starttag", "cdata", []), ("data", " <!-- not a comment --> &not-an-entity-ref; "), ("endtag", "cdata"), ("starttag", "notcdata", []), ("data", " "), ("comment", " comment "), ("data", " "), ("endtag", "notcdata"), ]) s = """<cdata> <not a='start tag'> </cdata>""" self.check_events(s, [ ("starttag", "cdata", []), ("data", " <not a='start tag'> "), ("endtag", "cdata"), ]) def test_illegal_declarations(self): s = 'abc<!spacer type="block" height="25">def' self.check_events(s, [ ("data", "abc"), ("unknown decl", 'spacer type="block" height="25"'), ("data", "def"), ]) def test_enumerated_attr_type(self): s = "<!DOCTYPE doc [<!ATTLIST doc attr (a | b) >]>" self.check_events(s, [ ('decl', 'DOCTYPE doc [<!ATTLIST doc attr (a | b) >]'), ]) def test_read_chunks(self): # SF bug #1541697, this caused sgml parser to hang # Just verify this code doesn't cause a hang. CHUNK = 1024 # increasing this to 8212 makes the problem go away f = open(test_support.findfile('sgml_input.html')) fp = sgmllib.SGMLParser() while 1: data = f.read(CHUNK) fp.feed(data) if len(data) != CHUNK: break def test_only_decode_ascii(self): # SF bug #1651995, make sure non-ascii character references are not decoded s = '<signs exclamation="&#33" copyright="&#169" quoteleft="&#8216;">' self.check_events(s, [ ('starttag', 'signs', [('exclamation', '!'), ('copyright', '&#169'), ('quoteleft', '&#8216;')]), ]) # XXX These tests have been disabled by prefixing their names with # an underscore. The first two exercise outstanding bugs in the # sgmllib module, and the third exhibits questionable behavior # that needs to be carefully considered before changing it. def _test_starttag_end_boundary(self): self.check_events("<a b='<'>", [("starttag", "a", [("b", "<")])]) self.check_events("<a b='>'>", [("starttag", "a", [("b", ">")])]) def _test_buffer_artefacts(self): output = [("starttag", "a", [("b", "<")])] self.check_events(["<a b='<'>"], output) self.check_events(["<a ", "b='<'>"], output) self.check_events(["<a b", "='<'>"], output) self.check_events(["<a b=", "'<'>"], output) self.check_events(["<a b='<", "'>"], output) self.check_events(["<a b='<'", ">"], output) output = [("starttag", "a", [("b", ">")])] self.check_events(["<a b='>'>"], output) self.check_events(["<a ", "b='>'>"], output) self.check_events(["<a b", "='>'>"], output) self.check_events(["<a b=", "'>'>"], output) self.check_events(["<a b='>", "'>"], output) self.check_events(["<a b='>'", ">"], output) output = [("comment", "abc")] self.check_events(["", "<!--abc-->"], output) self.check_events(["<", "!--abc-->"], output) self.check_events(["<!", "--abc-->"], output) self.check_events(["<!-", "-abc-->"], output) self.check_events(["<!--", "abc-->"], output) self.check_events(["<!--a", "bc-->"], output) self.check_events(["<!--ab", "c-->"], output) self.check_events(["<!--abc", "-->"], output) self.check_events(["<!--abc-", "->"], output) self.check_events(["<!--abc--", ">"], output) self.check_events(["<!--abc-->", ""], output) def _test_starttag_junk_chars(self): self.check_parse_error("<") self.check_parse_error("<>") self.check_parse_error("</$>") self.check_parse_error("</") self.check_parse_error("</a") self.check_parse_error("<$") self.check_parse_error("<$>") self.check_parse_error("<!") self.check_parse_error("<a $>") self.check_parse_error("<a") self.check_parse_error("<a foo='bar'") self.check_parse_error("<a foo='bar") self.check_parse_error("<a foo='>'") self.check_parse_error("<a foo='>") self.check_parse_error("<a foo=>") def test_main(): test_support.run_unittest(SGMLParserTestCase) if __name__ == "__main__": test_main()
apache-2.0
avedaee/DIRAC
ResourceStatusSystem/Utilities/CSHelpers.py
2
3673
# $HeadURL: $ ''' CSHelpers Module containing functions interacting with the CS and useful for the RSS modules. ''' from DIRAC import S_OK, S_ERROR from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getGOCSiteName from DIRAC.ResourceStatusSystem.Utilities import Utils from DIRAC.ConfigurationSystem.Client.Helpers import Resources __RCSID__ = '$Id: $' def getGOCSites( diracSites = None ): #FIXME: THIS SHOULD GO INTO Resources HELPER if diracSites is None: diracSites = Resources.getSites() if not diracSites[ 'OK' ]: return diracSites diracSites = diracSites[ 'Value' ] gocSites = [] for diracSite in diracSites: gocSite = getGOCSiteName( diracSite ) if not gocSite[ 'OK' ]: continue gocSites.append( gocSite[ 'Value' ] ) return S_OK( list( set( gocSites ) ) ) def getStorageElementsHosts( seNames = None ): seHosts = [] resources = Resources.Resources() if seNames is None: seNames = resources.getEligibleStorageElements() if not seNames[ 'OK' ]: return seNames seNames = seNames[ 'Value' ] for seName in seNames: result = getSEProtocolOption( seName, 'Host' ) if result['OK']: seHosts.append( result['Value'] ) return S_OK( list( set( seHosts ) ) ) def getSEProtocolOption( se, optionName ): """ Get option of the Storage Element access protocol """ resources = Resources.Resources() result = resources.getAccessProtocols( se ) if not result['OK']: return S_ERROR( "Acces Protocol for SE %s not found: %s" % ( se, result['Message'] ) ) try: ap = result['Value'][0] except IndexError: return S_ERROR( 'No AccessProtocol associated to %s' % se ) return resources.getAccessProtocolOption( ap, optionName ) def getStorageElementEndpoint( storageElement ): resources = Resources.Resources() result = resources.getAccessProtocols( storageElement ) if not result['OK']: return result # FIXME: There can be several access protocols for the same SE ! try: ap = result['Value'][0] except IndexError: return S_ERROR( 'No AccessProtocol associated to %s' % storageElement ) result = resources.getAccessProtocolOptionsDict( ap ) #result = resources.getAccessProtocols( storageElement ) if not result['OK']: return result host = result['Value'].get( 'Host', '' ) port = result['Value'].get( 'Port', '' ) wsurl = result['Value'].get( 'WSUrl', '' ) # MAYBE wusrl is not defined #if host and port and wsurl: if host and port: url = 'httpg://%s:%s%s' % ( host, port, wsurl ) url = url.replace( '?SFN=', '' ) return S_OK( url ) return S_ERROR( ( host, port, wsurl ) ) def getStorageElementEndpoints( storageElements = None ): resources = Resources.Resources() if storageElements is None: storageElements = resources.getEligibleStorageElements() if not storageElements[ 'OK' ]: return storageElements storageElements = storageElements[ 'Value' ] storageElementEndpoints = [] for se in storageElements: seEndpoint = getStorageElementEndpoint( se ) if not seEndpoint[ 'OK' ]: continue storageElementEndpoints.append( seEndpoint[ 'Value' ] ) return S_OK( list( set( storageElementEndpoints ) ) ) def getSpaceTokenEndpoints(): ''' Get Space Token Endpoints ''' return Utils.getCSTree( 'Shares/Disk' ) ################################################################################ #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
gpl-3.0
Python1320/icmpviewer
main.py
1
1217
#!/usr/bin/env python2 QUEUE_NUM = 5 #hush verbosity import logging l=logging.getLogger("scapy.runtime") l.setLevel(49) import os,sys,time from sys import stdout as out import nfqueue,socket from scapy.all import * import GeoIP gi = GeoIP.open("GeoLiteCity.dat",GeoIP.GEOIP_STANDARD) lastip="" def DoGeoIP(pkt): global lastip ip = pkt[IP].src if lastip==ip: out.write('.') out.flush() return lastip=ip gir = gi.record_by_addr(ip) if gir != None: out.write("\n%s %s %s %s "%( time.strftime("%Y-%m-%d %H:%M:%S"), ip, gir['country_name'] or "?", gir['city'] or "?")) out.flush() def process_packet(dummy, payload): payload.set_verdict(nfqueue.NF_ACCEPT) data = payload.get_data() pkt = IP(data) proto = pkt.proto if proto is 0x01: if pkt[ICMP].type is 8: DoGeoIP(pkt) #automatic iptables rules? def hook(): pass def unhook(): pass def main(): q = nfqueue.queue() q.open() q.bind(socket.AF_INET) q.set_callback(process_packet) q.create_queue(QUEUE_NUM) try: hook() q.try_run() except KeyboardInterrupt: unhook() print("Exit...") q.unbind(socket.AF_INET) q.close() sys.exit(0) print("Listening on queue number "+str(QUEUE_NUM)) main()
unlicense
williamsentosa/hadoop-modified
src/examples/python/WordCount.py
123
2243
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from org.apache.hadoop.fs import Path from org.apache.hadoop.io import * from org.apache.hadoop.mapred import * import sys import getopt class WordCountMap(Mapper, MapReduceBase): one = IntWritable(1) def map(self, key, value, output, reporter): for w in value.toString().split(): output.collect(Text(w), self.one) class Summer(Reducer, MapReduceBase): def reduce(self, key, values, output, reporter): sum = 0 while values.hasNext(): sum += values.next().get() output.collect(key, IntWritable(sum)) def printUsage(code): print "wordcount [-m <maps>] [-r <reduces>] <input> <output>" sys.exit(code) def main(args): conf = JobConf(WordCountMap); conf.setJobName("wordcount"); conf.setOutputKeyClass(Text); conf.setOutputValueClass(IntWritable); conf.setMapperClass(WordCountMap); conf.setCombinerClass(Summer); conf.setReducerClass(Summer); try: flags, other_args = getopt.getopt(args[1:], "m:r:") except getopt.GetoptError: printUsage(1) if len(other_args) != 2: printUsage(1) for f,v in flags: if f == "-m": conf.setNumMapTasks(int(v)) elif f == "-r": conf.setNumReduceTasks(int(v)) conf.setInputPath(Path(other_args[0])) conf.setOutputPath(Path(other_args[1])) JobClient.runJob(conf); if __name__ == "__main__": main(sys.argv)
apache-2.0
sebastic/QGIS
python/plugins/processing/tests/RunAlgTest.py
11
3686
# -*- coding: utf-8 -*- """ *************************************************************************** RunAlgTest.py --------------------- Date : March 2013 Copyright : (C) 2013 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'March 2013' __copyright__ = '(C) 2013, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import unittest import processing from processing.tools import dataobjects from processing.tools.system import getTempFilename from processing.tests.TestData import points, polygons class ParametrizedTestCase(unittest.TestCase): def __init__(self, methodName='runTest', useTempFiles=False): super(ParametrizedTestCase, self).__init__(methodName) self.useTempFiles = useTempFiles @staticmethod def parametrize(testcase_klass, useTempFiles): testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(testcase_klass) suite = unittest.TestSuite() for name in testnames: suite.addTest(testcase_klass(name, useTempFiles=useTempFiles)) return suite class RunAlgTest(ParametrizedTestCase): """This test takes a reduced set of algorithms and executes them in different ways, changing parameters such as whether to use temp outputs, the output file format, etc. Basically, it uses some algorithms to test other parts of the Processign framework, not the algorithms themselves """ def getOutputFile(self): if self.useTempFiles: return None else: return getTempFilename('shp') def test_qgiscountpointsinpolygon(self): outputs = processing.runalg('qgis:countpointsinpolygon', polygons(), points(), 'NUMPOINTS', self.getOutputFile()) output = outputs['OUTPUT'] layer = dataobjects.getObjectFromUri(output, True) fields = layer.pendingFields() expectednames = ['ID', 'POLY_NUM_A', 'POLY_ST_A', 'NUMPOINTS'] expectedtypes = ['Integer', 'Real', 'String', 'Real'] names = [unicode(f.name()) for f in fields] types = [unicode(f.typeName()) for f in fields] self.assertEqual(expectednames, names) self.assertEqual(expectedtypes, types) features = processing.features(layer) self.assertEqual(2, len(features)) feature = features.next() attrs = feature.attributes() expectedvalues = ['1', '1.1', 'string a', '6'] values = [unicode(attr) for attr in attrs] self.assertEqual(expectedvalues, values) def suite(): suite = unittest.TestSuite() suite.addTest(ParametrizedTestCase.parametrize(RunAlgTest, False)) suite.addTest(ParametrizedTestCase.parametrize(RunAlgTest, True)) return suite def runtests(): result = unittest.TestResult() testsuite = suite() testsuite.run(result) return result
gpl-2.0
mhabib1981/pySecn00b
zap_xml_parse.py
1
2159
from xml.dom.minidom import parse import xml.dom.minidom import sys import csv #uni_file=open(sys.argv[1],'r') #non_uni_file=uni_file.decode("utf8") dom_tree=parse(sys.argv[1]) collect=dom_tree.documentElement output_data=[[],[],[],[],[],[],[],[]] out_filename=((sys.argv[1].split("/")[-1]).split(".")[0])+".csv" out_file=open(out_filename,'w') write_csv=csv.writer(out_file, dialect=csv.excel) for item in collect.getElementsByTagName("alertitem"): try: risk_desc=item.getElementsByTagName('riskdesc')[0] output_data[0].append(risk_desc.childNodes[0].data) except IndexError: output_data[0].append("NONE") try: alert_name=item.getElementsByTagName('alert')[0] output_data[1].append(alert_name.childNodes[0].data) except IndexError: output_data[1].append("NONE") try: alert_desc=item.getElementsByTagName('desc')[0] output_data[2].append((alert_desc.childNodes[0].data).encode("utf-8")) except IndexError: output_data[2].append("NONE") try: alert_solution=item.getElementsByTagName('solution')[0] output_data[3].append((alert_solution.childNodes[0].data).encode("utf-8")) except IndexError: output_data[3].append("NONE") try: alert_ref=item.getElementsByTagName('reference')[0] output_data[4].append((alert_ref.childNodes[0].data).encode("utf-8")) except IndexError: output_data[4].append("NONE") try: uri=item.getElementsByTagName('uri')[0] output_data[5].append(uri.childNodes[0].data) except IndexError: output_data[5].append("NONE") try: evid=item.getElementsByTagName('evidence')[0] output_data[6].append(evid.childNodes[0].data) except IndexError: output_data[6].append("NONE") try: attack=item.getElementsByTagName('attack')[0] output_data[7].append(attack.childNodes[0].data) except IndexError: output_data[7].append("NONE") try: for i in range(0,len(output_data[0])-1): row=[] for x in range(0,len(output_data)): row.append(str(output_data[x][i]).replace(',',';c')) print row except UnicodeEncodeError: raise #print output_data # for x in xrange(0,len(output_data)-1): # print output_data[x][i] #write_csv.writerows(output_data)
cc0-1.0
syaiful6/django
django/contrib/gis/db/backends/postgis/introspection.py
330
5441
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.postgresql.introspection import DatabaseIntrospection class GeoIntrospectionError(Exception): pass class PostGISIntrospection(DatabaseIntrospection): # Reverse dictionary for PostGIS geometry types not populated until # introspection is actually performed. postgis_types_reverse = {} ignored_tables = DatabaseIntrospection.ignored_tables + [ 'geography_columns', 'geometry_columns', 'raster_columns', 'spatial_ref_sys', 'raster_overviews', ] # Overridden from parent to include raster indices in retrieval. # Raster indices have pg_index.indkey value 0 because they are an # expression over the raster column through the ST_ConvexHull function. # So the default query has to be adapted to include raster indices. _get_indexes_query = """ SELECT DISTINCT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index idx, pg_catalog.pg_attribute attr LEFT JOIN pg_catalog.pg_type t ON t.oid = attr.atttypid WHERE c.oid = idx.indrelid AND idx.indexrelid = c2.oid AND attr.attrelid = c.oid AND ( attr.attnum = idx.indkey[0] OR (t.typname LIKE 'raster' AND idx.indkey = '0') ) AND attr.attnum > 0 AND c.relname = %s""" def get_postgis_types(self): """ Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported). """ field_types = [ ('geometry', 'GeometryField'), # The value for the geography type is actually a tuple # to pass in the `geography=True` keyword to the field # definition. ('geography', ('GeometryField', {'geography': True})), ] postgis_types = {} # The OID integers associated with the geometry type may # be different across versions; hence, this is why we have # to query the PostgreSQL pg_type table corresponding to the # PostGIS custom data types. oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s' cursor = self.connection.cursor() try: for field_type in field_types: cursor.execute(oid_sql, (field_type[0],)) for result in cursor.fetchall(): postgis_types[result[0]] = field_type[1] finally: cursor.close() return postgis_types def get_field_type(self, data_type, description): if not self.postgis_types_reverse: # If the PostGIS types reverse dictionary is not populated, do so # now. In order to prevent unnecessary requests upon connection # initialization, the `data_types_reverse` dictionary is not updated # with the PostGIS custom types until introspection is actually # performed -- in other words, when this function is called. self.postgis_types_reverse = self.get_postgis_types() self.data_types_reverse.update(self.postgis_types_reverse) return super(PostGISIntrospection, self).get_field_type(data_type, description) def get_geometry_type(self, table_name, geo_col): """ The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type, """ cursor = self.connection.cursor() try: try: # First seeing if this geometry column is in the `geometry_columns` cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geometry_columns" ' 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise GeoIntrospectionError except GeoIntrospectionError: cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geography_columns" ' 'WHERE "f_table_name"=%s AND "f_geography_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise Exception('Could not find a geometry or geography column for "%s"."%s"' % (table_name, geo_col)) # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. field_type = OGRGeomType(row[2]).django # Getting any GeometryField keyword arguments that are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params['srid'] = srid if dim != 2: field_params['dim'] = dim finally: cursor.close() return field_type, field_params
bsd-3-clause
ibab/tensorflow
tensorflow/contrib/ffmpeg/__init__.py
5
1566
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=g-short-docstring-punctuation """## Encoding and decoding audio using FFmpeg TensorFlow provides Ops to decode and encode audio files using the [FFmpeg](https://www.ffmpeg.org/) library. FFmpeg must be locally [installed](https://ffmpeg.org/download.html) for these Ops to succeed. Example: ```python from tensorflow.contrib import ffmpeg audio_binary = tf.read_file('song.mp3') waveform = ffmpeg.decode_audio( audio_binary, file_format='mp3', samples_per_second=44100, channel_count=2) uncompressed_binary = ffmpeg.encode_audio( waveform, file_format='wav', samples_per_second=44100) ``` @@decode_audio @@encode_audio """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.ffmpeg.ffmpeg_ops import decode_audio from tensorflow.contrib.ffmpeg.ffmpeg_ops import encode_audio
apache-2.0
lidavidm/mathics-heroku
venv/lib/python2.7/site-packages/sympy/combinatorics/tests/test_partitions.py
3
3304
from sympy.combinatorics.partitions import (Partition, IntegerPartition, RGS_enum, RGS_unrank, RGS_rank, random_integer_partition) from sympy.utilities.pytest import raises from sympy.utilities.iterables import default_sort_key, partitions def test_partition(): from sympy.abc import x raises(ValueError, lambda: Partition(range(3))) raises(ValueError, lambda: Partition([[1, 1, 2]])) a = Partition([[1, 2, 3], [4]]) b = Partition([[1, 2], [3, 4]]) c = Partition([[x]]) l = [a, b, c] l.sort(key=default_sort_key) assert l == [c, a, b] l.sort(key=lambda w: default_sort_key(w, order='rev-lex')) assert l == [c, a, b] assert (a == b) is False assert a <= b assert (a > b) is False assert a != b assert (a + 2).partition == [[1, 2], [3, 4]] assert (b - 1).partition == [[1, 2, 4], [3]] assert (a - 1).partition == [[1, 2, 3, 4]] assert (a + 1).partition == [[1, 2, 4], [3]] assert (b + 1).partition == [[1, 2], [3], [4]] assert a.rank == 1 assert b.rank == 3 assert a.RGS == (0, 0, 0, 1) assert b.RGS == (0, 0, 1, 1) def test_integer_partition(): # no zeros in partition raises(ValueError, lambda: IntegerPartition(range(3))) # check fails since 1 + 2 != 100 raises(ValueError, lambda: IntegerPartition(100, range(1, 3))) a = IntegerPartition(8, [1, 3, 4]) b = a.next_lex() c = IntegerPartition([1, 3, 4]) d = IntegerPartition(8, {1: 3, 3: 1, 2: 1}) assert a == c assert a.integer == d.integer assert a.conjugate == [3, 2, 2, 1] assert (a == b) is False assert a <= b assert (a > b) is False assert a != b for i in range(1, 11): next = set() prev = set() a = IntegerPartition([i]) ans = set([IntegerPartition(p) for p in partitions(i)]) n = len(ans) for j in range(n): next.add(a) a = a.next_lex() IntegerPartition(i, a.partition) # check it by giving i for j in range(n): prev.add(a) a = a.prev_lex() IntegerPartition(i, a.partition) # check it by giving i assert next == ans assert prev == ans assert IntegerPartition([1, 2, 3]).as_ferrers() == '###\n##\n#' assert IntegerPartition([1, 1, 3]).as_ferrers('o') == 'ooo\no\no' assert str(IntegerPartition([1, 1, 3])) == '[3, 1, 1]' assert IntegerPartition([1, 1, 3]).partition == [3, 1, 1] raises(ValueError, lambda: random_integer_partition(-1)) assert random_integer_partition(1) == [1] assert random_integer_partition(10, seed=[1, 3, 2, 1, 5, 1] ) == [5, 2, 1, 1, 1] def test_rgs(): raises(ValueError, lambda: RGS_unrank(-1, 3)) raises(ValueError, lambda: RGS_unrank(3, 0)) raises(ValueError, lambda: RGS_unrank(10, 1)) raises(ValueError, lambda: Partition.from_rgs(range(3), range(2))) raises(ValueError, lambda: Partition.from_rgs(range(1, 3), range(2))) assert RGS_enum(-1) == 0 assert RGS_enum(1) == 1 assert RGS_unrank(7, 5) == [0, 0, 1, 0, 2] assert RGS_unrank(23, 14) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2] assert RGS_rank(RGS_unrank(40, 100)) == 40
gpl-3.0
androidarmv6/android_external_chromium_org
chrome/test/functional/test_clean_exit.py
69
1495
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import signal import subprocess import tempfile import unittest import pyauto_functional import pyauto import test_utils class SimpleTest(pyauto.PyUITest): def ExtraChromeFlags(self): """Ensures Chrome is launched with custom flags. Returns: A list of extra flags to pass to Chrome when it is launched. """ fd, self._strace_log = tempfile.mkstemp() os.close(fd) extra_flags = ['--no-sandbox', '--child-clean-exit', '--renderer-cmd-prefix=/usr/bin/strace -o %s' % self._strace_log] logging.debug('Strace file is: %s' % self._strace_log) return pyauto.PyUITest.ExtraChromeFlags(self) + extra_flags def testCleanExit(self): """Ensures the renderer process cleanly exits.""" url = self.GetHttpURLForDataPath('title2.html') self.NavigateToURL(url) os.kill(self.GetBrowserInfo()['browser_pid'], signal.SIGINT) self.WaitUntil(lambda: self._IsFileOpen(self._strace_log)) strace_contents = open(self._strace_log).read() self.assertTrue('exit_group' in strace_contents) os.remove(self._strace_log) def _IsFileOpen(self, filename): p = subprocess.Popen(['lsof', filename]) return p.communicate()[0] == '' if __name__ == '__main__': pyauto_functional.Main()
bsd-3-clause
billyhunt/osf.io
scripts/migration/migrate_personal_to_profile_websites.py
40
1417
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to migrate single value personal to profile_websites list.""" from __future__ import unicode_literals import logging import modularodm from modularodm import Q from website import models from website.app import init_app logger = logging.getLogger(__name__) def main(): init_app(routes=False) logger.info("migrating personal to profileWebsites") all_users = 0 migrated_users = 0 for user in get_users_with_social_field(): all_users += 1 if not user.social.get('profileWebsites', None): personal = user.social.get('personal', None) user.social['profileWebsites'] = [personal] if personal else [] migrated_users += 1 logger.info('User {}: social dictionary is now {}'.format(user._id, user.social)) try: user.save() except modularodm.exceptions.ValidationError as err: logger.error('Validation error occurred while trying to save user {}'.format(user._id)) logger.error(str(err)) logger.error('Continuing to next user...') logger.info("merged {} users to profileWebsites out of {} total users".format(migrated_users, all_users)) def get_users_with_social_field(): return models.User.find( Q('social.personal', 'ne', None) ) if __name__ == '__main__': main()
apache-2.0
bedder/gifbot
test/test_gif_bot.py
1
7000
# MIT License # # Copyright (c) 2018 Matthew Bedder (matthew@bedder.co.uk) # # 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. """ Tests for the ``GifBot`` class. """ import unittest from unittest.mock import patch, MagicMock from gif_bot.gif_bot import GifBot api_collector = MagicMock() def mock_api_call(command, *args, **kwargs): if command == "users.list": return { "ok": True, "members": [ {"name": "test_bot_name", "id": "test_bot_id"}, {"name": "test_owner_name", "id": "test_owner_id"} ] } else: api_collector(command, *args, **kwargs) def mock_client(_): return MagicMock(api_call=mock_api_call) def Any(cls): class Any(cls): def __eq__(self, other): return True return Any() @patch("gif_bot.gif_bot.SlackClient", mock_client) @patch("gif_bot.gif_bot.getLogger") @patch("gif_bot.gif_bot.Formatter") @patch("gif_bot.gif_bot.Logger") @patch("gif_bot.gif_bot.RotatingFileHandler") class TestGifBot(unittest.TestCase): def setUp(self): api_collector.reset_mock() def test_is_mention(self, *args): """ The bot should be able to identify direct mentions """ bot = GifBot("test.config", MagicMock()) self.assertTrue(bot.is_mention("@test_bot_name")) self.assertTrue(bot.is_mention("@test_bot_name help")) self.assertFalse(bot.is_mention("Something @test_bot_name")) def test_is_trigger(self, *args): """ The bot should be able to identify trigger words being used in messages """ bot = GifBot("test.config", MagicMock()) self.assertTrue(bot.is_trigger("test_trigger blah")) self.assertTrue(bot.is_trigger("blah test_trigger")) self.assertFalse(bot.is_trigger("something else")) def test_not_trigger_non_message(self, *args): """ The bot should ignore non-messages """ bot = GifBot("test.config", MagicMock()) bot.handle_message({ "channel": "test_channel", "ts": "test_ts" }) api_collector.assert_not_called() def test_not_trigger_self(self, *args): """ The bot shouldn't be able to trigger itself """ bot = GifBot("test.config", MagicMock()) bot.handle_message({ "user": "test_bot_id", "text": "Something something test_trigger", "channel": "test_channel", "ts": "test_ts" }) api_collector.assert_not_called() def test_handle_trigger_message(self, *args): """ The bot should trigger on messages from users containing a trigger word """ bot = GifBot("test.config", MagicMock()) bot.handle_message({ "user": "test_user_id", "text": "Something something test_trigger", "channel": "test_channel", "ts": "test_ts" }) api_collector.assert_any_call("chat.postMessage", text=Any(str), channel="test_channel", as_user=True) api_collector.assert_any_call("reactions.add", name="test_reaction", channel="test_channel", timestamp="test_ts") def test_handle_request_success(self, *args): """ The bot should post a gif and a happy reaction when they can fulfill a request """ bot = GifBot("test.config", MagicMock()) bot.handle_message({ "user": "test_user_id", "text": "@test_bot_name request tag_a1", "channel": "test_channel", "ts": "test_ts" }) api_collector.assert_any_call("chat.postMessage", text=Any(str), channel="test_channel", as_user=True) api_collector.assert_any_call("reactions.add", name="test_reaction", channel="test_channel", timestamp="test_ts") def test_handle_request_failure(self, *args): """ The bot should send a message and react with :brokenheart: when it cannot fulfill a request """ bot = GifBot("test.config", MagicMock()) bot.handle_message({ "user": "test_user_id", "text": "@test_bot_name request invalid_tag", "channel": "test_channel", "ts": "test_ts" }) api_collector.assert_any_call("chat.postMessage", text=Any(str), channel="test_channel", as_user=True) api_collector.assert_any_call("reactions.add", name="broken_heart", channel="test_channel", timestamp="test_ts") def test_admin(self, *args): """ Test that basic admin commands work """ bot = GifBot("test.config", MagicMock()) self.assertNotIn("tag", bot.store.tags) self.assertEqual(len(bot.store.elements), 2) bot.handle_message({ "user": "test_owner_id", "text": "add url tag", "channel": "Dtest_channel", "ts": "test_ts" }) self.assertIn("tag", bot.store.tags) self.assertEqual(len(bot.store.elements), 3) bot.handle_message({ "user": "test_owner_id", "text": "remove url", "channel": "Dtest_channel", "ts": "test_ts" }) self.assertNotIn("tag", bot.store.tags) self.assertEqual(len(bot.store.elements), 2) def test_admin_access(self, *args): """ Test that basic admin commands work only for the owner """ bot = GifBot("test.config", MagicMock()) self.assertNotIn("tag", bot.store.tags) self.assertEqual(len(bot.store.elements), 2) bot.handle_message({ "user": "test_user_id", "text": "add url tag", "channel": "Dtest_channel", "ts": "test_ts" }) self.assertNotIn("tag", bot.store.tags) self.assertEqual(len(bot.store.elements), 2)
mit
google/fedjax
fedjax/models/stackoverflow.py
1
5453
# Copyright 2021 Google LLC # # 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. """Stack Overflow recurrent models.""" from typing import Optional from fedjax.core import metrics from fedjax.core import models import haiku as hk import jax.numpy as jnp def create_lstm_model(vocab_size: int = 10000, embed_size: int = 96, lstm_hidden_size: int = 670, lstm_num_layers: int = 1, share_input_output_embeddings: bool = False, expected_length: Optional[float] = None) -> models.Model: """Creates LSTM language model. Word-level language model for Stack Overflow. Defaults to the model used in: Adaptive Federated Optimization Sashank Reddi, Zachary Charles, Manzil Zaheer, Zachary Garrett, Keith Rush, Jakub Konečný, Sanjiv Kumar, H. Brendan McMahan. https://arxiv.org/abs/2003.00295 Args: vocab_size: The number of possible output words. This does not include special tokens like PAD, BOS, EOS, or OOV. embed_size: Embedding size for each word. lstm_hidden_size: Hidden size for LSTM cells. lstm_num_layers: Number of LSTM layers. share_input_output_embeddings: Whether to share the input embeddings with the output logits. expected_length: Expected average sentence length used to scale the training loss down by `1. / expected_length`. This constant term is used so that the total loss over all the words in a sentence can be scaled down to per word cross entropy values by a constant factor instead of dividing by number of words which can vary across batches. Defaults to no scaling. Returns: Model. """ # TODO(jaero): Replace these with direct references from dataset. pad = 0 bos = 1 eos = 2 oov = vocab_size + 3 full_vocab_size = vocab_size + 4 # We do not guess EOS, and if we guess OOV, it's treated as a mistake. logits_mask = [0. for _ in range(full_vocab_size)] for i in (pad, bos, eos, oov): logits_mask[i] = jnp.NINF logits_mask = tuple(logits_mask) def forward_pass(batch): x = batch['x'] # [time_steps, batch_size, ...]. x = jnp.transpose(x) # [time_steps, batch_size, embed_dim]. embedding_layer = hk.Embed(full_vocab_size, embed_size) embeddings = embedding_layer(x) lstm_layers = [] for _ in range(lstm_num_layers): lstm_layers.extend([ hk.LSTM(hidden_size=lstm_hidden_size), jnp.tanh, # Projection changes dimension from lstm_hidden_size to embed_size. hk.Linear(embed_size) ]) rnn_core = hk.DeepRNN(lstm_layers) initial_state = rnn_core.initial_state(batch_size=embeddings.shape[1]) # [time_steps, batch_size, hidden_size]. output, _ = hk.static_unroll(rnn_core, embeddings, initial_state) if share_input_output_embeddings: output = jnp.dot(output, jnp.transpose(embedding_layer.embeddings)) output = hk.Bias(bias_dims=[-1])(output) else: output = hk.Linear(full_vocab_size)(output) # [batch_size, time_steps, full_vocab_size]. output = jnp.transpose(output, axes=(1, 0, 2)) return output def train_loss(batch, preds): """Returns total loss per sentence optionally scaled down to token level.""" targets = batch['y'] per_token_loss = metrics.unreduced_cross_entropy_loss(targets, preds) # Don't count padded values in loss. per_token_loss *= targets != pad sentence_loss = jnp.sum(per_token_loss, axis=-1) if expected_length is not None: return sentence_loss * (1. / expected_length) return sentence_loss transformed_forward_pass = hk.transform(forward_pass) return models.create_model_from_haiku( transformed_forward_pass=transformed_forward_pass, sample_batch={ 'x': jnp.zeros((1, 1), dtype=jnp.int32), 'y': jnp.zeros((1, 1), dtype=jnp.int32), }, train_loss=train_loss, eval_metrics={ 'accuracy_in_vocab': metrics.SequenceTokenAccuracy( masked_target_values=(pad, eos), logits_mask=logits_mask), 'accuracy_no_eos': metrics.SequenceTokenAccuracy(masked_target_values=(pad, eos)), 'num_tokens': metrics.SequenceTokenCount(masked_target_values=(pad,)), 'sequence_length': metrics.SequenceLength(masked_target_values=(pad,)), 'sequence_loss': metrics.SequenceCrossEntropyLoss(masked_target_values=(pad,)), 'token_loss': metrics.SequenceTokenCrossEntropyLoss( masked_target_values=(pad,)), 'token_oov_rate': metrics.SequenceTokenOOVRate( oov_target_values=(oov,), masked_target_values=(pad,)), 'truncation_rate': metrics.SequenceTruncationRate( eos_target_value=eos, masked_target_values=(pad,)), })
apache-2.0
frdb194/django
tests/forms_tests/models.py
261
3805
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import itertools import tempfile from django.core.files.storage import FileSystemStorage from django.db import models from django.utils.encoding import python_2_unicode_compatible callable_default_counter = itertools.count() def callable_default(): return next(callable_default_counter) temp_storage = FileSystemStorage(location=tempfile.mkdtemp()) class BoundaryModel(models.Model): positive_integer = models.PositiveIntegerField(null=True, blank=True) class Defaults(models.Model): name = models.CharField(max_length=255, default='class default value') def_date = models.DateField(default=datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) class ChoiceModel(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" CHOICES = [ ('', 'No Preference'), ('f', 'Foo'), ('b', 'Bar'), ] INTEGER_CHOICES = [ (None, 'No Preference'), (1, 'Foo'), (2, 'Bar'), ] STRING_CHOICES_WITH_NONE = [ (None, 'No Preference'), ('f', 'Foo'), ('b', 'Bar'), ] name = models.CharField(max_length=10) choice = models.CharField(max_length=2, blank=True, choices=CHOICES) choice_string_w_none = models.CharField( max_length=2, blank=True, null=True, choices=STRING_CHOICES_WITH_NONE) choice_integer = models.IntegerField(choices=INTEGER_CHOICES, blank=True, null=True) @python_2_unicode_compatible class ChoiceOptionModel(models.Model): """Destination for ChoiceFieldModel's ForeignKey. Can't reuse ChoiceModel because error_message tests require that it have no instances.""" name = models.CharField(max_length=10) class Meta: ordering = ('name',) def __str__(self): return 'ChoiceOption %d' % self.pk def choice_default(): return ChoiceOptionModel.objects.get_or_create(name='default')[0].pk def choice_default_list(): return [choice_default()] def int_default(): return 1 def int_list_default(): return [1] class ChoiceFieldModel(models.Model): """Model with ForeignKey to another model, for testing ModelForm generation with ModelChoiceField.""" choice = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, default=choice_default, ) choice_int = models.ForeignKey( ChoiceOptionModel, models.CASCADE, blank=False, related_name='choice_int', default=int_default, ) multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name='multi_choice', default=choice_default_list, ) multi_choice_int = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name='multi_choice_int', default=int_list_default, ) class OptionalMultiChoiceModel(models.Model): multi_choice = models.ManyToManyField( ChoiceOptionModel, blank=False, related_name='not_relevant', default=choice_default, ) multi_choice_optional = models.ManyToManyField( ChoiceOptionModel, blank=True, related_name='not_relevant2', ) class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to='tests') @python_2_unicode_compatible class Group(models.Model): name = models.CharField(max_length=10) def __str__(self): return '%s' % self.name class Cheese(models.Model): name = models.CharField(max_length=100) class Article(models.Model): content = models.TextField()
bsd-3-clause
pawl/wtforms
tests/validators.py
8
13083
# -*- coding: utf-8 -*- from unittest import TestCase from wtforms.compat import text_type from wtforms.validators import ( StopValidation, ValidationError, email, equal_to, ip_address, length, required, optional, regexp, url, NumberRange, AnyOf, NoneOf, mac_address, UUID, input_required, data_required ) from functools import partial from tests.common import DummyField, grab_error_message, grab_stop_message class DummyForm(dict): pass class ValidatorsTest(TestCase): def setUp(self): self.form = DummyForm() def test_email(self): self.assertEqual(email()(self.form, DummyField('foo@bar.dk')), None) self.assertEqual(email()(self.form, DummyField('123@bar.dk')), None) self.assertEqual(email()(self.form, DummyField('foo@456.dk')), None) self.assertEqual(email()(self.form, DummyField('foo@bar456.info')), None) self.assertRaises(ValidationError, email(), self.form, DummyField(None)) self.assertRaises(ValidationError, email(), self.form, DummyField('')) self.assertRaises(ValidationError, email(), self.form, DummyField(' ')) self.assertRaises(ValidationError, email(), self.form, DummyField('foo')) self.assertRaises(ValidationError, email(), self.form, DummyField('bar.dk')) self.assertRaises(ValidationError, email(), self.form, DummyField('foo@')) self.assertRaises(ValidationError, email(), self.form, DummyField('@bar.dk')) self.assertRaises(ValidationError, email(), self.form, DummyField('foo@bar')) self.assertRaises(ValidationError, email(), self.form, DummyField('foo@bar.ab12')) self.assertRaises(ValidationError, email(), self.form, DummyField('foo@.bar.ab')) # Test IDNA domains self.assertEqual(email()(self.form, DummyField(u'foo@bücher.中国')), None) def test_equal_to(self): self.form['foo'] = DummyField('test') self.assertEqual(equal_to('foo')(self.form, self.form['foo']), None) self.assertRaises(ValidationError, equal_to('invalid_field_name'), self.form, DummyField('test')) self.assertRaises(ValidationError, equal_to('foo'), self.form, DummyField('different_value')) def test_ip_address(self): self.assertEqual(ip_address()(self.form, DummyField('127.0.0.1')), None) self.assertRaises(ValidationError, ip_address(), self.form, DummyField('abc.0.0.1')) self.assertRaises(ValidationError, ip_address(), self.form, DummyField('1278.0.0.1')) self.assertRaises(ValidationError, ip_address(), self.form, DummyField('127.0.0.abc')) self.assertRaises(ValidationError, ip_address(), self.form, DummyField('900.200.100.75')) for bad_address in ('abc.0.0.1', 'abcd:1234::123::1', '1:2:3:4:5:6:7:8:9', 'abcd::1ffff'): self.assertRaises(ValidationError, ip_address(ipv6=True), self.form, DummyField(bad_address)) for good_address in ('::1', 'dead:beef:0:0:0:0:42:1', 'abcd:ef::42:1'): self.assertEqual(ip_address(ipv6=True)(self.form, DummyField(good_address)), None) # Test ValueError on ipv6=False and ipv4=False self.assertRaises(ValueError, ip_address, ipv4=False, ipv6=False) def test_mac_address(self): self.assertEqual(mac_address()(self.form, DummyField('01:23:45:67:ab:CD')), None) check_fail = partial( self.assertRaises, ValidationError, mac_address(), self.form ) check_fail(DummyField('00:00:00:00:00')) check_fail(DummyField('01:23:45:67:89:')) check_fail(DummyField('01:23:45:67:89:gh')) check_fail(DummyField('123:23:45:67:89:00')) def test_uuid(self): self.assertEqual( UUID()(self.form, DummyField('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')), None ) self.assertRaises(ValidationError, UUID(), self.form, DummyField('2bc1c94f-deb-43e9-92a1-4775189ec9f8')) self.assertRaises(ValidationError, UUID(), self.form, DummyField('2bc1c94f-0deb-43e9-92a1-4775189ec9f')) self.assertRaises(ValidationError, UUID(), self.form, DummyField('gbc1c94f-0deb-43e9-92a1-4775189ec9f8')) self.assertRaises(ValidationError, UUID(), self.form, DummyField('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')) def test_length(self): field = DummyField('foobar') self.assertEqual(length(min=2, max=6)(self.form, field), None) self.assertRaises(ValidationError, length(min=7), self.form, field) self.assertEqual(length(min=6)(self.form, field), None) self.assertRaises(ValidationError, length(max=5), self.form, field) self.assertEqual(length(max=6)(self.form, field), None) self.assertRaises(AssertionError, length) self.assertRaises(AssertionError, length, min=5, max=2) # Test new formatting features grab = lambda **k: grab_error_message(length(**k), self.form, field) self.assertEqual(grab(min=2, max=5, message='%(min)d and %(max)d'), '2 and 5') self.assertTrue('at least 8' in grab(min=8)) self.assertTrue('longer than 5' in grab(max=5)) self.assertTrue('between 2 and 5' in grab(min=2, max=5)) def test_required(self): self.assertEqual(required()(self.form, DummyField('foobar')), None) self.assertRaises(StopValidation, required(), self.form, DummyField('')) def test_data_required(self): # Make sure we stop the validation chain self.assertEqual(data_required()(self.form, DummyField('foobar')), None) self.assertRaises(StopValidation, data_required(), self.form, DummyField('')) self.assertRaises(StopValidation, data_required(), self.form, DummyField(' ')) self.assertEqual(data_required().field_flags, ('required', )) # Make sure we clobber errors f = DummyField('', ['Invalid Integer Value']) self.assertEqual(len(f.errors), 1) self.assertRaises(StopValidation, data_required(), self.form, f) self.assertEqual(len(f.errors), 0) # Check message and custom message grab = lambda **k: grab_stop_message(data_required(**k), self.form, DummyField('')) self.assertEqual(grab(), 'This field is required.') self.assertEqual(grab(message='foo'), 'foo') def test_input_required(self): self.assertEqual(input_required()(self.form, DummyField('foobar', raw_data=['foobar'])), None) self.assertRaises(StopValidation, input_required(), self.form, DummyField('', raw_data=[''])) self.assertEqual(input_required().field_flags, ('required', )) # Check message and custom message grab = lambda **k: grab_stop_message(input_required(**k), self.form, DummyField('', raw_data=[''])) self.assertEqual(grab(), 'This field is required.') self.assertEqual(grab(message='foo'), 'foo') def test_optional(self): self.assertEqual(optional()(self.form, DummyField('foobar', raw_data=['foobar'])), None) self.assertRaises(StopValidation, optional(), self.form, DummyField('', raw_data=[''])) self.assertEqual(optional().field_flags, ('optional', )) f = DummyField('', ['Invalid Integer Value'], raw_data=['']) self.assertEqual(len(f.errors), 1) self.assertRaises(StopValidation, optional(), self.form, f) self.assertEqual(len(f.errors), 0) # Test for whitespace behavior. whitespace_field = DummyField(' ', raw_data=[' ']) self.assertRaises(StopValidation, optional(), self.form, whitespace_field) self.assertEqual(optional(strip_whitespace=False)(self.form, whitespace_field), None) def test_regexp(self): import re # String regexp self.assertEqual(regexp('^a')(self.form, DummyField('abcd')).group(0), 'a') self.assertEqual(regexp('^a', re.I)(self.form, DummyField('ABcd')).group(0), 'A') self.assertRaises(ValidationError, regexp('^a'), self.form, DummyField('foo')) self.assertRaises(ValidationError, regexp('^a'), self.form, DummyField(None)) # Compiled regexp self.assertEqual(regexp(re.compile('^a'))(self.form, DummyField('abcd')).group(0), 'a') self.assertEqual(regexp(re.compile('^a', re.I))(self.form, DummyField('ABcd')).group(0), 'A') self.assertRaises(ValidationError, regexp(re.compile('^a')), self.form, DummyField('foo')) self.assertRaises(ValidationError, regexp(re.compile('^a')), self.form, DummyField(None)) # Check custom message self.assertEqual(grab_error_message(regexp('^a', message='foo'), self.form, DummyField('f')), 'foo') def test_url(self): self.assertEqual(url()(self.form, DummyField('http://foobar.dk')), None) self.assertEqual(url()(self.form, DummyField('http://foobar.dk/')), None) self.assertEqual(url()(self.form, DummyField('http://foobar.museum/foobar')), None) self.assertEqual(url()(self.form, DummyField('http://127.0.0.1/foobar')), None) self.assertEqual(url()(self.form, DummyField('http://127.0.0.1:9000/fake')), None) self.assertEqual(url(require_tld=False)(self.form, DummyField('http://localhost/foobar')), None) self.assertEqual(url(require_tld=False)(self.form, DummyField('http://foobar')), None) self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar')) self.assertRaises(ValidationError, url(), self.form, DummyField('foobar.dk')) self.assertRaises(ValidationError, url(), self.form, DummyField('http://127.0.0/asdf')) self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.d')) self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.12')) self.assertRaises(ValidationError, url(), self.form, DummyField('http://localhost:abc/a')) # Test IDNA IDNA_TESTS = ( u'http://\u0645\u062b\u0627\u0644.\u0625\u062e\u062a\u0628\u0627\u0631/foo.com', # Arabic test u'http://उदाहरण.परीक्षा/', # Hindi test u'http://실례.테스트', # Hangul test ) for s in IDNA_TESTS: self.assertEqual(url()(self.form, DummyField(s)), None) def test_number_range(self): v = NumberRange(min=5, max=10) self.assertEqual(v(self.form, DummyField(7)), None) self.assertRaises(ValidationError, v, self.form, DummyField(None)) self.assertRaises(ValidationError, v, self.form, DummyField(0)) self.assertRaises(ValidationError, v, self.form, DummyField(12)) self.assertRaises(ValidationError, v, self.form, DummyField(-5)) onlymin = NumberRange(min=5) self.assertEqual(onlymin(self.form, DummyField(500)), None) self.assertRaises(ValidationError, onlymin, self.form, DummyField(4)) onlymax = NumberRange(max=50) self.assertEqual(onlymax(self.form, DummyField(30)), None) self.assertRaises(ValidationError, onlymax, self.form, DummyField(75)) def test_lazy_proxy(self): """Tests that the validators support lazy translation strings for messages.""" class ReallyLazyProxy(object): def __unicode__(self): raise Exception('Translator function called during form declaration: it should be called at response time.') __str__ = __unicode__ message = ReallyLazyProxy() self.assertRaises(Exception, str, message) self.assertRaises(Exception, text_type, message) self.assertTrue(equal_to('fieldname', message=message)) self.assertTrue(length(min=1, message=message)) self.assertTrue(NumberRange(1, 5, message=message)) self.assertTrue(required(message=message)) self.assertTrue(regexp('.+', message=message)) self.assertTrue(email(message=message)) self.assertTrue(ip_address(message=message)) self.assertTrue(url(message=message)) def test_any_of(self): self.assertEqual(AnyOf(['a', 'b', 'c'])(self.form, DummyField('b')), None) self.assertRaises(ValueError, AnyOf(['a', 'b', 'c']), self.form, DummyField(None)) # Anyof in 1.0.1 failed on numbers for formatting the error with a TypeError check_num = AnyOf([1, 2, 3]) self.assertEqual(check_num(self.form, DummyField(2)), None) self.assertRaises(ValueError, check_num, self.form, DummyField(4)) # Test values_formatter formatter = lambda values: '::'.join(text_type(x) for x in reversed(values)) checker = AnyOf([7, 8, 9], message='test %(values)s', values_formatter=formatter) self.assertEqual(grab_error_message(checker, self.form, DummyField(4)), 'test 9::8::7') def test_none_of(self): self.assertEqual(NoneOf(['a', 'b', 'c'])(self.form, DummyField('d')), None) self.assertRaises(ValueError, NoneOf(['a', 'b', 'c']), self.form, DummyField('a'))
bsd-3-clause
t794104/ansible
lib/ansible/plugins/terminal/aruba.py
82
2315
# # (c) 2016 Red Hat Inc. # # 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/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json import re from ansible.errors import AnsibleConnectionFailure from ansible.module_utils._text import to_text, to_bytes from ansible.plugins.terminal import TerminalBase class TerminalModule(TerminalBase): ansi_re = [ # check ECMA-48 Section 5.4 (Control Sequences) re.compile(br'(\x1b\[\?1h\x1b=)'), re.compile(br'((?:\x9b|\x1b\x5b)[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e])'), re.compile(br'\x08.') ] terminal_stdout_re = [ re.compile(br"[\r\n]?[\w]*\(.+\) ?#(?:\s*)$"), re.compile(br"[pP]assword:$"), re.compile(br"(?<=\s)[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\s*#\s*$"), re.compile(br"[\r\n]?[\w\+\-\.:\/\[\]]+(?:\([^\)]+\)){0,3}(?:[>#]) ?$"), ] terminal_stderr_re = [ re.compile(br"% ?Error"), re.compile(br"Error:", re.M), re.compile(br"^% \w+", re.M), re.compile(br"% ?Bad secret"), re.compile(br"invalid input", re.I), re.compile(br"(?:incomplete|ambiguous) command", re.I), re.compile(br"connection timed out", re.I), re.compile(br"[^\r\n]+ not found", re.I), re.compile(br"'[^']' +returned error code: ?\d+"), ] terminal_initial_prompt = b'Press any key to continue' terminal_initial_answer = b'\r' terminal_inital_prompt_newline = False def on_open_shell(self): try: self._exec_cli_command(b'no pag') except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters')
gpl-3.0
10clouds/edx-platform
lms/djangoapps/courseware/tests/test_courses.py
5
14043
# -*- coding: utf-8 -*- """ Tests for course access """ import itertools import ddt from django.conf import settings from django.test.utils import override_settings from django.core.urlresolvers import reverse from django.test.client import RequestFactory import mock from nose.plugins.attrib import attr from opaque_keys.edx.locations import SlashSeparatedCourseKey from courseware.courses import ( get_cms_block_link, get_cms_course_link, get_courses, get_course_about_section, get_course_by_id, get_course_info_section, get_course_overview_with_access, get_course_with_access, ) from courseware.module_render import get_module_for_descriptor from courseware.tests.helpers import get_request_for_user from courseware.model_data import FieldDataCache from lms.djangoapps.courseware.courseware_access_exception import CoursewareAccessException from openedx.core.lib.courses import course_image_url from student.tests.factories import UserFactory from xmodule.modulestore.django import _get_modulestore_branch_setting, modulestore from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.xml_importer import import_course_from_xml from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import ( CourseFactory, ItemFactory, check_mongo_calls ) from xmodule.tests.xml import factories as xml from xmodule.tests.xml import XModuleXmlImportTest CMS_BASE_TEST = 'testcms' TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT @attr('shard_1') @ddt.ddt class CoursesTest(ModuleStoreTestCase): """Test methods related to fetching courses.""" @override_settings(CMS_BASE=CMS_BASE_TEST) def test_get_cms_course_block_link(self): """ Tests that get_cms_course_link_by_id and get_cms_block_link_by_id return the right thing """ self.course = CourseFactory.create( org='org', number='num', display_name='name' ) cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, unicode(self.course.id)) self.assertEqual(cms_url, get_cms_course_link(self.course)) cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, unicode(self.course.location)) self.assertEqual(cms_url, get_cms_block_link(self.course, 'course')) @ddt.data(get_course_with_access, get_course_overview_with_access) def test_get_course_func_with_access_error(self, course_access_func): user = UserFactory.create() course = CourseFactory.create(visible_to_staff_only=True) with self.assertRaises(CoursewareAccessException) as error: course_access_func(user, 'load', course.id) self.assertEqual(error.exception.message, "Course not found.") self.assertEqual(error.exception.access_response.error_code, "not_visible_to_user") self.assertFalse(error.exception.access_response.has_access) @ddt.data( (get_course_with_access, 1), (get_course_overview_with_access, 0), ) @ddt.unpack def test_get_course_func_with_access(self, course_access_func, num_mongo_calls): user = UserFactory.create() course = CourseFactory.create(emit_signals=True) with check_mongo_calls(num_mongo_calls): course_access_func(user, 'load', course.id) def test_get_courses_by_org(self): """ Verify that org filtering performs as expected, and that an empty result is returned if the org passed by the caller does not match the designated microsite org. """ primary = 'primary' alternate = 'alternate' def _fake_get_value(value, default=None): """Used to stub out microsite.get_value().""" if value == 'course_org_filter': return alternate return default user = UserFactory.create() # Pass `emit_signals=True` so that these courses are cached with CourseOverviews. primary_course = CourseFactory.create(org=primary, emit_signals=True) alternate_course = CourseFactory.create(org=alternate, emit_signals=True) self.assertNotEqual(primary_course.org, alternate_course.org) unfiltered_courses = get_courses(user) for org in [primary_course.org, alternate_course.org]: self.assertTrue( any(course.org == org for course in unfiltered_courses) ) filtered_courses = get_courses(user, org=primary) self.assertTrue( all(course.org == primary_course.org for course in filtered_courses) ) with mock.patch('microsite_configuration.microsite.get_value', autospec=True) as mock_get_value: mock_get_value.side_effect = _fake_get_value # Request filtering for an org distinct from the designated microsite org. no_courses = get_courses(user, org=primary) self.assertEqual(no_courses, []) # Request filtering for an org matching the designated microsite org. microsite_courses = get_courses(user, org=alternate) self.assertTrue( all(course.org == alternate_course.org for course in microsite_courses) ) def test_get_courses_with_filter(self): """ Verify that filtering performs as expected. """ user = UserFactory.create() non_mobile_course = CourseFactory.create(emit_signals=True) mobile_course = CourseFactory.create(mobile_available=True, emit_signals=True) test_cases = ( (None, {non_mobile_course.id, mobile_course.id}), (dict(mobile_available=True), {mobile_course.id}), (dict(mobile_available=False), {non_mobile_course.id}), ) for filter_, expected_courses in test_cases: self.assertEqual( { course.id for course in get_courses(user, filter_=filter_) }, expected_courses, "testing get_courses with filter_={}".format(filter_), ) @attr('shard_1') class ModuleStoreBranchSettingTest(ModuleStoreTestCase): """Test methods related to the modulestore branch setting.""" @mock.patch( 'xmodule.modulestore.django.get_current_request_hostname', mock.Mock(return_value='preview.localhost') ) @override_settings( HOSTNAME_MODULESTORE_DEFAULT_MAPPINGS={r'preview\.': ModuleStoreEnum.Branch.draft_preferred}, MODULESTORE_BRANCH='fake_default_branch', ) def test_default_modulestore_preview_mapping(self): self.assertEqual(_get_modulestore_branch_setting(), ModuleStoreEnum.Branch.draft_preferred) @mock.patch( 'xmodule.modulestore.django.get_current_request_hostname', mock.Mock(return_value='localhost') ) @override_settings( HOSTNAME_MODULESTORE_DEFAULT_MAPPINGS={r'preview\.': ModuleStoreEnum.Branch.draft_preferred}, MODULESTORE_BRANCH='fake_default_branch', ) def test_default_modulestore_branch_mapping(self): self.assertEqual(_get_modulestore_branch_setting(), 'fake_default_branch') @attr('shard_1') @override_settings(CMS_BASE=CMS_BASE_TEST) class MongoCourseImageTestCase(ModuleStoreTestCase): """Tests for course image URLs when using a mongo modulestore.""" def test_get_image_url(self): """Test image URL formatting.""" course = CourseFactory.create(org='edX', course='999') self.assertEquals(course_image_url(course), '/c4x/edX/999/asset/{0}'.format(course.course_image)) def test_non_ascii_image_name(self): # Verify that non-ascii image names are cleaned course = CourseFactory.create(course_image=u'before_\N{SNOWMAN}_after.jpg') self.assertEquals( course_image_url(course), '/c4x/{org}/{course}/asset/before___after.jpg'.format( org=course.location.org, course=course.location.course ) ) def test_spaces_in_image_name(self): # Verify that image names with spaces in them are cleaned course = CourseFactory.create(course_image=u'before after.jpg') self.assertEquals( course_image_url(course), '/c4x/{org}/{course}/asset/before_after.jpg'.format( org=course.location.org, course=course.location.course ) ) def test_static_asset_path_course_image_default(self): """ Test that without course_image being set, but static_asset_path being set that we get the right course_image url. """ course = CourseFactory.create(static_asset_path="foo") self.assertEquals( course_image_url(course), '/static/foo/images/course_image.jpg' ) def test_static_asset_path_course_image_set(self): """ Test that with course_image and static_asset_path both being set, that we get the right course_image url. """ course = CourseFactory.create(course_image=u'things_stuff.jpg', static_asset_path="foo") self.assertEquals( course_image_url(course), '/static/foo/things_stuff.jpg' ) @attr('shard_1') class XmlCourseImageTestCase(XModuleXmlImportTest): """Tests for course image URLs when using an xml modulestore.""" def test_get_image_url(self): """Test image URL formatting.""" course = self.process_xml(xml.CourseFactory.build()) self.assertEquals(course_image_url(course), '/static/xml_test_course/images/course_image.jpg') def test_non_ascii_image_name(self): course = self.process_xml(xml.CourseFactory.build(course_image=u'before_\N{SNOWMAN}_after.jpg')) self.assertEquals(course_image_url(course), u'/static/xml_test_course/before_\N{SNOWMAN}_after.jpg') def test_spaces_in_image_name(self): course = self.process_xml(xml.CourseFactory.build(course_image=u'before after.jpg')) self.assertEquals(course_image_url(course), u'/static/xml_test_course/before after.jpg') @attr('shard_1') class CoursesRenderTest(ModuleStoreTestCase): """Test methods related to rendering courses content.""" # TODO: this test relies on the specific setup of the toy course. # It should be rewritten to build the course it needs and then test that. def setUp(self): """ Set up the course and user context """ super(CoursesRenderTest, self).setUp() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['toy']) course_key = course_items[0].id self.course = get_course_by_id(course_key) self.request = get_request_for_user(UserFactory.create()) def test_get_course_info_section_render(self): # Test render works okay course_info = get_course_info_section(self.request, self.request.user, self.course, 'handouts') self.assertEqual(course_info, u"<a href='/c4x/edX/toy/asset/handouts_sample_handout.txt'>Sample</a>") # Test when render raises an exception with mock.patch('courseware.courses.get_module') as mock_module_render: mock_module_render.return_value = mock.MagicMock( render=mock.Mock(side_effect=Exception('Render failed!')) ) course_info = get_course_info_section(self.request, self.request.user, self.course, 'handouts') self.assertIn("this module is temporarily unavailable", course_info) def test_get_course_about_section_render(self): # Test render works okay course_about = get_course_about_section(self.request, self.course, 'short_description') self.assertEqual(course_about, "A course about toys.") # Test when render raises an exception with mock.patch('courseware.courses.get_module') as mock_module_render: mock_module_render.return_value = mock.MagicMock( render=mock.Mock(side_effect=Exception('Render failed!')) ) course_about = get_course_about_section(self.request, self.course, 'short_description') self.assertIn("this module is temporarily unavailable", course_about) @attr('shard_1') @ddt.ddt class CourseInstantiationTests(ModuleStoreTestCase): """ Tests around instantiating a course multiple times in the same request. """ def setUp(self): super(CourseInstantiationTests, self).setUp() self.factory = RequestFactory() @ddt.data(*itertools.product(xrange(5), [ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split], [None, 0, 5])) @ddt.unpack def test_repeated_course_module_instantiation(self, loops, default_store, course_depth): with modulestore().default_store(default_store): course = CourseFactory.create() chapter = ItemFactory(parent=course, category='chapter', graded=True) section = ItemFactory(parent=chapter, category='sequential') __ = ItemFactory(parent=section, category='problem') fake_request = self.factory.get( reverse('progress', kwargs={'course_id': unicode(course.id)}) ) course = modulestore().get_course(course.id, depth=course_depth) for _ in xrange(loops): field_data_cache = FieldDataCache.cache_for_descriptor_descendents( course.id, self.user, course, depth=course_depth ) course_module = get_module_for_descriptor( self.user, fake_request, course, field_data_cache, course.id, course=course ) for chapter in course_module.get_children(): for section in chapter.get_children(): for item in section.get_children(): self.assertTrue(item.graded)
agpl-3.0
theheros/kbengine
kbe/src/lib/python/Lib/unittest/test/test_case.py
50
50475
import difflib import pprint import pickle import re import sys import warnings import inspect from copy import deepcopy from test import support import unittest from .support import ( TestEquality, TestHashing, LoggingResult, ResultWithNoStartTestRunStopTestRun ) class Test(object): "Keep these TestCase classes out of the main namespace" class Foo(unittest.TestCase): def runTest(self): pass def test1(self): pass class Bar(Foo): def test2(self): pass class LoggingTestCase(unittest.TestCase): """A test case which logs its calls.""" def __init__(self, events): super(Test.LoggingTestCase, self).__init__('test') self.events = events def setUp(self): self.events.append('setUp') def test(self): self.events.append('test') def tearDown(self): self.events.append('tearDown') class Test_TestCase(unittest.TestCase, TestEquality, TestHashing): ### Set up attributes used by inherited tests ################################################################ # Used by TestHashing.test_hash and TestEquality.test_eq eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))] # Used by TestEquality.test_ne ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')), (Test.Foo('test1'), Test.Bar('test1')), (Test.Foo('test1'), Test.Bar('test2'))] ################################################################ ### /Set up attributes used by inherited tests # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." # ... # "methodName defaults to "runTest"." # # Make sure it really is optional, and that it defaults to the proper # thing. def test_init__no_test_name(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass self.assertEqual(Test().id()[-13:], '.Test.runTest') # test that TestCase can be instantiated with no args # primarily for use at the interactive interpreter test = unittest.TestCase() test.assertEqual(3, 3) with test.assertRaises(test.failureException): test.assertEqual(3, 2) with self.assertRaises(AttributeError): test.run() # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__valid(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass self.assertEqual(Test('test').id()[-10:], '.Test.test') # "class TestCase([methodName])" # ... # "Each instance of TestCase will run a single test method: the # method named methodName." def test_init__test_name__invalid(self): class Test(unittest.TestCase): def runTest(self): raise MyException() def test(self): pass try: Test('testfoo') except ValueError: pass else: self.fail("Failed to raise ValueError") # "Return the number of tests represented by the this test object. For # TestCase instances, this will always be 1" def test_countTestCases(self): class Foo(unittest.TestCase): def test(self): pass self.assertEqual(Foo('test').countTestCases(), 1) # "Return the default type of test result object to be used to run this # test. For TestCase instances, this will always be # unittest.TestResult; subclasses of TestCase should # override this as necessary." def test_defaultTestResult(self): class Foo(unittest.TestCase): def runTest(self): pass result = Foo().defaultTestResult() self.assertEqual(type(result), unittest.TestResult) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception. def test_run_call_order__error_in_setUp(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run(result) expected = ['startTest', 'setUp', 'addError', 'stopTest'] self.assertEqual(events, expected) # "With a temporary result stopTestRun is called when setUp errors. def test_run_call_order__error_in_setUp_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def setUp(self): super(Foo, self).setUp() raise RuntimeError('raised by Foo.setUp') Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test raises # an error (as opposed to a failure). def test_run_call_order__error_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "With a default result, an error in the test still results in stopTestRun # being called." def test_run_call_order__error_in_test_default_result(self): events = [] class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() raise RuntimeError('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest', 'stopTestRun'] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if the test signals # a failure (as opposed to an error). def test_run_call_order__failure_in_test(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest'] Foo(events).run(result) self.assertEqual(events, expected) # "When a test fails with a default result stopTestRun is still called." def test_run_call_order__failure_in_test_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def test(self): super(Foo, self).test() self.fail('raised by Foo.test') expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addFailure', 'stopTest', 'stopTestRun'] events = [] Foo(events).run() self.assertEqual(events, expected) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if tearDown() raises # an exception. def test_run_call_order__error_in_tearDown(self): events = [] result = LoggingResult(events) class Foo(Test.LoggingTestCase): def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') Foo(events).run(result) expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest'] self.assertEqual(events, expected) # "When tearDown errors with a default result stopTestRun is still called." def test_run_call_order__error_in_tearDown_default_result(self): class Foo(Test.LoggingTestCase): def defaultTestResult(self): return LoggingResult(self.events) def tearDown(self): super(Foo, self).tearDown() raise RuntimeError('raised by Foo.tearDown') events = [] Foo(events).run() expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 'addError', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) # "TestCase.run() still works when the defaultTestResult is a TestResult # that does not support startTestRun and stopTestRun. def test_run_call_order_default_result(self): class Foo(unittest.TestCase): def defaultTestResult(self): return ResultWithNoStartTestRunStopTestRun() def test(self): pass Foo('test').run() # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework. The initial value of this # attribute is AssertionError" def test_failureException__default(self): class Foo(unittest.TestCase): def test(self): pass self.assertTrue(Foo('test').failureException is AssertionError) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__explicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): raise RuntimeError() failureException = RuntimeError self.assertTrue(Foo('test').failureException is RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException def test_failureException__subclassing__implicit_raise(self): events = [] result = LoggingResult(events) class Foo(unittest.TestCase): def test(self): self.fail("foo") failureException = RuntimeError self.assertTrue(Foo('test').failureException is RuntimeError) Foo('test').run(result) expected = ['startTest', 'addFailure', 'stopTest'] self.assertEqual(events, expected) # "The default implementation does nothing." def test_setUp(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().setUp() # "The default implementation does nothing." def test_tearDown(self): class Foo(unittest.TestCase): def runTest(self): pass # ... and nothing should happen Foo().tearDown() # "Return a string identifying the specific test case." # # Because of the vague nature of the docs, I'm not going to lock this # test down too much. Really all that can be asserted is that the id() # will be a string (either 8-byte or unicode -- again, because the docs # just say "string") def test_id(self): class Foo(unittest.TestCase): def runTest(self): pass self.assertIsInstance(Foo().id(), str) # "If result is omitted or None, a temporary result object is created # and used, but is not made available to the caller. As TestCase owns the # temporary result startTestRun and stopTestRun are called. def test_run__uses_defaultTestResult(self): events = [] class Foo(unittest.TestCase): def test(self): events.append('test') def defaultTestResult(self): return LoggingResult(events) # Make run() find a result object on its own Foo('test').run() expected = ['startTestRun', 'startTest', 'test', 'addSuccess', 'stopTest', 'stopTestRun'] self.assertEqual(events, expected) def testShortDescriptionWithoutDocstring(self): self.assertIsNone(self.shortDescription()) @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithOneLineDocstring(self): """Tests shortDescription() for a method with a docstring.""" self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a docstring.') @unittest.skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def testShortDescriptionWithMultiLineDocstring(self): """Tests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is. """ self.assertEqual( self.shortDescription(), 'Tests shortDescription() for a method with a longer ' 'docstring.') def testAddTypeEqualityFunc(self): class SadSnake(object): """Dummy class for test_addTypeEqualityFunc.""" s1, s2 = SadSnake(), SadSnake() self.assertFalse(s1 == s2) def AllSnakesCreatedEqual(a, b, msg=None): return type(a) == type(b) == SadSnake self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) self.assertEqual(s1, s2) # No this doesn't clean up and remove the SadSnake equality func # from this TestCase instance but since its a local nothing else # will ever notice that. def testAssertIs(self): thing = object() self.assertIs(thing, thing) self.assertRaises(self.failureException, self.assertIs, thing, object()) def testAssertIsNot(self): thing = object() self.assertIsNot(thing, object()) self.assertRaises(self.failureException, self.assertIsNot, thing, thing) def testAssertIsInstance(self): thing = [] self.assertIsInstance(thing, list) self.assertRaises(self.failureException, self.assertIsInstance, thing, dict) def testAssertNotIsInstance(self): thing = [] self.assertNotIsInstance(thing, dict) self.assertRaises(self.failureException, self.assertNotIsInstance, thing, list) def testAssertIn(self): animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} self.assertIn('a', 'abc') self.assertIn(2, [1, 2, 3]) self.assertIn('monkey', animals) self.assertNotIn('d', 'abc') self.assertNotIn(0, [1, 2, 3]) self.assertNotIn('otter', animals) self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) self.assertRaises(self.failureException, self.assertIn, 'elephant', animals) self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) self.assertRaises(self.failureException, self.assertNotIn, 'cow', animals) def testAssertDictContainsSubset(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertDictContainsSubset({}, {}) self.assertDictContainsSubset({}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1}) self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({1: "one"}, {}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 2}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) with self.assertRaises(self.failureException): self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) one = ''.join(chr(i) for i in range(255)) # this used to cause a UnicodeDecodeError constructing the failure msg with self.assertRaises(self.failureException): self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) def testAssertEqual(self): equal_pairs = [ ((), ()), ({}, {}), ([], []), (set(), set()), (frozenset(), frozenset())] for a, b in equal_pairs: # This mess of try excepts is to test the assertEqual behavior # itself. try: self.assertEqual(a, b) except self.failureException: self.fail('assertEqual(%r, %r) failed' % (a, b)) try: self.assertEqual(a, b, msg='foo') except self.failureException: self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) try: self.assertEqual(a, b, 'foo') except self.failureException: self.fail('assertEqual(%r, %r) with third parameter failed' % (a, b)) unequal_pairs = [ ((), []), ({}, set()), (set([4,1]), frozenset([4,2])), (frozenset([4,5]), set([2,3])), (set([3,4]), set([5,4]))] for a, b in unequal_pairs: self.assertRaises(self.failureException, self.assertEqual, a, b) self.assertRaises(self.failureException, self.assertEqual, a, b, 'foo') self.assertRaises(self.failureException, self.assertEqual, a, b, msg='foo') def testEquality(self): self.assertListEqual([], []) self.assertTupleEqual((), ()) self.assertSequenceEqual([], ()) a = [0, 'a', []] b = [] self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, a, b) self.assertRaises(unittest.TestCase.failureException, self.assertListEqual, tuple(a), tuple(b)) self.assertRaises(unittest.TestCase.failureException, self.assertSequenceEqual, a, tuple(b)) b.extend(a) self.assertListEqual(a, b) self.assertTupleEqual(tuple(a), tuple(b)) self.assertSequenceEqual(a, tuple(b)) self.assertSequenceEqual(tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, a, tuple(b)) self.assertRaises(self.failureException, self.assertTupleEqual, tuple(a), b) self.assertRaises(self.failureException, self.assertListEqual, None, b) self.assertRaises(self.failureException, self.assertTupleEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertSequenceEqual, None, tuple(b)) self.assertRaises(self.failureException, self.assertListEqual, 1, 1) self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) self.assertRaises(self.failureException, self.assertSequenceEqual, 1, 1) self.assertDictEqual({}, {}) c = { 'x': 1 } d = {} self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d) d.update(c) self.assertDictEqual(c, d) d['x'] = 0 self.assertRaises(unittest.TestCase.failureException, self.assertDictEqual, c, d, 'These are unequal') self.assertRaises(self.failureException, self.assertDictEqual, None, d) self.assertRaises(self.failureException, self.assertDictEqual, [], d) self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) def testAssertSequenceEqualMaxDiff(self): self.assertEqual(self.maxDiff, 80*8) seq1 = 'a' + 'x' * 80**2 seq2 = 'b' + 'x' * 80**2 diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), pprint.pformat(seq2).splitlines())) # the +1 is the leading \n added by assertSequenceEqual omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) self.maxDiff = len(diff)//2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertTrue(len(msg) < len(diff)) self.assertIn(omitted, msg) self.maxDiff = len(diff) * 2 try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertTrue(len(msg) > len(diff)) self.assertNotIn(omitted, msg) self.maxDiff = None try: self.assertSequenceEqual(seq1, seq2) except self.failureException as e: msg = e.args[0] else: self.fail('assertSequenceEqual did not fail.') self.assertTrue(len(msg) > len(diff)) self.assertNotIn(omitted, msg) def testTruncateMessage(self): self.maxDiff = 1 message = self._truncateMessage('foo', 'bar') omitted = unittest.case.DIFF_OMITTED % len('bar') self.assertEqual(message, 'foo' + omitted) self.maxDiff = None message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') self.maxDiff = 4 message = self._truncateMessage('foo', 'bar') self.assertEqual(message, 'foobar') def testAssertDictEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertDictEqual({}, {1: 0}) except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertDictEqual did not fail') def testAssertMultiLineEqualTruncates(self): test = unittest.TestCase('assertEqual') def truncate(msg, diff): return 'foo' test._truncateMessage = truncate try: test.assertMultiLineEqual('foo', 'bar') except self.failureException as e: self.assertEqual(str(e), 'foo') else: self.fail('assertMultiLineEqual did not fail') def testAssertEqual_diffThreshold(self): # check threshold value self.assertEqual(self._diffThreshold, 2**16) # disable madDiff to get diff markers self.maxDiff = None # set a lower threshold value and add a cleanup to restore it old_threshold = self._diffThreshold self._diffThreshold = 2**8 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) # under the threshold: diff marker (^) in error message s = 'x' * (2**7) with self.assertRaises(self.failureException) as cm: self.assertEqual(s + 'a', s + 'b') self.assertIn('^', str(cm.exception)) self.assertEqual(s + 'a', s + 'a') # over the threshold: diff not used and marker (^) not in error message s = 'x' * (2**9) # if the path that uses difflib is taken, _truncateMessage will be # called -- replace it with explodingTruncation to verify that this # doesn't happen def explodingTruncation(message, diff): raise SystemError('this should not be raised') old_truncate = self._truncateMessage self._truncateMessage = explodingTruncation self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) s1, s2 = s + 'a', s + 'b' with self.assertRaises(self.failureException) as cm: self.assertEqual(s1, s2) self.assertNotIn('^', str(cm.exception)) self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) self.assertEqual(s + 'a', s + 'a') def testAssertCountEqual(self): a = object() self.assertCountEqual([1, 2, 3], [3, 2, 1]) self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) self.assertRaises(self.failureException, self.assertCountEqual, [1, 2] + [3] * 100, [1] * 100 + [2, 3]) self.assertRaises(self.failureException, self.assertCountEqual, [1, "2", "a", "a"], ["a", "2", True, 1]) self.assertRaises(self.failureException, self.assertCountEqual, [10], [10, 11]) self.assertRaises(self.failureException, self.assertCountEqual, [10, 11], [10]) self.assertRaises(self.failureException, self.assertCountEqual, [10, 11, 10], [10, 11]) # Test that sequences of unhashable objects can be tested for sameness: self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]]) # Test that iterator of unhashable objects can be tested for sameness: self.assertCountEqual(iter([1, 2, [], 3, 4]), iter([1, 2, [], 3, 4])) # hashable types, but not orderable self.assertRaises(self.failureException, self.assertCountEqual, [], [divmod, 'x', 1, 5j, 2j, frozenset()]) # comparing dicts self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) # comparing heterogenous non-hashable sequences self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1]) self.assertRaises(self.failureException, self.assertCountEqual, [], [divmod, [], 'x', 1, 5j, 2j, set()]) self.assertRaises(self.failureException, self.assertCountEqual, [[1]], [[2]]) # Same elements, but not same sequence length self.assertRaises(self.failureException, self.assertCountEqual, [1, 1, 2], [2, 1]) self.assertRaises(self.failureException, self.assertCountEqual, [1, 1, "2", "a", "a"], ["2", "2", True, "a"]) self.assertRaises(self.failureException, self.assertCountEqual, [1, {'b': 2}, None, True], [{'b': 2}, True, None]) # Same elements which don't reliably compare, in # different order, see issue 10242 a = [{2,4}, {1,2}] b = a[::-1] self.assertCountEqual(a, b) # test utility functions supporting assertCountEqual() diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) diffs = unittest.util._count_diff_all_purpose([[]], []) self.assertEqual(diffs, [(1, 0, [])]) diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce')) expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} self.assertEqual(diffs, expected) def testAssertSetEqual(self): set1 = set() set2 = set() self.assertSetEqual(set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, None, set2) self.assertRaises(self.failureException, self.assertSetEqual, [], set2) self.assertRaises(self.failureException, self.assertSetEqual, set1, None) self.assertRaises(self.failureException, self.assertSetEqual, set1, []) set1 = set(['a']) set2 = set() self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = set(['a']) self.assertSetEqual(set1, set2) set1 = set(['a']) set2 = set(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a']) set2 = frozenset(['a', 'b']) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) set1 = set(['a', 'b']) set2 = frozenset(['a', 'b']) self.assertSetEqual(set1, set2) set1 = set() set2 = "foo" self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) # make sure any string formatting is tuple-safe set1 = set([(0, 1), (2, 3)]) set2 = set([(4, 5)]) self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) def testInequality(self): # Try ints self.assertGreater(2, 1) self.assertGreaterEqual(2, 1) self.assertGreaterEqual(1, 1) self.assertLess(1, 2) self.assertLessEqual(1, 2) self.assertLessEqual(1, 1) self.assertRaises(self.failureException, self.assertGreater, 1, 2) self.assertRaises(self.failureException, self.assertGreater, 1, 1) self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) self.assertRaises(self.failureException, self.assertLess, 2, 1) self.assertRaises(self.failureException, self.assertLess, 1, 1) self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) # Try Floats self.assertGreater(1.1, 1.0) self.assertGreaterEqual(1.1, 1.0) self.assertGreaterEqual(1.0, 1.0) self.assertLess(1.0, 1.1) self.assertLessEqual(1.0, 1.1) self.assertLessEqual(1.0, 1.0) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) # Try Strings self.assertGreater('bug', 'ant') self.assertGreaterEqual('bug', 'ant') self.assertGreaterEqual('ant', 'ant') self.assertLess('ant', 'bug') self.assertLessEqual('ant', 'bug') self.assertLessEqual('ant', 'ant') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') # Try bytes self.assertGreater(b'bug', b'ant') self.assertGreaterEqual(b'bug', b'ant') self.assertGreaterEqual(b'ant', b'ant') self.assertLess(b'ant', b'bug') self.assertLessEqual(b'ant', b'bug') self.assertLessEqual(b'ant', b'ant') self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', b'bug') self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') def testAssertMultiLineEqual(self): sample_text = """\ http://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] """ revised_sample_text = """\ http://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. """ sample_text_error = """\ - http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. """ self.maxDiff = None try: self.assertMultiLineEqual(sample_text, revised_sample_text) except self.failureException as e: # need to remove the first line of the error message error = str(e).split('\n', 1)[1] # no fair testing ourself with ourself, and assertEqual is used for strings # so can't use assertEqual either. Just use assertTrue. self.assertTrue(sample_text_error == error) def testAsertEqualSingleLine(self): sample_text = "laden swallows fly slowly" revised_sample_text = "unladen swallows fly quickly" sample_text_error = """\ - laden swallows fly slowly ? ^^^^ + unladen swallows fly quickly ? ++ ^^^^^ """ try: self.assertEqual(sample_text, revised_sample_text) except self.failureException as e: error = str(e).split('\n', 1)[1] self.assertTrue(sample_text_error == error) def testAssertIsNone(self): self.assertIsNone(None) self.assertRaises(self.failureException, self.assertIsNone, False) self.assertIsNotNone('DjZoPloGears on Rails') self.assertRaises(self.failureException, self.assertIsNotNone, None) def testAssertRegex(self): self.assertRegex('asdfabasdf', r'ab+') self.assertRaises(self.failureException, self.assertRegex, 'saaas', r'aaaa') def testAssertRaisesRegex(self): class ExceptionMock(Exception): pass def Stub(): raise ExceptionMock('We expect') self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) def testAssertNotRaisesRegex(self): self.assertRaisesRegex( self.failureException, '^Exception not raised by <lambda>$', self.assertRaisesRegex, Exception, re.compile('x'), lambda: None) self.assertRaisesRegex( self.failureException, '^Exception not raised by <lambda>$', self.assertRaisesRegex, Exception, 'x', lambda: None) def testAssertRaisesRegexMismatch(self): def Stub(): raise Exception('Unexpected') self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegex, Exception, '^Expected$', Stub) self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', self.assertRaisesRegex, Exception, re.compile('^Expected$'), Stub) def testAssertRaisesExcValue(self): class ExceptionMock(Exception): pass def Stub(foo): raise ExceptionMock(foo) v = "particular value" ctx = self.assertRaises(ExceptionMock) with ctx: Stub(v) e = ctx.exception self.assertIsInstance(e, ExceptionMock) self.assertEqual(e.args[0], v) def testAssertWarnsCallable(self): def _runtime_warn(): warnings.warn("foo", RuntimeWarning) # Success when the right warning is triggered, even several times self.assertWarns(RuntimeWarning, _runtime_warn) self.assertWarns(RuntimeWarning, _runtime_warn) # A tuple of warning classes is accepted self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) # *args and **kwargs also work self.assertWarns(RuntimeWarning, warnings.warn, "foo", category=RuntimeWarning) # Failure when no warning is triggered with self.assertRaises(self.failureException): self.assertWarns(RuntimeWarning, lambda: 0) # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarns(DeprecationWarning, _runtime_warn) # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): self.assertWarns(DeprecationWarning, _runtime_warn) def testAssertWarnsContext(self): # Believe it or not, it is preferrable to duplicate all tests above, # to make sure the __warningregistry__ $@ is circumvented correctly. def _runtime_warn(): warnings.warn("foo", RuntimeWarning) _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] with self.assertWarns(RuntimeWarning) as cm: _runtime_warn() # A tuple of warning classes is accepted with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm: _runtime_warn() # The context manager exposes various useful attributes self.assertIsInstance(cm.warning, RuntimeWarning) self.assertEqual(cm.warning.args[0], "foo") self.assertIn("test_case.py", cm.filename) self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) # Same with several warnings with self.assertWarns(RuntimeWarning): _runtime_warn() _runtime_warn() with self.assertWarns(RuntimeWarning): warnings.warn("foo", category=RuntimeWarning) # Failure when no warning is triggered with self.assertRaises(self.failureException): with self.assertWarns(RuntimeWarning): pass # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarns(DeprecationWarning): _runtime_warn() # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): with self.assertWarns(DeprecationWarning): _runtime_warn() def testAssertWarnsRegexCallable(self): def _runtime_warn(msg): warnings.warn(msg, RuntimeWarning) self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "foox") # Failure when no warning is triggered with self.assertRaises(self.failureException): self.assertWarnsRegex(RuntimeWarning, "o+", lambda: 0) # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarnsRegex(DeprecationWarning, "o+", _runtime_warn, "foox") # Failure when message doesn't match with self.assertRaises(self.failureException): self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a # failureException. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises((RuntimeWarning, self.failureException)): self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "barz") def testAssertWarnsRegexContext(self): # Same as above, but with assertWarnsRegex as a context manager def _runtime_warn(msg): warnings.warn(msg, RuntimeWarning) _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] with self.assertWarnsRegex(RuntimeWarning, "o+") as cm: _runtime_warn("foox") self.assertIsInstance(cm.warning, RuntimeWarning) self.assertEqual(cm.warning.args[0], "foox") self.assertIn("test_case.py", cm.filename) self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) # Failure when no warning is triggered with self.assertRaises(self.failureException): with self.assertWarnsRegex(RuntimeWarning, "o+"): pass # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarnsRegex(DeprecationWarning, "o+"): _runtime_warn("foox") # Failure when message doesn't match with self.assertRaises(self.failureException): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a # failureException. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises((RuntimeWarning, self.failureException)): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") def testDeprecatedMethodNames(self): """ Test that the deprecated methods raise a DeprecationWarning. See #9424. """ old = ( (self.failIfEqual, (3, 5)), (self.assertNotEquals, (3, 5)), (self.failUnlessEqual, (3, 3)), (self.assertEquals, (3, 3)), (self.failUnlessAlmostEqual, (2.0, 2.0)), (self.assertAlmostEquals, (2.0, 2.0)), (self.failIfAlmostEqual, (3.0, 5.0)), (self.assertNotAlmostEquals, (3.0, 5.0)), (self.failUnless, (True,)), (self.assert_, (True,)), (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')), (self.failIf, (False,)), (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3])), (self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))), (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])), (self.assertRegexpMatches, ('bar', 'bar')), ) for meth, args in old: with self.assertWarns(DeprecationWarning): meth(*args) def testDeprecatedFailMethods(self): """Test that the deprecated fail* methods get removed in 3.3""" if sys.version_info[:2] < (3, 3): return deprecated_names = [ 'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', 'assertSameElements', 'assertDictContainsSubset', ] for deprecated_name in deprecated_names: with self.assertRaises(AttributeError): getattr(self, deprecated_name) # remove these in 3.3 def testDeepcopy(self): # Issue: 5660 class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') # This shouldn't blow up deepcopy(test) def testPickle(self): # Issue 10326 # Can't use TestCase classes defined in Test class as # pickle does not work with inner classes test = unittest.TestCase('run') for protocol in range(pickle.HIGHEST_PROTOCOL + 1): # blew up prior to fix pickled_test = pickle.dumps(test, protocol=protocol) unpickled_test = pickle.loads(pickled_test) self.assertEqual(test, unpickled_test) # exercise the TestCase instance in a way that will invoke # the type equality lookup mechanism unpickled_test.assertEqual(set(), set()) def testKeyboardInterrupt(self): def _raise(self=None): raise KeyboardInterrupt def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): with self.assertRaises(KeyboardInterrupt): klass('test_something').run() def testSkippingEverywhere(self): def _skip(self=None): raise unittest.SkipTest('some reason') def nothing(self): pass class Test1(unittest.TestCase): test_something = _skip class Test2(unittest.TestCase): setUp = _skip test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _skip class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_skip) for klass in (Test1, Test2, Test3, Test4): result = unittest.TestResult() klass('test_something').run(result) self.assertEqual(len(result.skipped), 1) self.assertEqual(result.testsRun, 1) def testSystemExit(self): def _raise(self=None): raise SystemExit def nothing(self): pass class Test1(unittest.TestCase): test_something = _raise class Test2(unittest.TestCase): setUp = _raise test_something = nothing class Test3(unittest.TestCase): test_something = nothing tearDown = _raise class Test4(unittest.TestCase): def test_something(self): self.addCleanup(_raise) for klass in (Test1, Test2, Test3, Test4): result = unittest.TestResult() klass('test_something').run(result) self.assertEqual(len(result.errors), 1) self.assertEqual(result.testsRun, 1)
lgpl-3.0
cloudbase/cinder
cinder/tests/unit/api/v3/test_messages.py
5
5249
# 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 cinder.api import extensions from cinder.api.v3 import messages from cinder import context from cinder import exception from cinder.message import api as message_api from cinder.message import defined_messages from cinder import test from cinder.tests.unit.api import fakes from cinder.tests.unit.api.v3 import fakes as v3_fakes NS = '{http://docs.openstack.org/api/openstack-block-storage/3.0/content}' class MessageApiTest(test.TestCase): def setUp(self): super(MessageApiTest, self).setUp() self.ext_mgr = extensions.ExtensionManager() self.ext_mgr.extensions = {} self.controller = messages.MessagesController(self.ext_mgr) self.maxDiff = None self.ctxt = context.RequestContext('admin', 'fakeproject', True) def _expected_message_from_controller(self, id): message = v3_fakes.fake_message(id) links = [ {'href': 'http://localhost/v3/fakeproject/messages/%s' % id, 'rel': 'self'}, {'href': 'http://localhost/fakeproject/messages/%s' % id, 'rel': 'bookmark'}, ] return { 'message': { 'id': message.get('id'), 'user_message': defined_messages.get_message_text( message.get('event_id')), 'request_id': message.get('request_id'), 'event_id': message.get('event_id'), 'created_at': message.get('created_at'), 'message_level': message.get('message_level'), 'guaranteed_until': message.get('expires_at'), 'links': links, } } def test_show(self): self.mock_object(message_api.API, 'get', v3_fakes.fake_message_get) req = fakes.HTTPRequest.blank( '/v3/messages/%s' % fakes.FAKE_UUID, version=messages.MESSAGES_BASE_MICRO_VERSION) req.environ['cinder.context'] = self.ctxt res_dict = self.controller.show(req, fakes.FAKE_UUID) ex = self._expected_message_from_controller(fakes.FAKE_UUID) self.assertEqual(ex, res_dict) def test_show_not_found(self): self.mock_object(message_api.API, 'get', side_effect=exception.MessageNotFound( message_id=fakes.FAKE_UUID)) req = fakes.HTTPRequest.blank( '/v3/messages/%s' % fakes.FAKE_UUID, version=messages.MESSAGES_BASE_MICRO_VERSION) req.environ['cinder.context'] = self.ctxt self.assertRaises(exception.MessageNotFound, self.controller.show, req, fakes.FAKE_UUID) def test_show_pre_microversion(self): self.mock_object(message_api.API, 'get', v3_fakes.fake_message_get) req = fakes.HTTPRequest.blank('/v3/messages/%s' % fakes.FAKE_UUID, version='3.0') req.environ['cinder.context'] = self.ctxt self.assertRaises(exception.VersionNotFoundForAPIMethod, self.controller.show, req, fakes.FAKE_UUID) def test_delete(self): self.mock_object(message_api.API, 'get', v3_fakes.fake_message_get) self.mock_object(message_api.API, 'delete') req = fakes.HTTPRequest.blank( '/v3/messages/%s' % fakes.FAKE_UUID, version=messages.MESSAGES_BASE_MICRO_VERSION) req.environ['cinder.context'] = self.ctxt resp = self.controller.delete(req, fakes.FAKE_UUID) self.assertEqual(204, resp.status_int) self.assertTrue(message_api.API.delete.called) def test_delete_not_found(self): self.mock_object(message_api.API, 'get', side_effect=exception.MessageNotFound( message_id=fakes.FAKE_UUID)) req = fakes.HTTPRequest.blank( '/v3/messages/%s' % fakes.FAKE_UUID, version=messages.MESSAGES_BASE_MICRO_VERSION) self.assertRaises(exception.MessageNotFound, self.controller.delete, req, fakes.FAKE_UUID) def test_index(self): self.mock_object(message_api.API, 'get_all', return_value=[v3_fakes.fake_message(fakes.FAKE_UUID)]) req = fakes.HTTPRequest.blank( '/v3/messages/%s' % fakes.FAKE_UUID, version=messages.MESSAGES_BASE_MICRO_VERSION) req.environ['cinder.context'] = self.ctxt res_dict = self.controller.index(req) ex = self._expected_message_from_controller(fakes.FAKE_UUID) expected = { 'messages': [ex['message']] } self.assertDictMatch(expected, res_dict)
apache-2.0
MattRijk/django-ecomsite
lib/python2.7/site-packages/django/core/servers/fastcgi.py
241
6638
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is a adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standalone or from the django-admin / manage.py scripts using the "runfcgi" directive. Run with the extra option "help" for a list of additional options you can pass to this server. """ import os import sys from django.utils import importlib __version__ = "0.1" __all__ = ["runfastcgi"] FASTCGI_OPTIONS = { 'protocol': 'fcgi', 'host': None, 'port': None, 'socket': None, 'method': 'fork', 'daemonize': None, 'workdir': '/', 'pidfile': None, 'maxspare': 5, 'minspare': 2, 'maxchildren': 50, 'maxrequests': 0, 'debug': None, 'outlog': None, 'errlog': None, 'umask': None, } FASTCGI_HELP = r""" Run this project as a fastcgi (or some other protocol supported by flup) application. To do this, the flup package from http://www.saddi.com/software/flup/ is required. runfcgi [options] [fcgi settings] Optional Fcgi settings: (setting=value) protocol=PROTOCOL fcgi, scgi, ajp, ... (default %(protocol)s) host=HOSTNAME hostname to listen on. port=PORTNUM port to listen on. socket=FILE UNIX socket to listen on. method=IMPL prefork or threaded (default %(method)s). maxrequests=NUMBER number of requests a child handles before it is killed and a new child is forked (0 = no limit). maxspare=NUMBER max number of spare processes / threads (default %(maxspare)s). minspare=NUMBER min number of spare processes / threads (default %(minspare)s). maxchildren=NUMBER hard limit number of processes / threads (default %(maxchildren)s). daemonize=BOOL whether to detach from terminal. pidfile=FILE write the spawned process-id to this file. workdir=DIRECTORY change to this directory when daemonizing (default %(workdir)s). debug=BOOL set to true to enable flup tracebacks. outlog=FILE write stdout to this file. errlog=FILE write stderr to this file. umask=UMASK umask to use when daemonizing, in octal notation (default 022). Examples: Run a "standard" fastcgi process on a file-descriptor (for Web servers which spawn your processes for you) $ manage.py runfcgi method=threaded Run a scgi server on a TCP host/port $ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025 Run a fastcgi server on a UNIX domain socket (posix platforms only) $ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock Run a fastCGI as a daemon and write the spawned PID in a file $ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \ daemonize=true pidfile=/var/run/django-fcgi.pid """ % FASTCGI_OPTIONS def fastcgi_help(message=None): print(FASTCGI_HELP) if message: print(message) return False def runfastcgi(argset=[], **kwargs): options = FASTCGI_OPTIONS.copy() options.update(kwargs) for x in argset: if "=" in x: k, v = x.split('=', 1) else: k, v = x, True options[k.lower()] = v if "help" in options: return fastcgi_help() try: import flup except ImportError as e: sys.stderr.write("ERROR: %s\n" % e) sys.stderr.write(" Unable to load the flup package. In order to run django\n") sys.stderr.write(" as a FastCGI application, you will need to get flup from\n") sys.stderr.write(" http://www.saddi.com/software/flup/ If you've already\n") sys.stderr.write(" installed flup, then make sure you have it in your PYTHONPATH.\n") return False flup_module = 'server.' + options['protocol'] if options['method'] in ('prefork', 'fork'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxChildren': int(options["maxchildren"]), 'maxRequests': int(options["maxrequests"]), } flup_module += '_fork' elif options['method'] in ('thread', 'threaded'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxThreads': int(options["maxchildren"]), } else: return fastcgi_help("ERROR: Implementation must be one of prefork or " "thread.") wsgi_opts['debug'] = options['debug'] is not None try: module = importlib.import_module('.%s' % flup_module, 'flup') WSGIServer = module.WSGIServer except Exception: print("Can't import flup." + flup_module) return False # Prep up and go from django.core.servers.basehttp import get_internal_wsgi_application if options["host"] and options["port"] and not options["socket"]: wsgi_opts['bindAddress'] = (options["host"], int(options["port"])) elif options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = options["socket"] elif not options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = None else: return fastcgi_help("Invalid combination of host, port, socket.") if options["daemonize"] is None: # Default to daemonizing if we're running on a socket/named pipe. daemonize = (wsgi_opts['bindAddress'] is not None) else: if options["daemonize"].lower() in ('true', 'yes', 't'): daemonize = True elif options["daemonize"].lower() in ('false', 'no', 'f'): daemonize = False else: return fastcgi_help("ERROR: Invalid option for daemonize " "parameter.") daemon_kwargs = {} if options['outlog']: daemon_kwargs['out_log'] = options['outlog'] if options['errlog']: daemon_kwargs['err_log'] = options['errlog'] if options['umask']: daemon_kwargs['umask'] = int(options['umask'], 8) if daemonize: from django.utils.daemonize import become_daemon become_daemon(our_home_dir=options["workdir"], **daemon_kwargs) if options["pidfile"]: with open(options["pidfile"], "w") as fp: fp.write("%d\n" % os.getpid()) WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run() if __name__ == '__main__': runfastcgi(sys.argv[1:])
cc0-1.0
ProfessorX/Emacs-Laptop
elpa/anaconda-mode-20140916.600/jedi/evaluate/compiled/__init__.py
17
13463
""" Imitate the parser representation. """ import inspect import re import sys import os from jedi._compatibility import builtins as _builtins, unicode from jedi import debug from jedi.cache import underscore_memoization, memoize from jedi.evaluate.sys_path import get_sys_path from jedi.parser.representation import Param, SubModule, Base, IsScope, Operator from jedi.evaluate.helpers import FakeName from . import fake _sep = os.path.sep if os.path.altsep is not None: _sep += os.path.altsep _path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.format(re.escape(_sep))) del _sep class CompiledObject(Base): # comply with the parser start_pos = 0, 0 asserts = [] path = None # modules have this attribute - set it to None. def __init__(self, obj, parent=None): self.obj = obj self.parent = parent @property def doc(self): return inspect.getdoc(self.obj) or '' @property def params(self): params_str, ret = self._parse_function_doc() tokens = params_str.split(',') params = [] module = SubModule(self.get_parent_until().name) # it seems like start_pos/end_pos is always (0, 0) for a compiled # object start_pos, end_pos = (0, 0), (0, 0) for p in tokens: parts = [FakeName(part) for part in p.strip().split('=')] if len(parts) >= 2: parts.insert(1, Operator(module, '=', module, (0, 0))) params.append(Param(module, parts, start_pos, end_pos, builtin)) return params def __repr__(self): return '<%s: %s>' % (type(self).__name__, repr(self.obj)) @underscore_memoization def _parse_function_doc(self): if self.doc is None: return '', '' return _parse_function_doc(self.doc) def type(self): cls = self._cls().obj if inspect.isclass(cls): return 'class' elif inspect.ismodule(cls): return 'module' elif inspect.isbuiltin(cls) or inspect.ismethod(cls) \ or inspect.ismethoddescriptor(cls): return 'function' def is_executable_class(self): return inspect.isclass(self.obj) @underscore_memoization def _cls(self): # Ensures that a CompiledObject is returned that is not an instance (like list) if fake.is_class_instance(self.obj): try: c = self.obj.__class__ except AttributeError: # happens with numpy.core.umath._UFUNC_API (you get it # automatically by doing `import numpy`. c = type(None) return CompiledObject(c, self.parent) return self def get_defined_names(self): if inspect.ismodule(self.obj): return self.instance_names() else: return type_names + self.instance_names() def scope_names_generator(self, position=None): yield self, self.get_defined_names() @underscore_memoization def instance_names(self): names = [] cls = self._cls() for name in dir(cls.obj): names.append(CompiledName(cls, name)) return names def get_subscope_by_name(self, name): if name in dir(self._cls().obj): return CompiledName(self._cls(), name).parent else: raise KeyError("CompiledObject doesn't have an attribute '%s'." % name) def get_index_types(self, evaluator, index_array): # If the object doesn't have `__getitem__`, just raise the # AttributeError. if not hasattr(self.obj, '__getitem__'): debug.warning('Tried to call __getitem__ on non-iterable.') return [] if type(self.obj) not in (str, list, tuple, unicode, bytes, bytearray, dict): # Get rid of side effects, we won't call custom `__getitem__`s. return [] result = [] from jedi.evaluate.iterable import create_indexes_or_slices for typ in create_indexes_or_slices(evaluator, index_array): index = None try: index = typ.obj new = self.obj[index] except (KeyError, IndexError, TypeError, AttributeError): # Just try, we don't care if it fails, except for slices. if isinstance(index, slice): result.append(self) else: result.append(CompiledObject(new)) if not result: try: for obj in self.obj: result.append(CompiledObject(obj)) except TypeError: pass # self.obj maynot have an __iter__ method. return result @property def name(self): # might not exist sometimes (raises AttributeError) return self._cls().obj.__name__ def execute_function(self, evaluator, params): if self.type() != 'function': return for name in self._parse_function_doc()[1].split(): try: bltn_obj = _create_from_name(builtin, builtin, name) except AttributeError: continue else: if isinstance(bltn_obj, CompiledObject): # We want everything except None. if bltn_obj.obj is not None: yield bltn_obj else: for result in evaluator.execute(bltn_obj, params): yield result @property @underscore_memoization def subscopes(self): """ Returns only the faked scopes - the other ones are not important for internal analysis. """ module = self.get_parent_until() faked_subscopes = [] for name in dir(self._cls().obj): f = fake.get_faked(module.obj, self.obj, name) if f: f.parent = self faked_subscopes.append(f) return faked_subscopes def is_scope(self): return True def get_self_attributes(self): return [] # Instance compatibility def get_imports(self): return [] # Builtins don't have imports def is_callable(self): """Check if the object has a ``__call__`` method.""" return hasattr(self.obj, '__call__') class CompiledName(FakeName): def __init__(self, obj, name): super(CompiledName, self).__init__(name) self._obj = obj self.name = name self.start_pos = 0, 0 # an illegal start_pos, to make sorting easy. def __repr__(self): try: name = self._obj.name # __name__ is not defined all the time except AttributeError: name = None return '<%s: (%s).%s>' % (type(self).__name__, name, self.name) @property @underscore_memoization def parent(self): module = self._obj.get_parent_until() return _create_from_name(module, self._obj, self.name) @parent.setter def parent(self, value): pass # Just ignore this, FakeName tries to overwrite the parent attribute. def dotted_from_fs_path(fs_path, sys_path=None): """ Changes `/usr/lib/python3.4/email/utils.py` to `email.utils`. I.e. compares the path with sys.path and then returns the dotted_path. If the path is not in the sys.path, just returns None. """ if sys_path is None: sys_path = get_sys_path() # prefer # - UNIX # /path/to/pythonX.Y/lib-dynload # /path/to/pythonX.Y/site-packages # - Windows # C:\path\to\DLLs # C:\path\to\Lib\site-packages # over # - UNIX # /path/to/pythonX.Y # - Windows # C:\path\to\Lib path = '' for s in sys_path: if (fs_path.startswith(s) and len(path) < len(s)): path = s return _path_re.sub('', fs_path[len(path):].lstrip(os.path.sep)).replace(os.path.sep, '.') def load_module(path, name): """ if not name: name = os.path.basename(path) name = name.rpartition('.')[0] # cut file type (normally .so) # sometimes there are endings like `_sqlite3.cpython-32mu` name = re.sub(r'\..*', '', name) dot_path = [] if path: p = path # if path is not in sys.path, we need to make a well defined import # like `from numpy.core import umath.` while p and p not in sys.path: p, sep, mod = p.rpartition(os.path.sep) dot_path.insert(0, mod.partition('.')[0]) if p: name = ".".join(dot_path) path = p else: path = os.path.dirname(path) """ if path is not None: dotted_path = dotted_from_fs_path(path) else: dotted_path = name sys_path = get_sys_path() if dotted_path is None: p, _, dotted_path = path.partition(os.path.sep) sys_path.insert(0, p) temp, sys.path = sys.path, sys_path __import__(dotted_path) # Just access the cache after import, because of #59 as well as the very # complicated import structure of Python. module = sys.modules[dotted_path] sys.path = temp return CompiledObject(module) docstr_defaults = { 'floating point number': 'float', 'character': 'str', 'integer': 'int', 'dictionary': 'dict', 'string': 'str', } def _parse_function_doc(doc): """ Takes a function and returns the params and return value as a tuple. This is nothing more than a docstring parser. TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None TODO docstrings like 'tuple of integers' """ # parse round parentheses: def func(a, (b,c)) try: count = 0 start = doc.index('(') for i, s in enumerate(doc[start:]): if s == '(': count += 1 elif s == ')': count -= 1 if count == 0: end = start + i break param_str = doc[start + 1:end] except (ValueError, UnboundLocalError): # ValueError for doc.index # UnboundLocalError for undefined end in last line debug.dbg('no brackets found - no param') end = 0 param_str = '' else: # remove square brackets, that show an optional param ( = None) def change_options(m): args = m.group(1).split(',') for i, a in enumerate(args): if a and '=' not in a: args[i] += '=None' return ','.join(args) while True: param_str, changes = re.subn(r' ?\[([^\[\]]+)\]', change_options, param_str) if changes == 0: break param_str = param_str.replace('-', '_') # see: isinstance.__doc__ # parse return value r = re.search('-[>-]* ', doc[end:end + 7]) if r is None: ret = '' else: index = end + r.end() # get result type, which can contain newlines pattern = re.compile(r'(,\n|[^\n-])+') ret_str = pattern.match(doc, index).group(0).strip() # New object -> object() ret_str = re.sub(r'[nN]ew (.*)', r'\1()', ret_str) ret = docstr_defaults.get(ret_str, ret_str) return param_str, ret class Builtin(CompiledObject, IsScope): @memoize def get_by_name(self, name): item = [n for n in self.get_defined_names() if n.get_code() == name][0] return item.parent def _a_generator(foo): """Used to have an object to return for generators.""" yield 42 yield foo def _create_from_name(module, parent, name): faked = fake.get_faked(module.obj, parent.obj, name) # only functions are necessary. if faked is not None: faked.parent = parent return faked try: obj = getattr(parent.obj, name) except AttributeError: # happens e.g. in properties of # PyQt4.QtGui.QStyleOptionComboBox.currentText # -> just set it to None obj = None return CompiledObject(obj, parent) builtin = Builtin(_builtins) magic_function_class = CompiledObject(type(load_module), parent=builtin) generator_obj = CompiledObject(_a_generator(1.0)) type_names = [] # Need this, because it's return in get_defined_names. type_names = builtin.get_by_name('type').get_defined_names() def compiled_objects_cache(func): def wrapper(evaluator, obj, parent=builtin, module=None): # Do a very cheap form of caching here. key = id(obj), id(parent), id(module) try: return evaluator.compiled_cache[key][0] except KeyError: result = func(evaluator, obj, parent, module) # Need to cache all of them, otherwise the id could be overwritten. evaluator.compiled_cache[key] = result, obj, parent, module return result return wrapper @compiled_objects_cache def create(evaluator, obj, parent=builtin, module=None): """ A very weird interface class to this module. The more options provided the more acurate loading compiled objects is. """ if not inspect.ismodule(obj): faked = fake.get_faked(module and module.obj, obj) if faked is not None: faked.parent = parent return faked return CompiledObject(obj, parent)
gpl-2.0
firerszd/kbengine
kbe/src/lib/python/Lib/aifc.py
83
31494
"""Stuff to parse AIFF-C and AIFF files. Unless explicitly stated otherwise, the description below is true both for AIFF-C files and AIFF files. An AIFF-C file has the following structure. +-----------------+ | FORM | +-----------------+ | <size> | +----+------------+ | | AIFC | | +------------+ | | <chunks> | | | . | | | . | | | . | +----+------------+ An AIFF file has the string "AIFF" instead of "AIFC". A chunk consists of an identifier (4 bytes) followed by a size (4 bytes, big endian order), followed by the data. The size field does not include the size of the 8 byte header. The following chunk types are recognized. FVER <version number of AIFF-C defining document> (AIFF-C only). MARK <# of markers> (2 bytes) list of markers: <marker ID> (2 bytes, must be > 0) <position> (4 bytes) <marker name> ("pstring") COMM <# of channels> (2 bytes) <# of sound frames> (4 bytes) <size of the samples> (2 bytes) <sampling frequency> (10 bytes, IEEE 80-bit extended floating point) in AIFF-C files only: <compression type> (4 bytes) <human-readable version of compression type> ("pstring") SSND <offset> (4 bytes, not used by this program) <blocksize> (4 bytes, not used by this program) <sound data> A pstring consists of 1 byte length, a string of characters, and 0 or 1 byte pad to make the total length even. Usage. Reading AIFF files: f = aifc.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). In some types of audio files, if the setpos() method is not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for AIFF files) getcompname() -- returns human-readable version of compression type ('not compressed' for AIFF files) getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- get the list of marks in the audio file or None if there are no marks getmark(id) -- get mark with the specified id (raises an error if the mark does not exist) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell(), the position given to setpos() and the position of marks are all compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing AIFF files: f = aifc.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: aiff() -- create an AIFF file (AIFF-C default) aifc() -- create an AIFF-C file setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once setmark(id, pos, name) -- add specified mark to the list of marks tell() -- return current position in output file (useful in combination with setmark()) writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. Marks can be added anytime. If there are any marks, you must call close() after all frames have been written. The close() method is called automatically when the class instance is destroyed. When a file is opened with the extension '.aiff', an AIFF file is written, otherwise an AIFF-C file is written. This default can be changed by calling aiff() or aifc() before the first writeframes or writeframesraw. """ import struct import builtins import warnings __all__ = ["Error", "open", "openfp"] class Error(Exception): pass _AIFC_version = 0xA2805140 # Version 1 of AIFF-C def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: raise EOFError def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: raise EOFError def _read_ushort(file): try: return struct.unpack('>H', file.read(2))[0] except struct.error: raise EOFError def _read_string(file): length = ord(file.read(1)) if length == 0: data = b'' else: data = file.read(length) if length & 1 == 0: dummy = file.read(1) return data _HUGE_VAL = 1.79769313486231e+308 # See <limits.h> def _read_float(f): # 10 bytes expon = _read_short(f) # 2 bytes sign = 1 if expon < 0: sign = -1 expon = expon + 0x8000 himant = _read_ulong(f) # 4 bytes lomant = _read_ulong(f) # 4 bytes if expon == himant == lomant == 0: f = 0.0 elif expon == 0x7FFF: f = _HUGE_VAL else: expon = expon - 16383 f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63) return sign * f def _write_short(f, x): f.write(struct.pack('>h', x)) def _write_ushort(f, x): f.write(struct.pack('>H', x)) def _write_long(f, x): f.write(struct.pack('>l', x)) def _write_ulong(f, x): f.write(struct.pack('>L', x)) def _write_string(f, s): if len(s) > 255: raise ValueError("string exceeds maximum pstring length") f.write(struct.pack('B', len(s))) f.write(s) if len(s) & 1 == 0: f.write(b'\x00') def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = int(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = int(fsmant) _write_ushort(f, expon) _write_ulong(f, himant) _write_ulong(f, lomant) from chunk import Chunk from collections import namedtuple _aifc_params = namedtuple('_aifc_params', 'nchannels sampwidth framerate nframes comptype compname') class Aifc_read: # Variables used in this class: # # These variables are available to the user though appropriate # methods of this class: # _file -- the open file with methods read(), close(), and seek() # set through the __init__() method # _nchannels -- the number of audio channels # available through the getnchannels() method # _nframes -- the number of audio frames # available through the getnframes() method # _sampwidth -- the number of bytes per audio sample # available through the getsampwidth() method # _framerate -- the sampling frequency # available through the getframerate() method # _comptype -- the AIFF-C compression type ('NONE' if AIFF) # available through the getcomptype() method # _compname -- the human-readable AIFF-C compression type # available through the getcomptype() method # _markers -- the marks in the audio file # available through the getmarkers() and getmark() # methods # _soundpos -- the position in the audio stream # available through the tell() method, set through the # setpos() method # # These variables are used internally only: # _version -- the AIFF-C version number # _decomp -- the decompressor from builtin module cl # _comm_chunk_read -- 1 iff the COMM chunk has been read # _aifc -- 1 iff reading an AIFF-C file # _ssnd_seek_needed -- 1 iff positioned correctly in audio # file for readframes() # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk # _framesize -- size of one frame in the file def initfp(self, file): self._version = 0 self._convert = None self._markers = [] self._soundpos = 0 self._file = file chunk = Chunk(file) if chunk.getname() != b'FORM': raise Error('file does not start with FORM id') formdata = chunk.read(4) if formdata == b'AIFF': self._aifc = 0 elif formdata == b'AIFC': self._aifc = 1 else: raise Error('not an AIFF or AIFF-C file') self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == b'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == b'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == b'FVER': self._version = _read_ulong(chunk) elif chunkname == b'MARK': self._readmark(chunk) chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error('COMM chunk and/or SSND chunk missing') def __init__(self, f): if isinstance(f, str): f = builtins.open(f, 'rb') # else, assume it is an open file object already self.initfp(f) def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def getfp(self): return self._file def rewind(self): self._ssnd_seek_needed = 1 self._soundpos = 0 def close(self): self._file.close() def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def getversion(self): ## return self._version def getparams(self): return _aifc_params(self.getnchannels(), self.getsampwidth(), self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname()) def getmarkers(self): if len(self._markers) == 0: return None return self._markers def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id)) def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._ssnd_seek_needed = 1 def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.seek(0) dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._framesize if pos: self._ssnd_chunk.seek(pos + 8) self._ssnd_seek_needed = 0 if nframes == 0: return b'' data = self._ssnd_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data # # Internal methods. # def _alaw2lin(self, data): import audioop return audioop.alaw2lin(data, 2) def _ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2) def _adpcm2lin(self, data): import audioop if not hasattr(self, '_adpcmstate'): # first time self._adpcmstate = None data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate) return data def _read_comm_chunk(self, chunk): self._nchannels = _read_short(chunk) self._nframes = _read_long(chunk) self._sampwidth = (_read_short(chunk) + 7) // 8 self._framerate = int(_read_float(chunk)) self._framesize = self._nchannels * self._sampwidth if self._aifc: #DEBUG: SGI's soundeditor produces a bad size :-( kludge = 0 if chunk.chunksize == 18: kludge = 1 warnings.warn('Warning: bad COMM chunk size') chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) #DEBUG start if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: length = length + 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end self._compname = _read_string(chunk) if self._comptype != b'NONE': if self._comptype == b'G722': self._convert = self._adpcm2lin elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._ulaw2lin elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._alaw2lin else: raise Error('unsupported compression type') self._sampwidth = 2 else: self._comptype = b'NONE' self._compname = b'not compressed' def _readmark(self, chunk): nmarkers = _read_short(chunk) # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: for i in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) if pos or name: # some files appear to have # dummy markers consisting of # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: w = ('Warning: MARK chunk contains only %s marker%s instead of %s' % (len(self._markers), '' if len(self._markers) == 1 else 's', nmarkers)) warnings.warn(w) class Aifc_write: # Variables used in this class: # # These variables are user settable through appropriate methods # of this class: # _file -- the open file with methods write(), close(), tell(), seek() # set through the __init__() method # _comptype -- the AIFF-C compression type ('NONE' in AIFF) # set through the setcomptype() or setparams() method # _compname -- the human-readable AIFF-C compression type # set through the setcomptype() or setparams() method # _nchannels -- the number of audio channels # set through the setnchannels() or setparams() method # _sampwidth -- the number of bytes per audio sample # set through the setsampwidth() or setparams() method # _framerate -- the sampling frequency # set through the setframerate() or setparams() method # _nframes -- the number of audio frames written to the header # set through the setnframes() or setparams() method # _aifc -- whether we're writing an AIFF-C file or an AIFF file # set through the aifc() method, reset through the # aiff() method # # These variables are used internally only: # _version -- the AIFF-C version number # _comp -- the compressor from builtin module cl # _nframeswritten -- the number of audio frames actually written # _datalength -- the size of the audio samples written to the header # _datawritten -- the size of the audio samples actually written def __init__(self, f): if isinstance(f, str): filename = f f = builtins.open(f, 'wb') else: # else, assume it is an open file object already filename = '???' self.initfp(f) if filename[-5:] == '.aiff': self._aifc = 0 else: self._aifc = 1 def initfp(self, file): self._file = file self._version = _AIFC_version self._comptype = b'NONE' self._compname = b'not compressed' self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._markers = [] self._marklength = 0 self._aifc = 1 # AIFF-C is default def __del__(self): self.close() def __enter__(self): return self def __exit__(self, *args): self.close() # # User visible methods. # def aiff(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 0 def aifc(self): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._aifc = 1 def setnchannels(self, nchannels): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if nchannels < 1: raise Error('bad # of channels') self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error('number of channels not set') return self._nchannels def setsampwidth(self, sampwidth): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error('sample width not set') return self._sampwidth def setframerate(self, framerate): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if framerate <= 0: raise Error('bad frame rate') self._framerate = framerate def getframerate(self): if not self._framerate: raise Error('frame rate not set') return self._framerate def setnframes(self, nframes): if self._nframeswritten: raise Error('cannot change parameters after starting to write') self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def setversion(self, version): ## if self._nframeswritten: ## raise Error, 'cannot change parameters after starting to write' ## self._version = version def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._nframeswritten: raise Error('cannot change parameters after starting to write') if comptype not in (b'NONE', b'ulaw', b'ULAW', b'alaw', b'ALAW', b'G722'): raise Error('unsupported compression type') self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error('not all parameters set') return _aifc_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname) def setmark(self, id, pos, name): if id <= 0: raise Error('marker ID must be > 0') if pos < 0: raise Error('marker position must be >= 0') if not isinstance(name, bytes): raise Error('marker name must be bytes') for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name)) def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error('marker {0!r} does not exist'.format(id)) def getmarkers(self): if len(self._markers) == 0: return None return self._markers def tell(self): return self._nframeswritten def writeframesraw(self, data): if not isinstance(data, (bytes, bytearray)): data = memoryview(data).cast('B') self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data) def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() def close(self): if self._file is None: return try: self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size self._file.write(b'\x00') self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten or \ self._marklength: self._patchheader() finally: # Prevent ref cycles self._convert = None f = self._file self._file = None f.close() # # Internal methods. # def _lin2alaw(self, data): import audioop return audioop.lin2alaw(data, 2) def _lin2ulaw(self, data): import audioop return audioop.lin2ulaw(data, 2) def _lin2adpcm(self, data): import audioop if not hasattr(self, '_adpcmstate'): self._adpcmstate = None data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate) return data def _ensure_header_written(self, datasize): if not self._nframeswritten: if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error('sample width must be 2 when compressing ' 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') if not self._nchannels: raise Error('# channels not specified') if not self._sampwidth: raise Error('sample width not specified') if not self._framerate: raise Error('sampling rate not specified') self._write_header(datasize) def _init_compression(self): if self._comptype == b'G722': self._convert = self._lin2adpcm elif self._comptype in (b'ulaw', b'ULAW'): self._convert = self._lin2ulaw elif self._comptype in (b'alaw', b'ALAW'): self._convert = self._lin2alaw def _write_header(self, initlength): if self._aifc and self._comptype != b'NONE': self._init_compression() self._file.write(b'FORM') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth if self._datalength & 1: self._datalength = self._datalength + 1 if self._aifc: if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'): self._datalength = self._datalength // 2 if self._datalength & 1: self._datalength = self._datalength + 1 elif self._comptype == b'G722': self._datalength = (self._datalength + 3) // 4 if self._datalength & 1: self._datalength = self._datalength + 1 try: self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None commlength = self._write_form_length(self._datalength) if self._aifc: self._file.write(b'AIFC') self._file.write(b'FVER') _write_ulong(self._file, 4) _write_ulong(self._file, self._version) else: self._file.write(b'AIFF') self._file.write(b'COMM') _write_ulong(self._file, commlength) _write_short(self._file, self._nchannels) if self._form_length_pos is not None: self._nframes_pos = self._file.tell() _write_ulong(self._file, self._nframes) if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): _write_short(self._file, 8) else: _write_short(self._file, self._sampwidth * 8) _write_float(self._file, self._framerate) if self._aifc: self._file.write(self._comptype) _write_string(self._file, self._compname) self._file.write(b'SSND') if self._form_length_pos is not None: self._ssnd_length_pos = self._file.tell() _write_ulong(self._file, self._datalength + 8) _write_ulong(self._file, 0) _write_ulong(self._file, 0) def _write_form_length(self, datalength): if self._aifc: commlength = 18 + 5 + len(self._compname) if commlength & 1: commlength = commlength + 1 verslength = 12 else: commlength = 18 verslength = 0 _write_ulong(self._file, 4 + verslength + self._marklength + \ 8 + commlength + 16 + datalength) return commlength def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(b'\x00') else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten and \ self._marklength == 0: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_ulong(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_ulong(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength def _writemarkers(self): if len(self._markers) == 0: return self._file.write(b'MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_ulong(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_ulong(self._file, pos) _write_string(self._file, name) def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Aifc_read(f) elif mode in ('w', 'wb'): return Aifc_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'") openfp = open # B/W compatibility if __name__ == '__main__': import sys if not sys.argv[1:]: sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] with open(fn, 'r') as f: print("Reading", fn) print("nchannels =", f.getnchannels()) print("nframes =", f.getnframes()) print("sampwidth =", f.getsampwidth()) print("framerate =", f.getframerate()) print("comptype =", f.getcomptype()) print("compname =", f.getcompname()) if sys.argv[2:]: gn = sys.argv[2] print("Writing", gn) with open(gn, 'w') as g: g.setparams(f.getparams()) while 1: data = f.readframes(1024) if not data: break g.writeframes(data) print("Done.")
lgpl-3.0
matsengrp/bioboxpartis
packages/ighutil/python/vdjalign/_version.py
3
8543
IN_LONG_VERSION_PY = True # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (build by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.8+ (https://github.com/warner/python-versioneer) # these strings will be replaced by git during git-archive git_refnames = "$Format:%d$" git_full = "$Format:%H$" import subprocess import sys def run_command(args, cwd=None, verbose=False, hide_stderr=False): try: # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) except EnvironmentError: e = sys.exc_info()[1] if verbose: print("unable to run %s" % args[0]) print(e) return None stdout = p.communicate()[0].strip() if sys.version >= '3': stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % args[0]) return None return stdout import sys import re import os.path def get_expanded_variables(versionfile_source): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import # _version.py, so we do it with a regexp instead. This function is not # used from _version.py. variables = {} try: f = open(versionfile_source,"r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["full"] = mo.group(1) f.close() except EnvironmentError: pass return variables def versions_from_expanded_variables(variables, tag_prefix, verbose=False): refnames = variables["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("variables are unexpanded, not using") return {} # unexpanded, so not in an unpacked git-archive tarball refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return { "version": r, "full": variables["full"].strip() } # no suitable tags, so we use the full revision id if verbose: print("no suitable tags, using full revision id") return { "version": variables["full"].strip(), "full": variables["full"].strip() } def versions_from_vcs(tag_prefix, versionfile_source, verbose=False): # this runs 'git' from the root of the source tree. That either means # someone ran a setup.py command (and this code is in versioneer.py, so # IN_LONG_VERSION_PY=False, thus the containing directory is the root of # the source tree), or someone ran a project-specific entry point (and # this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the # containing directory is somewhere deeper in the source tree). This only # gets called if the git-archive 'subst' variables were *not* expanded, # and _version.py hasn't already been rewritten with a short version # string, meaning we're inside a checked out source tree. try: here = os.path.abspath(__file__) except NameError: # some py2exe/bbfreeze/non-CPython implementations don't do __file__ return {} # not always correct GIT = "git" if sys.platform == "win32": GIT = "git.cmd" # versionfile_source is the relative path from the top of the source tree # (where the .git directory might live) to this file. Invert this to find # the root from __file__. root = here if IN_LONG_VERSION_PY: for i in range(len(versionfile_source.split("/"))): root = os.path.dirname(root) else: toplevel = run_command([GIT, "rev-parse", "--show-toplevel"], hide_stderr=True) root = (toplevel.strip() if toplevel else os.path.dirname(here)) if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) return {} stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} if not stdout.startswith(tag_prefix): if verbose: print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix)) return {} tag = stdout[len(tag_prefix):] stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() if tag.endswith("-dirty"): full += "-dirty" return {"version": tag, "full": full} def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False): if IN_LONG_VERSION_PY: # We're running from _version.py. If it's from a source tree # (execute-in-place), we can work upwards to find the root of the # tree, and then check the parent directory for a version string. If # it's in an installed application, there's no hope. try: here = os.path.abspath(__file__) except NameError: # py2exe/bbfreeze/non-CPython don't have __file__ return {} # without __file__, we have no hope # versionfile_source is the relative path from the top of the source # tree to _version.py. Invert this to find the root from __file__. root = here for i in range(len(versionfile_source.split("/"))): root = os.path.dirname(root) else: # we're running from versioneer.py, which means we're running from # the setup.py in a source tree. sys.argv[0] is setup.py in the root. here = os.path.abspath(sys.argv[0]) root = os.path.dirname(here) # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" % (root, dirname, parentdir_prefix)) return None return {"version": dirname[len(parentdir_prefix):], "full": ""} tag_prefix = "" parentdir_prefix = "vdjalign-" versionfile_source = "vdjalign/_version.py" def get_versions(default={"version": "unknown", "full": ""}, verbose=False): variables = { "refnames": git_refnames, "full": git_full } ver = versions_from_expanded_variables(variables, tag_prefix, verbose) if not ver: ver = versions_from_vcs(tag_prefix, versionfile_source, verbose) if not ver: ver = versions_from_parentdir(parentdir_prefix, versionfile_source, verbose) if not ver: ver = default return ver
gpl-3.0
grimmjow8/ansible
lib/ansible/utils/module_docs_fragments/validate.py
366
1146
# Copyright (c) 2015 Ansible, Inc # # 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/>. class ModuleDocFragment(object): # Standard documentation fragment DOCUMENTATION = ''' options: validate: required: false description: - The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the example below. The command is passed securely so shell features like expansion and pipes won't work. default: None '''
gpl-3.0
juanalfonsopr/odoo
addons/survey_crm/__openerp__.py
312
1593
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Survey CRM', 'version': '2.0', 'category': 'Marketing', 'complexity': 'easy', 'website': 'https://www.odoo.com/page/survey', 'description': """ Survey - CRM (bridge module) ================================================================================= This module adds a Survey mass mailing button inside the more option of lead/customers views """, 'author': 'OpenERP SA', 'depends': ['crm', 'survey'], 'data': [ 'crm_view.xml', ], 'installable': True, 'auto_install': True } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
bobwalker99/Pydev
plugins/org.python.pydev.jython/Lib/encodings/cp858.py
416
34271
""" Python Character Mapping Codec for CP858, modified from cp850. """ import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp858', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR 0x00a8: 0x00bf, # INVERTED QUESTION MARK 0x00a9: 0x00ae, # REGISTERED SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x00b8: 0x00a9, # COPYRIGHT SIGN 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x00a2, # CENT SIGN 0x00be: 0x00a5, # YEN SIGN 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x00e3, # LATIN SMALL LETTER A WITH TILDE 0x00c7: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x00f0, # LATIN SMALL LETTER ETH 0x00d1: 0x00d0, # LATIN CAPITAL LETTER ETH 0x00d2: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x00d5: 0x20ac, # EURO SIGN 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x00a6, # BROKEN BAR 0x00de: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x00fe, # LATIN SMALL LETTER THORN 0x00e8: 0x00de, # LATIN CAPITAL LETTER THORN 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00eb: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x00af, # MACRON 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2017, # DOUBLE LOW LINE 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00f4: 0x00b6, # PILCROW SIGN 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x00b9, # SUPERSCRIPT ONE 0x00fc: 0x00b3, # SUPERSCRIPT THREE 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( u'\x00' # 0x0000 -> NULL u'\x01' # 0x0001 -> START OF HEADING u'\x02' # 0x0002 -> START OF TEXT u'\x03' # 0x0003 -> END OF TEXT u'\x04' # 0x0004 -> END OF TRANSMISSION u'\x05' # 0x0005 -> ENQUIRY u'\x06' # 0x0006 -> ACKNOWLEDGE u'\x07' # 0x0007 -> BELL u'\x08' # 0x0008 -> BACKSPACE u'\t' # 0x0009 -> HORIZONTAL TABULATION u'\n' # 0x000a -> LINE FEED u'\x0b' # 0x000b -> VERTICAL TABULATION u'\x0c' # 0x000c -> FORM FEED u'\r' # 0x000d -> CARRIAGE RETURN u'\x0e' # 0x000e -> SHIFT OUT u'\x0f' # 0x000f -> SHIFT IN u'\x10' # 0x0010 -> DATA LINK ESCAPE u'\x11' # 0x0011 -> DEVICE CONTROL ONE u'\x12' # 0x0012 -> DEVICE CONTROL TWO u'\x13' # 0x0013 -> DEVICE CONTROL THREE u'\x14' # 0x0014 -> DEVICE CONTROL FOUR u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x0016 -> SYNCHRONOUS IDLE u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK u'\x18' # 0x0018 -> CANCEL u'\x19' # 0x0019 -> END OF MEDIUM u'\x1a' # 0x001a -> SUBSTITUTE u'\x1b' # 0x001b -> ESCAPE u'\x1c' # 0x001c -> FILE SEPARATOR u'\x1d' # 0x001d -> GROUP SEPARATOR u'\x1e' # 0x001e -> RECORD SEPARATOR u'\x1f' # 0x001f -> UNIT SEPARATOR u' ' # 0x0020 -> SPACE u'!' # 0x0021 -> EXCLAMATION MARK u'"' # 0x0022 -> QUOTATION MARK u'#' # 0x0023 -> NUMBER SIGN u'$' # 0x0024 -> DOLLAR SIGN u'%' # 0x0025 -> PERCENT SIGN u'&' # 0x0026 -> AMPERSAND u"'" # 0x0027 -> APOSTROPHE u'(' # 0x0028 -> LEFT PARENTHESIS u')' # 0x0029 -> RIGHT PARENTHESIS u'*' # 0x002a -> ASTERISK u'+' # 0x002b -> PLUS SIGN u',' # 0x002c -> COMMA u'-' # 0x002d -> HYPHEN-MINUS u'.' # 0x002e -> FULL STOP u'/' # 0x002f -> SOLIDUS u'0' # 0x0030 -> DIGIT ZERO u'1' # 0x0031 -> DIGIT ONE u'2' # 0x0032 -> DIGIT TWO u'3' # 0x0033 -> DIGIT THREE u'4' # 0x0034 -> DIGIT FOUR u'5' # 0x0035 -> DIGIT FIVE u'6' # 0x0036 -> DIGIT SIX u'7' # 0x0037 -> DIGIT SEVEN u'8' # 0x0038 -> DIGIT EIGHT u'9' # 0x0039 -> DIGIT NINE u':' # 0x003a -> COLON u';' # 0x003b -> SEMICOLON u'<' # 0x003c -> LESS-THAN SIGN u'=' # 0x003d -> EQUALS SIGN u'>' # 0x003e -> GREATER-THAN SIGN u'?' # 0x003f -> QUESTION MARK u'@' # 0x0040 -> COMMERCIAL AT u'A' # 0x0041 -> LATIN CAPITAL LETTER A u'B' # 0x0042 -> LATIN CAPITAL LETTER B u'C' # 0x0043 -> LATIN CAPITAL LETTER C u'D' # 0x0044 -> LATIN CAPITAL LETTER D u'E' # 0x0045 -> LATIN CAPITAL LETTER E u'F' # 0x0046 -> LATIN CAPITAL LETTER F u'G' # 0x0047 -> LATIN CAPITAL LETTER G u'H' # 0x0048 -> LATIN CAPITAL LETTER H u'I' # 0x0049 -> LATIN CAPITAL LETTER I u'J' # 0x004a -> LATIN CAPITAL LETTER J u'K' # 0x004b -> LATIN CAPITAL LETTER K u'L' # 0x004c -> LATIN CAPITAL LETTER L u'M' # 0x004d -> LATIN CAPITAL LETTER M u'N' # 0x004e -> LATIN CAPITAL LETTER N u'O' # 0x004f -> LATIN CAPITAL LETTER O u'P' # 0x0050 -> LATIN CAPITAL LETTER P u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q u'R' # 0x0052 -> LATIN CAPITAL LETTER R u'S' # 0x0053 -> LATIN CAPITAL LETTER S u'T' # 0x0054 -> LATIN CAPITAL LETTER T u'U' # 0x0055 -> LATIN CAPITAL LETTER U u'V' # 0x0056 -> LATIN CAPITAL LETTER V u'W' # 0x0057 -> LATIN CAPITAL LETTER W u'X' # 0x0058 -> LATIN CAPITAL LETTER X u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y u'Z' # 0x005a -> LATIN CAPITAL LETTER Z u'[' # 0x005b -> LEFT SQUARE BRACKET u'\\' # 0x005c -> REVERSE SOLIDUS u']' # 0x005d -> RIGHT SQUARE BRACKET u'^' # 0x005e -> CIRCUMFLEX ACCENT u'_' # 0x005f -> LOW LINE u'`' # 0x0060 -> GRAVE ACCENT u'a' # 0x0061 -> LATIN SMALL LETTER A u'b' # 0x0062 -> LATIN SMALL LETTER B u'c' # 0x0063 -> LATIN SMALL LETTER C u'd' # 0x0064 -> LATIN SMALL LETTER D u'e' # 0x0065 -> LATIN SMALL LETTER E u'f' # 0x0066 -> LATIN SMALL LETTER F u'g' # 0x0067 -> LATIN SMALL LETTER G u'h' # 0x0068 -> LATIN SMALL LETTER H u'i' # 0x0069 -> LATIN SMALL LETTER I u'j' # 0x006a -> LATIN SMALL LETTER J u'k' # 0x006b -> LATIN SMALL LETTER K u'l' # 0x006c -> LATIN SMALL LETTER L u'm' # 0x006d -> LATIN SMALL LETTER M u'n' # 0x006e -> LATIN SMALL LETTER N u'o' # 0x006f -> LATIN SMALL LETTER O u'p' # 0x0070 -> LATIN SMALL LETTER P u'q' # 0x0071 -> LATIN SMALL LETTER Q u'r' # 0x0072 -> LATIN SMALL LETTER R u's' # 0x0073 -> LATIN SMALL LETTER S u't' # 0x0074 -> LATIN SMALL LETTER T u'u' # 0x0075 -> LATIN SMALL LETTER U u'v' # 0x0076 -> LATIN SMALL LETTER V u'w' # 0x0077 -> LATIN SMALL LETTER W u'x' # 0x0078 -> LATIN SMALL LETTER X u'y' # 0x0079 -> LATIN SMALL LETTER Y u'z' # 0x007a -> LATIN SMALL LETTER Z u'{' # 0x007b -> LEFT CURLY BRACKET u'|' # 0x007c -> VERTICAL LINE u'}' # 0x007d -> RIGHT CURLY BRACKET u'~' # 0x007e -> TILDE u'\x7f' # 0x007f -> DELETE u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE u'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE u'\xff' # 0x0098 -> LATIN SMALL LETTER Y WITH DIAERESIS u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE u'\xa3' # 0x009c -> POUND SIGN u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE u'\xd7' # 0x009e -> MULTIPLICATION SIGN u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE u'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR u'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK u'\xae' # 0x00a9 -> REGISTERED SIGN u'\xac' # 0x00aa -> NOT SIGN u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u2591' # 0x00b0 -> LIGHT SHADE u'\u2592' # 0x00b1 -> MEDIUM SHADE u'\u2593' # 0x00b2 -> DARK SHADE u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT u'\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\xc0' # 0x00b7 -> LATIN CAPITAL LETTER A WITH GRAVE u'\xa9' # 0x00b8 -> COPYRIGHT SIGN u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT u'\xa2' # 0x00bd -> CENT SIGN u'\xa5' # 0x00be -> YEN SIGN u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL u'\xe3' # 0x00c6 -> LATIN SMALL LETTER A WITH TILDE u'\xc3' # 0x00c7 -> LATIN CAPITAL LETTER A WITH TILDE u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL u'\xa4' # 0x00cf -> CURRENCY SIGN u'\xf0' # 0x00d0 -> LATIN SMALL LETTER ETH u'\xd0' # 0x00d1 -> LATIN CAPITAL LETTER ETH u'\xca' # 0x00d2 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX u'\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\xc8' # 0x00d4 -> LATIN CAPITAL LETTER E WITH GRAVE u'\u20ac' # 0x00d5 -> EURO SIGN u'\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\xcf' # 0x00d8 -> LATIN CAPITAL LETTER I WITH DIAERESIS u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT u'\u2588' # 0x00db -> FULL BLOCK u'\u2584' # 0x00dc -> LOWER HALF BLOCK u'\xa6' # 0x00dd -> BROKEN BAR u'\xcc' # 0x00de -> LATIN CAPITAL LETTER I WITH GRAVE u'\u2580' # 0x00df -> UPPER HALF BLOCK u'\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S u'\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\xd2' # 0x00e3 -> LATIN CAPITAL LETTER O WITH GRAVE u'\xf5' # 0x00e4 -> LATIN SMALL LETTER O WITH TILDE u'\xd5' # 0x00e5 -> LATIN CAPITAL LETTER O WITH TILDE u'\xb5' # 0x00e6 -> MICRO SIGN u'\xfe' # 0x00e7 -> LATIN SMALL LETTER THORN u'\xde' # 0x00e8 -> LATIN CAPITAL LETTER THORN u'\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE u'\xdb' # 0x00ea -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX u'\xd9' # 0x00eb -> LATIN CAPITAL LETTER U WITH GRAVE u'\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE u'\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE u'\xaf' # 0x00ee -> MACRON u'\xb4' # 0x00ef -> ACUTE ACCENT u'\xad' # 0x00f0 -> SOFT HYPHEN u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN u'\u2017' # 0x00f2 -> DOUBLE LOW LINE u'\xbe' # 0x00f3 -> VULGAR FRACTION THREE QUARTERS u'\xb6' # 0x00f4 -> PILCROW SIGN u'\xa7' # 0x00f5 -> SECTION SIGN u'\xf7' # 0x00f6 -> DIVISION SIGN u'\xb8' # 0x00f7 -> CEDILLA u'\xb0' # 0x00f8 -> DEGREE SIGN u'\xa8' # 0x00f9 -> DIAERESIS u'\xb7' # 0x00fa -> MIDDLE DOT u'\xb9' # 0x00fb -> SUPERSCRIPT ONE u'\xb3' # 0x00fc -> SUPERSCRIPT THREE u'\xb2' # 0x00fd -> SUPERSCRIPT TWO u'\u25a0' # 0x00fe -> BLACK SQUARE u'\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK 0x00a2: 0x00bd, # CENT SIGN 0x00a3: 0x009c, # POUND SIGN 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a5: 0x00be, # YEN SIGN 0x00a6: 0x00dd, # BROKEN BAR 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00a9: 0x00b8, # COPYRIGHT SIGN 0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00ae: 0x00a9, # REGISTERED SIGN 0x00af: 0x00ee, # MACRON 0x00b0: 0x00f8, # DEGREE SIGN 0x00b1: 0x00f1, # PLUS-MINUS SIGN 0x00b2: 0x00fd, # SUPERSCRIPT TWO 0x00b3: 0x00fc, # SUPERSCRIPT THREE 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b5: 0x00e6, # MICRO SIGN 0x00b6: 0x00f4, # PILCROW SIGN 0x00b7: 0x00fa, # MIDDLE DOT 0x00b8: 0x00f7, # CEDILLA 0x00b9: 0x00fb, # SUPERSCRIPT ONE 0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF 0x00be: 0x00f3, # VULGAR FRACTION THREE QUARTERS 0x00bf: 0x00a8, # INVERTED QUESTION MARK 0x00c0: 0x00b7, # LATIN CAPITAL LETTER A WITH GRAVE 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c3: 0x00c7, # LATIN CAPITAL LETTER A WITH TILDE 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c8: 0x00d4, # LATIN CAPITAL LETTER E WITH GRAVE 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00ca: 0x00d2, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cc: 0x00de, # LATIN CAPITAL LETTER I WITH GRAVE 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00cf: 0x00d8, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d0: 0x00d1, # LATIN CAPITAL LETTER ETH 0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE 0x00d2: 0x00e3, # LATIN CAPITAL LETTER O WITH GRAVE 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d5: 0x00e5, # LATIN CAPITAL LETTER O WITH TILDE 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE 0x00d9: 0x00eb, # LATIN CAPITAL LETTER U WITH GRAVE 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00db: 0x00ea, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00de: 0x00e8, # LATIN CAPITAL LETTER THORN 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e3: 0x00c6, # LATIN SMALL LETTER A WITH TILDE 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE 0x00e6: 0x0091, # LATIN SMALL LIGATURE AE 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS 0x00f0: 0x00d0, # LATIN SMALL LETTER ETH 0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE 0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f5: 0x00e4, # LATIN SMALL LETTER O WITH TILDE 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE 0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE 0x00fe: 0x00e7, # LATIN SMALL LETTER THORN 0x00ff: 0x0098, # LATIN SMALL LETTER Y WITH DIAERESIS 0x20ac: 0x00d5, # EURO SIGN 0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK 0x2017: 0x00f2, # DOUBLE LOW LINE 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
epl-1.0
blueyed/pip
pip/_vendor/requests/packages/chardet/constants.py
3008
1335
######################## 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 ######################### _debug = 0 eDetecting = 0 eFoundIt = 1 eNotMe = 2 eStart = 0 eError = 1 eItsMe = 2 SHORTCUT_THRESHOLD = 0.95
mit
acsone/odoo
addons/account/res_config.py
40
25488
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time import datetime from dateutil.relativedelta import relativedelta import openerp from openerp import SUPERUSER_ID from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DF from openerp.tools.translate import _ from openerp.osv import fields, osv class account_config_settings(osv.osv_memory): _name = 'account.config.settings' _inherit = 'res.config.settings' _columns = { 'company_id': fields.many2one('res.company', 'Company', required=True), 'has_default_company': fields.boolean('Has default company', readonly=True), 'expects_chart_of_accounts': fields.related('company_id', 'expects_chart_of_accounts', type='boolean', string='This company has its own chart of accounts', help="""Check this box if this company is a legal entity."""), 'currency_id': fields.related('company_id', 'currency_id', type='many2one', relation='res.currency', required=True, string='Default company currency', help="Main currency of the company."), 'paypal_account': fields.related('company_id', 'paypal_account', type='char', size=128, string='Paypal account', help="Paypal account (email) for receiving online payments (credit card, etc.) If you set a paypal account, the customer will be able to pay your invoices or quotations with a button \"Pay with Paypal\" in automated emails or through the Odoo portal."), 'company_footer': fields.related('company_id', 'rml_footer', type='text', readonly=True, string='Bank accounts footer preview', help="Bank accounts as printed in the footer of each printed document"), 'has_chart_of_accounts': fields.boolean('Company has a chart of accounts'), 'chart_template_id': fields.many2one('account.chart.template', 'Template', domain="[('visible','=', True)]"), 'code_digits': fields.integer('# of Digits', help="No. of digits to use for account code"), 'tax_calculation_rounding_method': fields.related('company_id', 'tax_calculation_rounding_method', type='selection', selection=[ ('round_per_line', 'Round per line'), ('round_globally', 'Round globally'), ], string='Tax calculation rounding method', help="If you select 'Round per line' : for each tax, the tax amount will first be computed and rounded for each PO/SO/invoice line and then these rounded amounts will be summed, leading to the total amount for that tax. If you select 'Round globally': for each tax, the tax amount will be computed for each PO/SO/invoice line, then these amounts will be summed and eventually this total tax amount will be rounded. If you sell with tax included, you should choose 'Round per line' because you certainly want the sum of your tax-included line subtotals to be equal to the total amount with taxes."), 'sale_tax': fields.many2one("account.tax.template", "Default sale tax"), 'purchase_tax': fields.many2one("account.tax.template", "Default purchase tax"), 'sale_tax_rate': fields.float('Sales tax (%)'), 'purchase_tax_rate': fields.float('Purchase tax (%)'), 'complete_tax_set': fields.boolean('Complete set of taxes', help='This boolean helps you to choose if you want to propose to the user to encode the sales and purchase rates or use the usual m2o fields. This last choice assumes that the set of tax defined for the chosen template is complete'), 'has_fiscal_year': fields.boolean('Company has a fiscal year'), 'date_start': fields.date('Start date', required=True), 'date_stop': fields.date('End date', required=True), 'period': fields.selection([('month', 'Monthly'), ('3months','3 Monthly')], 'Periods', required=True), 'sale_journal_id': fields.many2one('account.journal', 'Sale journal'), 'sale_sequence_prefix': fields.related('sale_journal_id', 'sequence_id', 'prefix', type='char', string='Invoice sequence'), 'sale_sequence_next': fields.related('sale_journal_id', 'sequence_id', 'number_next_actual', type='integer', string='Next invoice number'), 'sale_refund_journal_id': fields.many2one('account.journal', 'Sale refund journal'), 'sale_refund_sequence_prefix': fields.related('sale_refund_journal_id', 'sequence_id', 'prefix', type='char', string='Credit note sequence'), 'sale_refund_sequence_next': fields.related('sale_refund_journal_id', 'sequence_id', 'number_next_actual', type='integer', string='Next credit note number'), 'purchase_journal_id': fields.many2one('account.journal', 'Purchase journal'), 'purchase_sequence_prefix': fields.related('purchase_journal_id', 'sequence_id', 'prefix', type='char', string='Supplier invoice sequence'), 'purchase_sequence_next': fields.related('purchase_journal_id', 'sequence_id', 'number_next_actual', type='integer', string='Next supplier invoice number'), 'purchase_refund_journal_id': fields.many2one('account.journal', 'Purchase refund journal'), 'purchase_refund_sequence_prefix': fields.related('purchase_refund_journal_id', 'sequence_id', 'prefix', type='char', string='Supplier credit note sequence'), 'purchase_refund_sequence_next': fields.related('purchase_refund_journal_id', 'sequence_id', 'number_next_actual', type='integer', string='Next supplier credit note number'), 'module_account_check_writing': fields.boolean('Pay your suppliers by check', help='This allows you to check writing and printing.\n' '-This installs the module account_check_writing.'), 'module_account_accountant': fields.boolean('Full accounting features: journals, legal statements, chart of accounts, etc.', help="""If you do not check this box, you will be able to do invoicing & payments, but not accounting (Journal Items, Chart of Accounts, ...)"""), 'module_account_asset': fields.boolean('Assets management', help='This allows you to manage the assets owned by a company or a person.\n' 'It keeps track of the depreciation occurred on those assets, and creates account move for those depreciation lines.\n' '-This installs the module account_asset. If you do not check this box, you will be able to do invoicing & payments, ' 'but not accounting (Journal Items, Chart of Accounts, ...)'), 'module_account_budget': fields.boolean('Budget management', help='This allows accountants to manage analytic and crossovered budgets. ' 'Once the master budgets and the budgets are defined, ' 'the project managers can set the planned amount on each analytic account.\n' '-This installs the module account_budget.'), 'module_account_payment': fields.boolean('Manage payment orders', help='This allows you to create and manage your payment orders, with purposes to \n' '* serve as base for an easy plug-in of various automated payment mechanisms, and \n' '* provide a more efficient way to manage invoice payments.\n' '-This installs the module account_payment.' ), 'module_account_voucher': fields.boolean('Manage customer payments', help='This includes all the basic requirements of voucher entries for bank, cash, sales, purchase, expense, contra, etc.\n' '-This installs the module account_voucher.'), 'module_account_followup': fields.boolean('Manage customer payment follow-ups', help='This allows to automate letters for unpaid invoices, with multi-level recalls.\n' '-This installs the module account_followup.'), 'module_product_email_template': fields.boolean('Send products tools and information at the invoice confirmation', help='With this module, link your products to a template to send complete information and tools to your customer.\n' 'For instance when invoicing a training, the training agenda and materials will automatically be send to your customers.'), 'group_proforma_invoices': fields.boolean('Allow pro-forma invoices', implied_group='account.group_proforma_invoices', help="Allows you to put invoices in pro-forma state."), 'default_sale_tax': fields.many2one('account.tax', 'Default sale tax', help="This sale tax will be assigned by default on new products."), 'default_purchase_tax': fields.many2one('account.tax', 'Default purchase tax', help="This purchase tax will be assigned by default on new products."), 'decimal_precision': fields.integer('Decimal precision on journal entries', help="""As an example, a decimal precision of 2 will allow journal entries like: 9.99 EUR, whereas a decimal precision of 4 will allow journal entries like: 0.0231 EUR."""), 'group_multi_currency': fields.boolean('Allow multi currencies', implied_group='base.group_multi_currency', help="Allows you multi currency environment"), 'group_analytic_accounting': fields.boolean('Analytic accounting', implied_group='analytic.group_analytic_accounting', help="Allows you to use the analytic accounting."), 'group_check_supplier_invoice_total': fields.boolean('Check the total of supplier invoices', implied_group="account.group_supplier_inv_check_total"), 'income_currency_exchange_account_id': fields.related( 'company_id', 'income_currency_exchange_account_id', type='many2one', relation='account.account', string="Gain Exchange Rate Account", domain="[('type', '=', 'other'), ('company_id', '=', company_id)]]"), 'expense_currency_exchange_account_id': fields.related( 'company_id', 'expense_currency_exchange_account_id', type="many2one", relation='account.account', string="Loss Exchange Rate Account", domain="[('type', '=', 'other'), ('company_id', '=', company_id)]]"), } def _check_account_gain(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): if obj.income_currency_exchange_account_id.company_id and obj.company_id != obj.income_currency_exchange_account_id.company_id: return False return True def _check_account_loss(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): if obj.expense_currency_exchange_account_id.company_id and obj.company_id != obj.expense_currency_exchange_account_id.company_id: return False return True _constraints = [ (_check_account_gain, 'The company of the gain exchange rate account must be the same than the company selected.', ['income_currency_exchange_account_id']), (_check_account_loss, 'The company of the loss exchange rate account must be the same than the company selected.', ['expense_currency_exchange_account_id']), ] def _default_company(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) return user.company_id.id def _default_has_default_company(self, cr, uid, context=None): count = self.pool.get('res.company').search_count(cr, uid, [], context=context) return bool(count == 1) def _get_default_fiscalyear_data(self, cr, uid, company_id, context=None): """Compute default period, starting and ending date for fiscalyear - if in a fiscal year, use its period, starting and ending date - if past fiscal year, use its period, and new dates [ending date of the latest +1 day ; ending date of the latest +1 year] - if no fiscal year, use monthly, 1st jan, 31th dec of this year :return: (date_start, date_stop, period) at format DEFAULT_SERVER_DATETIME_FORMAT """ fiscalyear_ids = self.pool.get('account.fiscalyear').search(cr, uid, [('date_start', '<=', time.strftime(DF)), ('date_stop', '>=', time.strftime(DF)), ('company_id', '=', company_id)]) if fiscalyear_ids: # is in a current fiscal year, use this one fiscalyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_ids[0], context=context) if len(fiscalyear.period_ids) == 5: # 4 periods of 3 months + opening period period = '3months' else: period = 'month' return (fiscalyear.date_start, fiscalyear.date_stop, period) else: past_fiscalyear_ids = self.pool.get('account.fiscalyear').search(cr, uid, [('date_stop', '<=', time.strftime(DF)), ('company_id', '=', company_id)]) if past_fiscalyear_ids: # use the latest fiscal, sorted by (start_date, id) latest_year = self.pool.get('account.fiscalyear').browse(cr, uid, past_fiscalyear_ids[-1], context=context) latest_stop = datetime.datetime.strptime(latest_year.date_stop, DF) if len(latest_year.period_ids) == 5: period = '3months' else: period = 'month' return ((latest_stop+datetime.timedelta(days=1)).strftime(DF), latest_stop.replace(year=latest_stop.year+1).strftime(DF), period) else: return (time.strftime('%Y-01-01'), time.strftime('%Y-12-31'), 'month') _defaults = { 'company_id': _default_company, 'has_default_company': _default_has_default_company, } def create(self, cr, uid, values, context=None): id = super(account_config_settings, self).create(cr, uid, values, context) # Hack: to avoid some nasty bug, related fields are not written upon record creation. # Hence we write on those fields here. vals = {} for fname, field in self._columns.iteritems(): if isinstance(field, fields.related) and fname in values: vals[fname] = values[fname] self.write(cr, uid, [id], vals, context) return id def onchange_company_id(self, cr, uid, ids, company_id, context=None): # update related fields values = {} values['currency_id'] = False if company_id: company = self.pool.get('res.company').browse(cr, uid, company_id, context=context) has_chart_of_accounts = company_id not in self.pool.get('account.installer').get_unconfigured_cmp(cr, uid) fiscalyear_count = self.pool.get('account.fiscalyear').search_count(cr, uid, [('date_start', '<=', time.strftime('%Y-%m-%d')), ('date_stop', '>=', time.strftime('%Y-%m-%d')), ('company_id', '=', company_id)]) date_start, date_stop, period = self._get_default_fiscalyear_data(cr, uid, company_id, context=context) values = { 'expects_chart_of_accounts': company.expects_chart_of_accounts, 'currency_id': company.currency_id.id, 'paypal_account': company.paypal_account, 'company_footer': company.rml_footer, 'has_chart_of_accounts': has_chart_of_accounts, 'has_fiscal_year': bool(fiscalyear_count), 'chart_template_id': False, 'tax_calculation_rounding_method': company.tax_calculation_rounding_method, 'date_start': date_start, 'date_stop': date_stop, 'period': period, } # update journals and sequences for journal_type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'): for suffix in ('_journal_id', '_sequence_prefix', '_sequence_next'): values[journal_type + suffix] = False journal_obj = self.pool.get('account.journal') journal_ids = journal_obj.search(cr, uid, [('company_id', '=', company_id)]) for journal in journal_obj.browse(cr, uid, journal_ids): if journal.type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'): values.update({ journal.type + '_journal_id': journal.id, journal.type + '_sequence_prefix': journal.sequence_id.prefix, journal.type + '_sequence_next': journal.sequence_id.number_next_actual, }) # update taxes ir_values = self.pool.get('ir.values') taxes_id = ir_values.get_default(cr, uid, 'product.template', 'taxes_id', company_id=company_id) supplier_taxes_id = ir_values.get_default(cr, uid, 'product.template', 'supplier_taxes_id', company_id=company_id) values.update({ 'default_sale_tax': isinstance(taxes_id, list) and taxes_id[0] or taxes_id, 'default_purchase_tax': isinstance(supplier_taxes_id, list) and supplier_taxes_id[0] or supplier_taxes_id, }) # update gain/loss exchange rate accounts values.update({ 'income_currency_exchange_account_id': company.income_currency_exchange_account_id and company.income_currency_exchange_account_id.id or False, 'expense_currency_exchange_account_id': company.expense_currency_exchange_account_id and company.expense_currency_exchange_account_id.id or False }) return {'value': values} def onchange_chart_template_id(self, cr, uid, ids, chart_template_id, context=None): tax_templ_obj = self.pool.get('account.tax.template') res = {'value': { 'complete_tax_set': False, 'sale_tax': False, 'purchase_tax': False, 'sale_tax_rate': 15, 'purchase_tax_rate': 15, }} if chart_template_id: # update complete_tax_set, sale_tax and purchase_tax chart_template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context) res['value'].update({'complete_tax_set': chart_template.complete_tax_set}) if chart_template.complete_tax_set: # default tax is given by the lowest sequence. For same sequence we will take the latest created as it will be the case for tax created while isntalling the generic chart of account sale_tax_ids = tax_templ_obj.search(cr, uid, [("chart_template_id", "=", chart_template_id), ('type_tax_use', 'in', ('sale','all'))], order="sequence, id desc") purchase_tax_ids = tax_templ_obj.search(cr, uid, [("chart_template_id", "=", chart_template_id), ('type_tax_use', 'in', ('purchase','all'))], order="sequence, id desc") res['value']['sale_tax'] = sale_tax_ids and sale_tax_ids[0] or False res['value']['purchase_tax'] = purchase_tax_ids and purchase_tax_ids[0] or False if chart_template.code_digits: res['value']['code_digits'] = chart_template.code_digits return res def onchange_tax_rate(self, cr, uid, ids, rate, context=None): return {'value': {'purchase_tax_rate': rate or False}} def onchange_multi_currency(self, cr, uid, ids, group_multi_currency, context=None): res = {} if not group_multi_currency: res['value'] = {'income_currency_exchange_account_id': False, 'expense_currency_exchange_account_id': False} return res def onchange_start_date(self, cr, uid, id, start_date): if start_date: start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d") end_date = (start_date + relativedelta(months=12)) - relativedelta(days=1) return {'value': {'date_stop': end_date.strftime('%Y-%m-%d')}} return {} def open_company_form(self, cr, uid, ids, context=None): config = self.browse(cr, uid, ids[0], context) return { 'type': 'ir.actions.act_window', 'name': 'Configure your Company', 'res_model': 'res.company', 'res_id': config.company_id.id, 'view_mode': 'form', } def set_default_taxes(self, cr, uid, ids, context=None): """ set default sale and purchase taxes for products """ if uid != SUPERUSER_ID and not self.pool['res.users'].has_group(cr, uid, 'base.group_erp_manager'): raise openerp.exceptions.AccessError(_("Only administrators can change the settings")) ir_values = self.pool.get('ir.values') config = self.browse(cr, uid, ids[0], context) ir_values.set_default(cr, SUPERUSER_ID, 'product.template', 'taxes_id', config.default_sale_tax and [config.default_sale_tax.id] or False, company_id=config.company_id.id) ir_values.set_default(cr, SUPERUSER_ID, 'product.template', 'supplier_taxes_id', config.default_purchase_tax and [config.default_purchase_tax.id] or False, company_id=config.company_id.id) def set_chart_of_accounts(self, cr, uid, ids, context=None): """ install a chart of accounts for the given company (if required) """ config = self.browse(cr, uid, ids[0], context) if config.chart_template_id: assert config.expects_chart_of_accounts and not config.has_chart_of_accounts wizard = self.pool.get('wizard.multi.charts.accounts') wizard_id = wizard.create(cr, uid, { 'company_id': config.company_id.id, 'chart_template_id': config.chart_template_id.id, 'code_digits': config.code_digits or 6, 'sale_tax': config.sale_tax.id, 'purchase_tax': config.purchase_tax.id, 'sale_tax_rate': config.sale_tax_rate, 'purchase_tax_rate': config.purchase_tax_rate, 'complete_tax_set': config.complete_tax_set, 'currency_id': config.currency_id.id, }, context) wizard.execute(cr, uid, [wizard_id], context) def set_fiscalyear(self, cr, uid, ids, context=None): """ create a fiscal year for the given company (if necessary) """ config = self.browse(cr, uid, ids[0], context) if config.has_chart_of_accounts or config.chart_template_id: fiscalyear = self.pool.get('account.fiscalyear') fiscalyear_count = fiscalyear.search_count(cr, uid, [('date_start', '<=', config.date_start), ('date_stop', '>=', config.date_stop), ('company_id', '=', config.company_id.id)], context=context) if not fiscalyear_count: name = code = config.date_start[:4] if int(name) != int(config.date_stop[:4]): name = config.date_start[:4] +'-'+ config.date_stop[:4] code = config.date_start[2:4] +'-'+ config.date_stop[2:4] vals = { 'name': name, 'code': code, 'date_start': config.date_start, 'date_stop': config.date_stop, 'company_id': config.company_id.id, } fiscalyear_id = fiscalyear.create(cr, uid, vals, context=context) if config.period == 'month': fiscalyear.create_period(cr, uid, [fiscalyear_id]) elif config.period == '3months': fiscalyear.create_period3(cr, uid, [fiscalyear_id]) def get_default_dp(self, cr, uid, fields, context=None): dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product','decimal_account') return {'decimal_precision': dp.digits} def set_default_dp(self, cr, uid, ids, context=None): config = self.browse(cr, uid, ids[0], context) dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product','decimal_account') dp.write({'digits': config.decimal_precision}) def onchange_analytic_accounting(self, cr, uid, ids, analytic_accounting, context=None): if analytic_accounting: return {'value': { 'module_account_accountant': True, }} return {} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
tjlaboss/openmc
openmc/lib/tally.py
8
13615
from collections.abc import Mapping from ctypes import c_int, c_int32, c_size_t, c_double, c_char_p, c_bool, POINTER from weakref import WeakValueDictionary import numpy as np from numpy.ctypeslib import as_array import scipy.stats from openmc.exceptions import AllocationError, InvalidIDError from openmc.data.reaction import REACTION_NAME from . import _dll, Nuclide from .core import _FortranObjectWithID from .error import _error_handler from .filter import _get_filter __all__ = ['Tally', 'tallies', 'global_tallies', 'num_realizations'] # Tally functions _dll.openmc_extend_tallies.argtypes = [c_int32, POINTER(c_int32), POINTER(c_int32)] _dll.openmc_extend_tallies.restype = c_int _dll.openmc_extend_tallies.errcheck = _error_handler _dll.openmc_get_tally_index.argtypes = [c_int32, POINTER(c_int32)] _dll.openmc_get_tally_index.restype = c_int _dll.openmc_get_tally_index.errcheck = _error_handler _dll.openmc_global_tallies.argtypes = [POINTER(POINTER(c_double))] _dll.openmc_global_tallies.restype = c_int _dll.openmc_global_tallies.errcheck = _error_handler _dll.openmc_tally_get_active.argtypes = [c_int32, POINTER(c_bool)] _dll.openmc_tally_get_active.restype = c_int _dll.openmc_tally_get_active.errcheck = _error_handler _dll.openmc_tally_get_estimator.argtypes = [c_int32, POINTER(c_int)] _dll.openmc_tally_get_estimator.restype = c_int _dll.openmc_tally_get_estimator.errcheck = _error_handler _dll.openmc_tally_get_id.argtypes = [c_int32, POINTER(c_int32)] _dll.openmc_tally_get_id.restype = c_int _dll.openmc_tally_get_id.errcheck = _error_handler _dll.openmc_tally_get_filters.argtypes = [ c_int32, POINTER(POINTER(c_int32)), POINTER(c_size_t)] _dll.openmc_tally_get_filters.restype = c_int _dll.openmc_tally_get_filters.errcheck = _error_handler _dll.openmc_tally_get_n_realizations.argtypes = [c_int32, POINTER(c_int32)] _dll.openmc_tally_get_n_realizations.restype = c_int _dll.openmc_tally_get_n_realizations.errcheck = _error_handler _dll.openmc_tally_get_nuclides.argtypes = [ c_int32, POINTER(POINTER(c_int)), POINTER(c_int)] _dll.openmc_tally_get_nuclides.restype = c_int _dll.openmc_tally_get_nuclides.errcheck = _error_handler _dll.openmc_tally_get_scores.argtypes = [ c_int32, POINTER(POINTER(c_int)), POINTER(c_int)] _dll.openmc_tally_get_scores.restype = c_int _dll.openmc_tally_get_scores.errcheck = _error_handler _dll.openmc_tally_get_type.argtypes = [c_int32, POINTER(c_int32)] _dll.openmc_tally_get_type.restype = c_int _dll.openmc_tally_get_type.errcheck = _error_handler _dll.openmc_tally_get_writable.argtypes = [c_int32, POINTER(c_bool)] _dll.openmc_tally_get_writable.restype = c_int _dll.openmc_tally_get_writable.errcheck = _error_handler _dll.openmc_tally_reset.argtypes = [c_int32] _dll.openmc_tally_reset.restype = c_int _dll.openmc_tally_reset.errcheck = _error_handler _dll.openmc_tally_results.argtypes = [ c_int32, POINTER(POINTER(c_double)), POINTER(c_size_t*3)] _dll.openmc_tally_results.restype = c_int _dll.openmc_tally_results.errcheck = _error_handler _dll.openmc_tally_set_active.argtypes = [c_int32, c_bool] _dll.openmc_tally_set_active.restype = c_int _dll.openmc_tally_set_active.errcheck = _error_handler _dll.openmc_tally_set_filters.argtypes = [c_int32, c_size_t, POINTER(c_int32)] _dll.openmc_tally_set_filters.restype = c_int _dll.openmc_tally_set_filters.errcheck = _error_handler _dll.openmc_tally_set_estimator.argtypes = [c_int32, c_char_p] _dll.openmc_tally_set_estimator.restype = c_int _dll.openmc_tally_set_estimator.errcheck = _error_handler _dll.openmc_tally_set_id.argtypes = [c_int32, c_int32] _dll.openmc_tally_set_id.restype = c_int _dll.openmc_tally_set_id.errcheck = _error_handler _dll.openmc_tally_set_nuclides.argtypes = [c_int32, c_int, POINTER(c_char_p)] _dll.openmc_tally_set_nuclides.restype = c_int _dll.openmc_tally_set_nuclides.errcheck = _error_handler _dll.openmc_tally_set_scores.argtypes = [c_int32, c_int, POINTER(c_char_p)] _dll.openmc_tally_set_scores.restype = c_int _dll.openmc_tally_set_scores.errcheck = _error_handler _dll.openmc_tally_set_type.argtypes = [c_int32, c_char_p] _dll.openmc_tally_set_type.restype = c_int _dll.openmc_tally_set_type.errcheck = _error_handler _dll.openmc_tally_set_writable.argtypes = [c_int32, c_bool] _dll.openmc_tally_set_writable.restype = c_int _dll.openmc_tally_set_writable.errcheck = _error_handler _dll.tallies_size.restype = c_size_t _SCORES = { -1: 'flux', -2: 'total', -3: 'scatter', -4: 'nu-scatter', -5: 'absorption', -6: 'fission', -7: 'nu-fission', -8: 'kappa-fission', -9: 'current', -10: 'events', -11: 'delayed-nu-fission', -12: 'prompt-nu-fission', -13: 'inverse-velocity', -14: 'fission-q-prompt', -15: 'fission-q-recoverable', -16: 'decay-rate' } _ESTIMATORS = { 0: 'analog', 1: 'tracklength', 2: 'collision' } _TALLY_TYPES = { 0: 'volume', 1: 'mesh-surface', 2: 'surface' } def global_tallies(): """Mean and standard deviation of the mean for each global tally. Returns ------- list of tuple For each global tally, a tuple of (mean, standard deviation) """ ptr = POINTER(c_double)() _dll.openmc_global_tallies(ptr) array = as_array(ptr, (4, 3)) # Get sum, sum-of-squares, and number of realizations sum_ = array[:, 1] sum_sq = array[:, 2] n = num_realizations() # Determine mean if n > 0: mean = sum_ / n else: mean = sum_.copy() # Determine standard deviation nonzero = np.abs(mean) > 0 stdev = np.empty_like(mean) stdev.fill(np.inf) if n > 1: stdev[nonzero] = np.sqrt((sum_sq[nonzero]/n - mean[nonzero]**2)/(n - 1)) return list(zip(mean, stdev)) def num_realizations(): """Number of realizations of global tallies.""" return c_int32.in_dll(_dll, 'n_realizations').value class Tally(_FortranObjectWithID): """Tally stored internally. This class exposes a tally that is stored internally in the OpenMC library. To obtain a view of a tally with a given ID, use the :data:`openmc.lib.tallies` mapping. Parameters ---------- uid : int or None Unique ID of the tally new : bool When `index` is None, this argument controls whether a new object is created or a view of an existing object is returned. index : int or None Index in the `tallies` array. Attributes ---------- id : int ID of the tally estimator: str Estimator type of tally (analog, tracklength, collision) filters : list List of tally filters mean : numpy.ndarray An array containing the sample mean for each bin nuclides : list of str List of nuclides to score results for num_realizations : int Number of realizations results : numpy.ndarray Array of tally results std_dev : numpy.ndarray An array containing the sample standard deviation for each bin type : str Type of tally (volume, mesh_surface, surface) """ __instances = WeakValueDictionary() def __new__(cls, uid=None, new=True, index=None): mapping = tallies if index is None: if new: # Determine ID to assign if uid is None: uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A tally with ID={} has already ' 'been allocated.'.format(uid)) index = c_int32() _dll.openmc_extend_tallies(1, index, None) index = index.value else: index = mapping[uid]._index if index not in cls.__instances: instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid cls.__instances[index] = instance return cls.__instances[index] @property def active(self): active = c_bool() _dll.openmc_tally_get_active(self._index, active) return active.value @property def type(self): type = c_int32() _dll.openmc_tally_get_type(self._index, type) return _TALLY_TYPES[type.value] @type.setter def type(self, type): _dll.openmc_tally_set_type(self._index, type.encode()) @property def estimator(self): estimator = c_int() _dll.openmc_tally_get_estimator(self._index, estimator) return _ESTIMATORS[estimator.value] @estimator.setter def estimator(self, estimator): _dll.openmc_tally_set_estimator(self._index, estimator.encode()) @active.setter def active(self, active): _dll.openmc_tally_set_active(self._index, active) @property def id(self): tally_id = c_int32() _dll.openmc_tally_get_id(self._index, tally_id) return tally_id.value @id.setter def id(self, tally_id): _dll.openmc_tally_set_id(self._index, tally_id) @property def filters(self): filt_idx = POINTER(c_int32)() n = c_size_t() _dll.openmc_tally_get_filters(self._index, filt_idx, n) return [_get_filter(filt_idx[i]) for i in range(n.value)] @filters.setter def filters(self, filters): # Get filter indices as int32_t[] n = len(filters) indices = (c_int32*n)(*(f._index for f in filters)) _dll.openmc_tally_set_filters(self._index, n, indices) @property def mean(self): n = self.num_realizations sum_ = self.results[:, :, 1] if n > 0: return sum_ / n else: return sum_.copy() @property def nuclides(self): nucs = POINTER(c_int)() n = c_int() _dll.openmc_tally_get_nuclides(self._index, nucs, n) return [Nuclide(nucs[i]).name if nucs[i] >= 0 else 'total' for i in range(n.value)] @nuclides.setter def nuclides(self, nuclides): nucs = (c_char_p * len(nuclides))() nucs[:] = [x.encode() for x in nuclides] _dll.openmc_tally_set_nuclides(self._index, len(nuclides), nucs) @property def num_realizations(self): n = c_int32() _dll.openmc_tally_get_n_realizations(self._index, n) return n.value @property def results(self): data = POINTER(c_double)() shape = (c_size_t*3)() _dll.openmc_tally_results(self._index, data, shape) return as_array(data, tuple(shape)) @property def scores(self): scores_as_int = POINTER(c_int)() n = c_int() try: _dll.openmc_tally_get_scores(self._index, scores_as_int, n) except AllocationError: return [] else: scores = [] for i in range(n.value): if scores_as_int[i] in _SCORES: scores.append(_SCORES[scores_as_int[i]]) elif scores_as_int[i] in REACTION_NAME: scores.append(REACTION_NAME[scores_as_int[i]]) else: scores.append(str(scores_as_int[i])) return scores @scores.setter def scores(self, scores): scores_ = (c_char_p * len(scores))() scores_[:] = [x.encode() for x in scores] _dll.openmc_tally_set_scores(self._index, len(scores), scores_) @property def std_dev(self): results = self.results std_dev = np.empty(results.shape[:2]) std_dev.fill(np.inf) n = self.num_realizations if n > 1: # Get sum and sum-of-squares from results sum_ = results[:, :, 1] sum_sq = results[:, :, 2] # Determine non-zero entries mean = sum_ / n nonzero = np.abs(mean) > 0 # Calculate sample standard deviation of the mean std_dev[nonzero] = np.sqrt( (sum_sq[nonzero]/n - mean[nonzero]**2)/(n - 1)) return std_dev @property def writable(self): writable = c_bool() _dll.openmc_tally_get_writable(self._index, writable) return writable.value @writable.setter def writable(self, writable): _dll.openmc_tally_set_writable(self._index, writable) def reset(self): """Reset results and num_realizations of tally""" _dll.openmc_tally_reset(self._index) def ci_width(self, alpha=0.05): """Confidence interval half-width based on a Student t distribution Parameters ---------- alpha : float Significance level (one minus the confidence level!) Returns ------- float Half-width of a two-sided (1 - :math:`alpha`) confidence interval """ half_width = self.std_dev.copy() n = self.num_realizations if n > 1: half_width *= scipy.stats.t.ppf(1 - alpha/2, n - 1) return half_width class _TallyMapping(Mapping): def __getitem__(self, key): index = c_int32() try: _dll.openmc_get_tally_index(key, index) except (AllocationError, InvalidIDError) as e: # __contains__ expects a KeyError to work correctly raise KeyError(str(e)) return Tally(index=index.value) def __iter__(self): for i in range(len(self)): yield Tally(index=i).id def __len__(self): return _dll.tallies_size() def __repr__(self): return repr(dict(self)) tallies = _TallyMapping()
mit
boa19861105/Butterfly-S-Sense-4.4.3
scripts/build-all.py
1250
9474
#! /usr/bin/env python # Copyright (c) 2009-2011, Code Aurora Forum. 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 Code Aurora 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Build the kernel for all targets using the Android build environment. # # TODO: Accept arguments to indicate what to build. import glob from optparse import OptionParser import subprocess import os import os.path import shutil import sys version = 'build-all.py, version 0.01' build_dir = '../all-kernels' make_command = ["vmlinux", "modules"] make_env = os.environ make_env.update({ 'ARCH': 'arm', 'CROSS_COMPILE': 'arm-none-linux-gnueabi-', 'KCONFIG_NOTIMESTAMP': 'true' }) all_options = {} def error(msg): sys.stderr.write("error: %s\n" % msg) def fail(msg): """Fail with a user-printed message""" error(msg) sys.exit(1) def check_kernel(): """Ensure that PWD is a kernel directory""" if (not os.path.isfile('MAINTAINERS') or not os.path.isfile('arch/arm/mach-msm/Kconfig')): fail("This doesn't seem to be an MSM kernel dir") def check_build(): """Ensure that the build directory is present.""" if not os.path.isdir(build_dir): try: os.makedirs(build_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise def update_config(file, str): print 'Updating %s with \'%s\'\n' % (file, str) defconfig = open(file, 'a') defconfig.write(str + '\n') defconfig.close() def scan_configs(): """Get the full list of defconfigs appropriate for this tree.""" names = {} for n in glob.glob('arch/arm/configs/[fm]sm[0-9-]*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/qsd*_defconfig'): names[os.path.basename(n)[:-10]] = n for n in glob.glob('arch/arm/configs/apq*_defconfig'): names[os.path.basename(n)[:-10]] = n return names class Builder: def __init__(self, logname): self.logname = logname self.fd = open(logname, 'w') def run(self, args): devnull = open('/dev/null', 'r') proc = subprocess.Popen(args, stdin=devnull, env=make_env, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) count = 0 # for line in proc.stdout: rawfd = proc.stdout.fileno() while True: line = os.read(rawfd, 1024) if not line: break self.fd.write(line) self.fd.flush() if all_options.verbose: sys.stdout.write(line) sys.stdout.flush() else: for i in range(line.count('\n')): count += 1 if count == 64: count = 0 print sys.stdout.write('.') sys.stdout.flush() print result = proc.wait() self.fd.close() return result failed_targets = [] def build(target): dest_dir = os.path.join(build_dir, target) log_name = '%s/log-%s.log' % (build_dir, target) print 'Building %s in %s log %s' % (target, dest_dir, log_name) if not os.path.isdir(dest_dir): os.mkdir(dest_dir) defconfig = 'arch/arm/configs/%s_defconfig' % target dotconfig = '%s/.config' % dest_dir savedefconfig = '%s/defconfig' % dest_dir shutil.copyfile(defconfig, dotconfig) devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, '%s_defconfig' % target], env=make_env, stdin=devnull) devnull.close() if not all_options.updateconfigs: build = Builder(log_name) result = build.run(['make', 'O=%s' % dest_dir] + make_command) if result != 0: if all_options.keep_going: failed_targets.append(target) fail_or_error = error else: fail_or_error = fail fail_or_error("Failed to build %s, see %s" % (target, build.logname)) # Copy the defconfig back. if all_options.configs or all_options.updateconfigs: devnull = open('/dev/null', 'r') subprocess.check_call(['make', 'O=%s' % dest_dir, 'savedefconfig'], env=make_env, stdin=devnull) devnull.close() shutil.copyfile(savedefconfig, defconfig) def build_many(allconf, targets): print "Building %d target(s)" % len(targets) for target in targets: if all_options.updateconfigs: update_config(allconf[target], all_options.updateconfigs) build(target) if failed_targets: fail('\n '.join(["Failed targets:"] + [target for target in failed_targets])) def main(): global make_command check_kernel() check_build() configs = scan_configs() usage = (""" %prog [options] all -- Build all targets %prog [options] target target ... -- List specific targets %prog [options] perf -- Build all perf targets %prog [options] noperf -- Build all non-perf targets""") parser = OptionParser(usage=usage, version=version) parser.add_option('--configs', action='store_true', dest='configs', help="Copy configs back into tree") parser.add_option('--list', action='store_true', dest='list', help='List available targets') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='Output to stdout in addition to log file') parser.add_option('--oldconfig', action='store_true', dest='oldconfig', help='Only process "make oldconfig"') parser.add_option('--updateconfigs', dest='updateconfigs', help="Update defconfigs with provided option setting, " "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'") parser.add_option('-j', '--jobs', type='int', dest="jobs", help="Number of simultaneous jobs") parser.add_option('-l', '--load-average', type='int', dest='load_average', help="Don't start multiple jobs unless load is below LOAD_AVERAGE") parser.add_option('-k', '--keep-going', action='store_true', dest='keep_going', default=False, help="Keep building other targets if a target fails") parser.add_option('-m', '--make-target', action='append', help='Build the indicated make target (default: %s)' % ' '.join(make_command)) (options, args) = parser.parse_args() global all_options all_options = options if options.list: print "Available targets:" for target in configs.keys(): print " %s" % target sys.exit(0) if options.oldconfig: make_command = ["oldconfig"] elif options.make_target: make_command = options.make_target if options.jobs: make_command.append("-j%d" % options.jobs) if options.load_average: make_command.append("-l%d" % options.load_average) if args == ['all']: build_many(configs, configs.keys()) elif args == ['perf']: targets = [] for t in configs.keys(): if "perf" in t: targets.append(t) build_many(configs, targets) elif args == ['noperf']: targets = [] for t in configs.keys(): if "perf" not in t: targets.append(t) build_many(configs, targets) elif len(args) > 0: targets = [] for t in args: if t not in configs.keys(): parser.error("Target '%s' not one of %s" % (t, configs.keys())) targets.append(t) build_many(configs, targets) else: parser.error("Must specify a target to build, or 'all'") if __name__ == "__main__": main()
gpl-2.0
lglenat/whmnet
RaspberryPi/readGateway.py
1
12588
#!/usr/bin/python # -*- coding: utf-8 -*- """ readGateway.py script ===================== This script is used in the whmnet project to receive data from the wireless network gateway and send it to a custom server on the web. This script is run on a Raspberry Pi, connected to the Gateway through the UART serial port on the Pi GPIO header. """ # built-in modules import serial import binascii import struct import datetime import logging import logging.handlers # third-party modules import crcmod import requests # Import configuration variables from config import * # Constants FILE_TYPE_GW_LOG = 0 FILE_TYPE_SENSOR_LOG = 1 FILE_TYPE_LEGACY_DATA = 2 FILE_TYPE_DATA = 3 GW_TYPE_REMOTE_DATA = 0 GW_TYPE_LOCAL_DATA = 1 GW_TYPE_LOG = 2 SENS_TYPE_DATA = 0 SENS_TYPE_LOG = 1 SENS_TYPE_DATA_LEGACY = 2 logger = logging.getLogger() def main(): # Configure logger wfh = logging.handlers.WatchedFileHandler(cfgLoggerFile) # log file formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s') # log header wfh.setFormatter(formatter) logger.addHandler(wfh) logger.setLevel(cfgLogLevel) # set level according to your needs # Configure CRC with polynome, reversing etc. crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0x0, rev=True, xorOut=0xFFFFFFFF) # Open serial port to communicate with gateway try: logger.info('Opening serial port.') port = serial.Serial(cfgSerialName, cfgSerialSpeed, timeout=None) except serial.SerialException: logger.critical('Serial port unavailable') raise else: logger.info('Serial port successfully opened.') # main loop while True: # search for sync byte 0xAA rcv = port.read(1) if rcv == b'\xAA': logger.debug('Sync word received.') # Get timestamp timedata = datetime.datetime.now() # Proceed with message # First byte is length of UART frame # use ord() because data is written in binary format on UART by STM32 (not char) length = ord(port.read(1)) logger.debug('Size of rcvd frame: ' + str(length)) # We can have length = 0 if rx uart buffer is full (in case python script # is started after sensor gateway) if length > 0: # Then read the entire frame msg = port.read(length) logger.debug('Rx frame: ' + binascii.hexlify(msg)) # Unpack the CRC from the 4 last bytes of frame try: rxcrc = struct.unpack('<I', msg[length-4:length])[0] except struct.error: logger.exception('CRC struct error.') else: logger.debug('Rx CRC: ' + str(rxcrc) + ' - ' + hex(rxcrc)) # Compute CRC on frame data (except sync and length bytes) compcrc = crc32_func(msg[0:length-4]) logger.debug('Calculated CRC: ' + str(compcrc) + ' - ' + hex(int(compcrc))) # Compare rcvd CRC and calculated CRC if rxcrc != int(compcrc): # A problem occured during UART transmission logger.info('CRC ERROR.') else: # Get message type from Gateway gwMsgType = ord(msg[0]); # Remote data is data coming from wireless sensors if gwMsgType == GW_TYPE_REMOTE_DATA: # get sensor id and msg type sensMsgType = ord(msg[2]) >> 4 sensorId = ord(msg[2]) & 0xf # get RSSI (can be negative) rssi = ord(msg[length-6]) if rssi > 127: rssi = (256 - rssi) * (-1) # Print sensor ID logger.info('Sensor ID: ' + str(sensorId) + ' - RSSI: ' + str(rssi)) # log/error message from sensor if sensMsgType == SENS_TYPE_LOG: # print and process log message log_msg = binascii.hexlify(msg[3:6]) logger.info('Log message: ' + log_msg) # Write msg to file writeSensorLog(sensorId, timedata, log_msg, rssi) # Post msg on server postMeasFromFile() # measurement message from V1 sensor (not used anymore) elif sensMsgType == SENS_TYPE_DATA_LEGACY: # Extract and print temperature # temperature = computeTemp(msg[3:5]) logger.debug('Temperature: ' + str(temperature)) # Write measurement to file writeLegacyData(sensorId, timedata, temperature, rssi) # Post measurement on server postMeasFromFile() # measurement message from V2 sensor elif sensMsgType == SENS_TYPE_DATA: #Extract data from message data = computeData(msg[3:8]) logger.info('Temp: ' + '{:.2f}'.format(data['temp'])) logger.info('Hum: ' + '{:.2f}'.format(data['hum'])) logger.info('Pres: ' + str(data['pres'])) # Write data to file writeData(sensorId, timedata, data['temp'], data['hum'], data['pres'], rssi) # Post on server postMeasFromFile() else: logger.warning('UNKNOWN SENSOR MSG TYPE.') # log message from gateway itself elif gwMsgType == GW_TYPE_LOG: # Print log message logger.info('Gateway log: ' + str(ord(msg[1]))) # Write msg to file writeGatewayLog(timedata, ord(msg[1])) # Post msg on server postMeasFromFile() else: logger.warning('UNKNOWN GATEWAY MSG TYPE.') else: logger.error('Gateway msg is of length 0.') # The 4 functions below save posts to the CSV buffer file before they are sent to the server def writeLegacyData(id, timedata, temp, rssi): with open(cfgBufferFile, 'a') as f: f.write(str(id) + ',' + str(FILE_TYPE_LEGACY_DATA) + ',' + timedata.strftime("%Y-%m-%d %H:%M:%S") + ',' + str(temp) + ',' + str(rssi)) f.write('\n') def writeData(id, timedata, temp, hum, pres, rssi): with open(cfgBufferFile, 'a') as f: f.write(str(id) + ',' + str(FILE_TYPE_DATA) + ',' + timedata.strftime("%Y-%m-%d %H:%M:%S") + ',' + '{:.2f}'.format(temp) + ',' + '{:.2f}'.format(hum) + ',' + str(pres) + ',' + str(rssi)) f.write('\n') def writeSensorLog(id, timedata, log, rssi): with open(cfgBufferFile, 'a') as f: f.write(str(id) + ',' + str(FILE_TYPE_SENSOR_LOG) + ',' + timedata.strftime("%Y-%m-%d %H:%M:%S") + ',' + str(log) + ',' + str(rssi)) f.write('\n') def writeGatewayLog(timedata, log): with open(cfgBufferFile, 'a') as f: f.write('255' + ',' + str(FILE_TYPE_GW_LOG) + ',' + timedata.strftime("%Y-%m-%d %H:%M:%S") + ',' + str(log)) f.write('\n') # Function to compute temperature from V1 sensor message (not for V2 sensor) def computeTemp(tempString): # unpack data - big endian 16 bit try: temp = struct.unpack('>h', tempString)[0] except struct.error: logger.exception('Temperature struct error.') return -99 else: # Convert code to actual temperature temp = temp * 0.0625 # 1 LSB = 0.0625 °C return temp # Function to extract temperature, RH and pressure data from sensor V2 message # See sensor V2 STM32L0 firmware source to retrieve message structure def computeData(dataStr): # Initialize dictionnary data = {} #fixme: return errors and check for error in calling function # Little endian 24-bit padded to 32 try: sht = struct.unpack('<I', dataStr[0:3] + '\x00') except struct.error: logger.exception('SHT21 data decoding struct error.') return -99 else: data['temp'] = -46.85 + 175.72 * ((sht[0] & 0x7FF) << 5) / pow(2,16) data['hum'] = -6.0 + 125.0 * ((sht[0] >> 11) << 5) / pow(2,16) # Little endian 16-bit try: ms56 = struct.unpack('<H', dataStr[3:5]) except struct.error: logger.exception('MS5637 data decoding struct error.') return -99 else: data['pres'] = ms56[0] + 85000 return data # Function that reads the CSV buffer file line by line and post the data to the # webserver if it is reachable on the internet def postMeasFromFile(): nbLinesPosted = 0 # open backup file in read mode with open(cfgBufferFile, 'r') as f: # Save all measurements in lines variable lines = f.readlines() # Go back to start of file and read it line by line f.seek(0, 0) for line in f: # Remove newline character line = line.rstrip('\n') # Split the line to get the items in a list s = line.split(',', -1) if len(s) != 0: # Try to post measurement on server type = int(s[1]) if type == FILE_TYPE_GW_LOG: status = postOnServer(s[0], s[1], s[2], s[3], '', '', '', '') elif type == FILE_TYPE_SENSOR_LOG: status = postOnServer(s[0], s[1], s[2], s[3], '', '', '', s[4]) elif type == FILE_TYPE_LEGACY_DATA: status = postOnServer(s[0], s[1], s[2], '', s[3], '', '', s[4]) elif type == FILE_TYPE_DATA: status = postOnServer(s[0], s[1], s[2], '', s[3], s[4], s[5], s[6]) else: logger.error('Unknow type in data file.') status = 200 # If posting is successful, increment variable else break if status != 200: break else: nbLinesPosted = nbLinesPosted + 1 else: # simply ignore line logger.error('Invalid line in file. Skipping.') nbLinesPosted = nbLinesPosted + 1 # Open the file not appending write mode with open(cfgBufferFile, 'w') as f: # Write all lines that were not posted on server f.writelines(lines[nbLinesPosted:]) # Function to post data on websever. Uses the requests package. def postOnServer(id_s, dataType_s, datetime_s, log_s, temp_s, hum_s, pres_s, rssi_s): retval = 0; payload = {'id': id_s, 'type': dataType_s, 'time': datetime_s, 'temp': temp_s, 'hum': hum_s, 'pres': pres_s, 'log': log_s, 'rssi': rssi_s, 'chk': cfgPostPwd} logger.debug(payload) try: r = requests.post(cfgPostUrl, data=payload, timeout=5) except requests.exceptions.ConnectionError: logger.exception('Connection error') except requests.exceptions.HTTPError: logger.exception('HTTP invalid response error.') except requests.exceptions.Timeout: logger.exception('Connection timeout error.') except requests.exceptions.TooManyRedirects: logger.exception('Too many redirects.') else: retval = r.status_code logger.debug(r.text) return retval if __name__ == "__main__": main() __author__ = "Lucas Glénat" __copyright__ = "Copyright 2017, whmnet project" __credits__ = ["Lucas Glénat"] __license__ = "GPLv3" __version__ = "1.0.0" __maintainer__ = "Lucas Glénat" __email__ = "lucasglenat@hotmail.com" __status__ = "Production" #### END OF FILE ####
gpl-3.0
marcoantoniooliveira/labweb
oscar/lib/python2.7/site-packages/werkzeug/contrib/cache.py
146
23519
# -*- coding: utf-8 -*- """ werkzeug.contrib.cache ~~~~~~~~~~~~~~~~~~~~~~ The main problem with dynamic Web sites is, well, they're dynamic. Each time a user requests a page, the webserver executes a lot of code, queries the database, renders templates until the visitor gets the page he sees. This is a lot more expensive than just loading a file from the file system and sending it to the visitor. For most Web applications, this overhead isn't a big deal but once it becomes, you will be glad to have a cache system in place. How Caching Works ================= Caching is pretty simple. Basically you have a cache object lurking around somewhere that is connected to a remote cache or the file system or something else. When the request comes in you check if the current page is already in the cache and if so, you're returning it from the cache. Otherwise you generate the page and put it into the cache. (Or a fragment of the page, you don't have to cache the full thing) Here is a simple example of how to cache a sidebar for a template:: def get_sidebar(user): identifier = 'sidebar_for/user%d' % user.id value = cache.get(identifier) if value is not None: return value value = generate_sidebar_for(user=user) cache.set(identifier, value, timeout=60 * 5) return value Creating a Cache Object ======================= To create a cache object you just import the cache system of your choice from the cache module and instantiate it. Then you can start working with that object: >>> from werkzeug.contrib.cache import SimpleCache >>> c = SimpleCache() >>> c.set("foo", "value") >>> c.get("foo") 'value' >>> c.get("missing") is None True Please keep in mind that you have to create the cache and put it somewhere you have access to it (either as a module global you can import or you just put it into your WSGI application). :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import re import tempfile from hashlib import md5 from time import time try: import cPickle as pickle except ImportError: import pickle from werkzeug._compat import iteritems, string_types, text_type, \ integer_types, to_bytes from werkzeug.posixemulation import rename def _items(mappingorseq): """Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v """ if hasattr(mappingorseq, "iteritems"): return mappingorseq.iteritems() elif hasattr(mappingorseq, "items"): return mappingorseq.items() return mappingorseq class BaseCache(object): """Baseclass for the cache systems. All the cache systems implement this API or a superset of it. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`set`. """ def __init__(self, default_timeout=300): self.default_timeout = default_timeout def get(self, key): """Looks up key in the cache and returns the value for it. If the key does not exist `None` is returned instead. :param key: the key to be looked up. """ return None def delete(self, key): """Deletes `key` from the cache. If it does not exist in the cache nothing happens. :param key: the key to delete. """ pass def get_many(self, *keys): """Returns a list of values for the given keys. For each key a item in the list is created. Example:: foo, bar = cache.get_many("foo", "bar") If a key can't be looked up `None` is returned for that key instead. :param keys: The function accepts multiple keys as positional arguments. """ return map(self.get, keys) def get_dict(self, *keys): """Works like :meth:`get_many` but returns a dict:: d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"] :param keys: The function accepts multiple keys as positional arguments. """ return dict(zip(keys, self.get_many(*keys))) def set(self, key, value, timeout=None): """Adds a new key/value to the cache (overwrites value, if key already exists in the cache). :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ pass def add(self, key, value, timeout=None): """Works like :meth:`set` but does not overwrite the values of already existing keys. :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key or the default timeout if not specified. """ pass def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ for key, value in _items(mapping): self.set(key, value, timeout) def delete_many(self, *keys): """Deletes multiple keys at once. :param keys: The function accepts multiple keys as positional arguments. """ for key in keys: self.delete(key) def clear(self): """Clears the cache. Keep in mind that not all caches support completely clearing the cache. """ pass def inc(self, key, delta=1): """Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add. """ self.set(key, (self.get(key) or 0) + delta) def dec(self, key, delta=1): """Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract. """ self.set(key, (self.get(key) or 0) - delta) class NullCache(BaseCache): """A cache that doesn't cache. This can be useful for unit testing. :param default_timeout: a dummy parameter that is ignored but exists for API compatibility with other caches. """ class SimpleCache(BaseCache): """Simple memory cache for single process environments. This class exists mainly for the development server and is not 100% thread safe. It tries to use as many atomic operations as possible and no locks for simplicity but it could happen under heavy load that keys are added multiple times. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. """ def __init__(self, threshold=500, default_timeout=300): BaseCache.__init__(self, default_timeout) self._cache = {} self.clear = self._cache.clear self._threshold = threshold def _prune(self): if len(self._cache) > self._threshold: now = time() for idx, (key, (expires, _)) in enumerate(self._cache.items()): if expires <= now or idx % 3 == 0: self._cache.pop(key, None) def get(self, key): expires, value = self._cache.get(key, (0, None)) if expires > time(): return pickle.loads(value) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout self._prune() self._cache[key] = (time() + timeout, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if len(self._cache) > self._threshold: self._prune() item = (time() + timeout, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) self._cache.setdefault(key, item) def delete(self, key): self._cache.pop(key, None) _test_memcached_key = re.compile(br'[^\x00-\x21\xff]{1,250}$').match class MemcachedCache(BaseCache): """A cache that uses memcached as backend. The first argument can either be an object that resembles the API of a :class:`memcache.Client` or a tuple/list of server addresses. In the event that a tuple/list is passed, Werkzeug tries to import the best available memcache library. Implementation notes: This cache backend works around some limitations in memcached to simplify the interface. For example unicode keys are encoded to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return the keys in the same format as passed. Furthermore all get methods silently ignore key errors to not cause problems when untrusted user data is passed to the get methods which is often the case in web applications. :param servers: a list or tuple of server addresses or alternatively a :class:`memcache.Client` or a compatible client. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param key_prefix: a prefix that is added before all keys. This makes it possible to use the same memcached server for different applications. Keep in mind that :meth:`~BaseCache.clear` will also clear keys with a different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if servers is None or isinstance(servers, (list, tuple)): if servers is None: servers = ['127.0.0.1:11211'] self._client = self.import_preferred_memcache_lib(servers) if self._client is None: raise RuntimeError('no memcache module found') else: # NOTE: servers is actually an already initialized memcache # client. self._client = servers self.key_prefix = to_bytes(key_prefix) def get(self, key): if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key # memcached doesn't support keys longer than that. Because often # checks for so long keys can occour because it's tested from user # submitted data etc we fail silently for getting. if _test_memcached_key(key): return self._client.get(key) def get_dict(self, *keys): key_mapping = {} have_encoded_keys = False for key in keys: if isinstance(key, unicode): encoded_key = key.encode('utf-8') have_encoded_keys = True else: encoded_key = key if self.key_prefix: encoded_key = self.key_prefix + encoded_key if _test_memcached_key(key): key_mapping[encoded_key] = key d = rv = self._client.get_multi(key_mapping.keys()) if have_encoded_keys or self.key_prefix: rv = {} for key, value in iteritems(d): rv[key_mapping[key]] = value if len(rv) < len(keys): for key in keys: if key not in rv: rv[key] = None return rv def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.add(key, value, timeout) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.set(key, value, timeout) def get_many(self, *keys): d = self.get_dict(*keys) return [d[key] for key in keys] def set_many(self, mapping, timeout=None): if timeout is None: timeout = self.default_timeout new_mapping = {} for key, value in _items(mapping): if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key new_mapping[key] = value self._client.set_multi(new_mapping, timeout) def delete(self, key): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key if _test_memcached_key(key): self._client.delete(key) def delete_many(self, *keys): new_keys = [] for key in keys: if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key if _test_memcached_key(key): new_keys.append(key) self._client.delete_multi(new_keys) def clear(self): self._client.flush_all() def inc(self, key, delta=1): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.incr(key, delta) def dec(self, key, delta=1): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.decr(key, delta) def import_preferred_memcache_lib(self, servers): """Returns an initialized memcache client. Used by the constructor.""" try: import pylibmc except ImportError: pass else: return pylibmc.Client(servers) try: from google.appengine.api import memcache except ImportError: pass else: return memcache.Client() try: import memcache except ImportError: pass else: return memcache.Client(servers) # backwards compatibility GAEMemcachedCache = MemcachedCache class RedisCache(BaseCache): """Uses the Redis key-value store as a cache backend. The first argument can be either a string denoting address of the Redis server or an object resembling an instance of a redis.Redis class. Note: Python Redis API already takes care of encoding unicode strings on the fly. .. versionadded:: 0.7 .. versionadded:: 0.8 `key_prefix` was added. .. versionchanged:: 0.8 This cache backend now properly serializes objects. .. versionchanged:: 0.8.3 This cache backend now supports password authentication. :param host: address of the Redis server or an object which API is compatible with the official Python Redis client (redis-py). :param port: port number on which Redis server listens for connections. :param password: password authentication for the Redis server. :param db: db (zero-based numeric index) on Redis Server to connect. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param key_prefix: A prefix that should be added to all keys. """ def __init__(self, host='localhost', port=6379, password=None, db=0, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if isinstance(host, string_types): try: import redis except ImportError: raise RuntimeError('no redis module found') self._client = redis.Redis(host=host, port=port, password=password, db=db) else: self._client = host self.key_prefix = key_prefix or '' def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t in integer_types: return str(value).encode('ascii') return b'!' + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be callde with None. """ if value is None: return None if value.startswith(b'!'): return pickle.loads(value[1:]) try: return int(value) except ValueError: # before 0.8 we did not have serialization. Still support that. return value def get(self, key): return self.load_object(self._client.get(self.key_prefix + key)) def get_many(self, *keys): if self.key_prefix: keys = [self.key_prefix + key for key in keys] return [self.load_object(x) for x in self._client.mget(keys)] def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout dump = self.dump_object(value) self._client.setex(self.key_prefix + key, dump, timeout) def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout dump = self.dump_object(value) added = self._client.setnx(self.key_prefix + key, dump) if added: self._client.expire(self.key_prefix + key, timeout) def set_many(self, mapping, timeout=None): if timeout is None: timeout = self.default_timeout pipe = self._client.pipeline() for key, value in _items(mapping): dump = self.dump_object(value) pipe.setex(self.key_prefix + key, dump, timeout) pipe.execute() def delete(self, key): self._client.delete(self.key_prefix + key) def delete_many(self, *keys): if not keys: return if self.key_prefix: keys = [self.key_prefix + key for key in keys] self._client.delete(*keys) def clear(self): if self.key_prefix: keys = self._client.keys(self.key_prefix + '*') if keys: self._client.delete(*keys) else: self._client.flushdb() def inc(self, key, delta=1): return self._client.incr(self.key_prefix + key, delta) def dec(self, key, delta=1): return self._client.decr(self.key_prefix + key, delta) class FileSystemCache(BaseCache): """A cache that stores the items on the file system. This cache depends on being the only user of the `cache_dir`. Make absolutely sure that nobody but this cache stores files there or otherwise the cache will randomly delete files therein. :param cache_dir: the directory where cache files are stored. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param mode: the file mode wanted for the cache files, default 0600 """ #: used for temporary files by the FileSystemCache _fs_transaction_suffix = '.__wz_cache' def __init__(self, cache_dir, threshold=500, default_timeout=300, mode=0o600): BaseCache.__init__(self, default_timeout) self._path = cache_dir self._threshold = threshold self._mode = mode if not os.path.exists(self._path): os.makedirs(self._path) def _list_dir(self): """return a list of (fully qualified) cache filenames """ return [os.path.join(self._path, fn) for fn in os.listdir(self._path) if not fn.endswith(self._fs_transaction_suffix)] def _prune(self): entries = self._list_dir() if len(entries) > self._threshold: now = time() for idx, fname in enumerate(entries): remove = False f = None try: try: f = open(fname, 'rb') expires = pickle.load(f) remove = expires <= now or idx % 3 == 0 finally: if f is not None: f.close() except Exception: pass if remove: try: os.remove(fname) except (IOError, OSError): pass def clear(self): for fname in self._list_dir(): try: os.remove(fname) except (IOError, OSError): pass def _get_filename(self, key): if isinstance(key, text_type): key = key.encode('utf-8') #XXX unicode review hash = md5(key).hexdigest() return os.path.join(self._path, hash) def get(self, key): filename = self._get_filename(key) try: f = open(filename, 'rb') try: if pickle.load(f) >= time(): return pickle.load(f) finally: f.close() os.remove(filename) except Exception: return None def add(self, key, value, timeout=None): filename = self._get_filename(key) if not os.path.exists(filename): self.set(key, value, timeout) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout filename = self._get_filename(key) self._prune() try: fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix, dir=self._path) f = os.fdopen(fd, 'wb') try: pickle.dump(int(time() + timeout), f, 1) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) finally: f.close() rename(tmp, filename) os.chmod(filename, self._mode) except (IOError, OSError): pass def delete(self, key): try: os.remove(self._get_filename(key)) except (IOError, OSError): pass
bsd-3-clause
umairghani/py-jrpc
build/lib/jrpc/jrpcClient/SimpleTCPClient.py
2
2711
import json import urllib2 import urlparse import SimpleTCPClientException from Method import _Method __author__ = 'umairghani' class SimpleTCPClient(object): """ Client class for a logical connection to the TCP Server """ def __init__(self, host, port=80, ssl=False): """ Constructor :param host: :param port: """ self.url = "%s://%s:%d" % ('https' if ssl else 'http', host, port) self.methods = self._listMethods() def _uri(self, request): """ opens the URL :param request: :return: response """ try: _output = urllib2.urlopen(request) return _output.read() except urllib2.HTTPError, e: raise SimpleTCPClientException.HTTPError(e) except urllib2.URLError, e: raise SimpleTCPClientException.URLError(e) def _get(self, url): """ HTTP GET private class :return: response """ _request = urllib2.Request(url) return self._uri(_request) def get(self, url): """ HTTP GET Public function :param url: :return: response """ _url = urlparse.urljoin(self.url, url) return self._get(_url) def post(self, data): """ HTTP POST :param data: :return: response """ _data = json.dumps(data) _request = urllib2.Request(self.url) _request.add_header("Content-type", "application/json") _request.add_data(_data) return self._uri(_request) def geturl(self): """ :return: the base url """ return self.url def _listMethods(self): """ List all the methods on the server :return: List of methods """ #_functions = {} _url = urlparse.urljoin(self.url, "list_methods") _response = self._get(_url) return json.loads(_response)["list_methods"] #for _method in _methods: # _functions[_method] = _method #return _functions def _request(self, method, data): """ Call a method on the remote server :param method: :param data: :return: response """ __params = {method: data} __response = self.post(__params) return __response def __getattr__(self, item): """ Magic method dispatcher :param item: :return: response """ return _Method(self._request, item) def __dir__(self): _methods = ["post", "get", "geturl"] _methods.extend(self.methods) return _methods
mit
eepalms/gem5-newcache
src/arch/x86/isa/insts/x87/control/clear_exceptions.py
91
2159
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 the copyright holders 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. # # Authors: Gabe Black microcode = ''' # FCLEX # FNCLEX '''
bsd-3-clause
ISRyuu/ISNNTF
test.py
1
3957
import numpy as np def iou(box_1, box_2): box_1_ulx = box_1[0] - box_1[2] * 0.5 box_1_uly = box_1[1] - box_1[3] * 0.5 box_1_lrx = box_1[0] + box_1[2] * 0.5 box_1_lry = box_1[1] + box_1[3] * 0.5 box_2_ulx = box_2[0] - box_2[2] * 0.5 box_2_uly = box_2[1] - box_2[3] * 0.5 box_2_lrx = box_2[0] + box_2[2] * 0.5 box_2_lry = box_2[1] + box_2[3] * 0.5 overlap_ulx = max(box_1_ulx, box_2_ulx) overlap_uly = max(box_1_uly, box_2_uly) overlap_lrx = min(box_1_lrx, box_2_lrx) overlap_lry = min(box_1_lry, box_2_lry) overlap = max(0, (overlap_lrx - overlap_ulx)) * max(0, (overlap_lry - overlap_uly)) union = max(1e-10, (box_1[2] * box_1[3] + box_2[2] * box_2[3] - overlap)) return min(max(0, overlap / union), 1) def non_max_suppression(output, cell_size, class_num, boxes_per_cell, threshold=0.1, iou_threshold=0.5): '''output [cell_size, cell_size, boxes_per_cell, values]''' offset_y = np.reshape( np.asarray([np.arange(cell_size)]*cell_size*boxes_per_cell).T, (cell_size, cell_size, boxes_per_cell)) offset_x = np.transpose(offset_y, [1, 0, 2]) output = np.asarray(output) classes = np.reshape(output[..., :class_num], [cell_size, cell_size, class_num]) confidences = np.reshape(output[..., class_num:class_num+boxes_per_cell], [cell_size, cell_size, boxes_per_cell]) boxes = np.reshape(output[..., class_num+boxes_per_cell:], [cell_size, cell_size, boxes_per_cell, -1]) boxes[..., 0] = (boxes[..., 0] + offset_x) / cell_size boxes[..., 1] = (boxes[..., 1] + offset_y) / cell_size boxes[..., 2:] = np.square(boxes[..., 2:]) class_confidences = [] for i in range(boxes_per_cell): class_confidences += [np.expand_dims(confidences[..., i], axis=-1) * classes] class_confidences = np.stack(class_confidences, axis=-2) class_filter = class_confidences >= threshold class_filtered_indices = np.nonzero(class_filter) boxes_filtered = boxes[class_filtered_indices[0:3]] class_filtered = np.argmax(class_confidences, axis=-1)[class_filtered_indices[0:3]] probabilites_filtered = class_confidences[class_filter] sorted_probs_indices = np.flip(np.argsort(probabilites_filtered), axis=0) probabilites_filtered = probabilites_filtered[sorted_probs_indices] boxes_filtered = boxes_filtered[sorted_probs_indices] class_filtered = class_filtered[sorted_probs_indices] for i in range(len(sorted_probs_indices)): if probabilites_filtered[i] == 0: continue for j in range(i+1, len(sorted_probs_indices)): if iou(boxes_filtered[i], boxes_filtered[j]) >= iou_threshold: probabilites_filtered[j] = 0 result_indices = probabilites_filtered > 0 confidence_result = probabilites_filtered[result_indices] classes_result = class_filtered[result_indices] boxes_result = boxes_filtered[result_indices] return np.concatenate([np.expand_dims(confidence_result, axis=-1), np.expand_dims(classes_result, axis=-1), boxes_result], axis=-1) if __name__ == '__main__': test_data = np.reshape(np.load("/Users/Kevin/Desktop/out.npy")[2], [7, 7, 30]) print(non_max_suppression(test_data, 7, 20, 2)) # confidences = np.random.randn(3,3,2) # classes = np.random.randn(3,3,20) # boxes_per_cell = 2 # probs = np.zeros([3,3,2,20]) # for i in range(boxes_per_cell): # for j in range(20): # probs[:, :, i, j] = np.multiply( # classes[:, :, j], confidences[:, :, i]) # probabilites = [] # for i in range(boxes_per_cell): # probabilites += [np.expand_dims(confidences[..., i], axis=-1) * classes] # print(probs == np.stack(probabilites, axis=-2))
bsd-3-clause
canaryhealth/nlu_trainer
nlu_trainer/util.py
1
1186
# -*- coding: utf-8 -*- import re def phrase_index(sentence, phrase): ''' Returns the start and end index of phrase (first instance) if it exists in sentence. ex: >>> phrase_index('the quick brown fox jumps over the lazy dog', 'brown fox jumps') (10, 24) ''' phrase = str(phrase) # in case phrase is a number m = re.match(r'(.*?)\b'+re.escape(phrase)+r'\b', sentence) if m: # group 0 and 1 returns the match with and without the phrase respectively l = len(m.group(1)) return (l, l+len(phrase)-1) return None def phrase_pos(sentence, phrase): ''' Returns the start and end position of phrase (first instance) if it exists in sentence. ex: >>> phrase_index('the quick brown fox jumps over the lazy dog', 'brown fox jumps') (2, 5) ''' phrase = str(phrase) # in case phrase is a number s_tok = sentence.split() p_tok = phrase.split() p_len = len(p_tok) # get all indices where s_tok[i] matches p_tok[0] indices = [ i for i, x in enumerate(s_tok) if x == p_tok[0] ] for i in indices: if s_tok[i : i+p_len] == p_tok: return i, i+p_len return None
mit
mttr/django
tests/test_client_regress/urls.py
352
2521
from django.conf.urls import include, url from django.views.generic import RedirectView from . import views urlpatterns = [ url(r'', include('test_client.urls')), url(r'^no_template_view/$', views.no_template_view), url(r'^staff_only/$', views.staff_only_view), url(r'^get_view/$', views.get_view), url(r'^request_data/$', views.request_data), url(r'^request_data_extended/$', views.request_data, {'template': 'extended.html', 'data': 'bacon'}), url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'), url(r'^nested_view/$', views.nested_view, name='nested_view'), url(r'^login_protected_redirect_view/$', views.login_protected_redirect_view), url(r'^redirects/$', RedirectView.as_view(url='/redirects/further/')), url(r'^redirects/further/$', RedirectView.as_view(url='/redirects/further/more/')), url(r'^redirects/further/more/$', RedirectView.as_view(url='/no_template_view/')), url(r'^redirect_to_non_existent_view/$', RedirectView.as_view(url='/non_existent_view/')), url(r'^redirect_to_non_existent_view2/$', RedirectView.as_view(url='/redirect_to_non_existent_view/')), url(r'^redirect_to_self/$', RedirectView.as_view(url='/redirect_to_self/')), url(r'^redirect_to_self_with_changing_query_view/$', views.redirect_to_self_with_changing_query_view), url(r'^circular_redirect_1/$', RedirectView.as_view(url='/circular_redirect_2/')), url(r'^circular_redirect_2/$', RedirectView.as_view(url='/circular_redirect_3/')), url(r'^circular_redirect_3/$', RedirectView.as_view(url='/circular_redirect_1/')), url(r'^redirect_other_host/$', RedirectView.as_view(url='https://otherserver:8443/no_template_view/')), url(r'^set_session/$', views.set_session_view), url(r'^check_session/$', views.check_session_view), url(r'^request_methods/$', views.request_methods_view), url(r'^check_unicode/$', views.return_unicode), url(r'^check_binary/$', views.return_undecodable_binary), url(r'^json_response/$', views.return_json_response), url(r'^parse_unicode_json/$', views.return_json_file), url(r'^check_headers/$', views.check_headers), url(r'^check_headers_redirect/$', RedirectView.as_view(url='/check_headers/')), url(r'^body/$', views.body), url(r'^read_all/$', views.read_all), url(r'^read_buffer/$', views.read_buffer), url(r'^request_context_view/$', views.request_context_view), url(r'^render_template_multiple_times/$', views.render_template_multiple_times), ]
bsd-3-clause
delta2323/chainer
tests/chainer_tests/testing_tests/test_parameterized.py
8
1837
import unittest from chainer import testing @testing.parameterize( {'actual': {'a': [1, 2], 'b': [3, 4, 5]}, 'expect': [{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]}, {'actual': {'a': [1, 2]}, 'expect': [{'a': 1}, {'a': 2}]}, {'actual': {'a': [1, 2], 'b': []}, 'expect': []}, {'actual': {'a': []}, 'expect': []}, {'actual': {}, 'expect': [{}]}) class ProductTest(unittest.TestCase): def test_product(self): self.assertListEqual(testing.product(self.actual), self.expect) @testing.parameterize( {'actual': [[{'a': 1, 'b': 3}, {'a': 2, 'b': 4}], [{'c': 5}, {'c': 6}]], 'expect': [{'a': 1, 'b': 3, 'c': 5}, {'a': 1, 'b': 3, 'c': 6}, {'a': 2, 'b': 4, 'c': 5}, {'a': 2, 'b': 4, 'c': 6}]}, {'actual': [[{'a': 1}, {'a': 2}], [{'b': 3}, {'b': 4}, {'b': 5}]], 'expect': [{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]}, {'actual': [[{'a': 1}, {'a': 2}]], 'expect': [{'a': 1}, {'a': 2}]}, {'actual': [[{'a': 1}, {'a': 2}], []], 'expect': []}, {'actual': [[]], 'expect': []}, {'actual': [], 'expect': [{}]}) class ProductDictTest(unittest.TestCase): def test_product_dict(self): self.assertListEqual(testing.product_dict(*self.actual), self.expect) def f(x): return x class C(object): def __call__(self, x): return x def method(self, x): return x @testing.parameterize( {'callable': f}, {'callable': lambda x: x}, {'callable': C()}, {'callable': C().method} ) class TestParameterize(unittest.TestCase): def test_callable(self): y = self.callable(1) self.assertEqual(y, 1) testing.run_module(__name__, __file__)
mit
bensternthal/bedrock
bedrock/security/tests/test_views.py
16
7643
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.test import RequestFactory from mock import patch, Mock from nose.tools import eq_, ok_ from product_details import product_details from product_details.version_compare import Version from bedrock.mozorg.tests import TestCase from bedrock.security.management.commands.update_security_advisories import add_or_update_advisory from bedrock.security.models import Product from bedrock.security.views import (ProductView, ProductVersionView, latest_queryset, product_is_obsolete) @patch.object(product_details, 'firefox_versions', {'LATEST_FIREFOX_VERSION': '33.0', 'FIREFOX_ESR': '31.2.0'}) @patch.object(product_details, 'thunderbird_versions', {'LATEST_THUNDERBIRD_VERSION': '31.2.0'}) def test_product_is_obsolete(): ok_(product_is_obsolete('firefox', '3.6')) ok_(product_is_obsolete('firefox', '32')) ok_(product_is_obsolete('firefox-esr', '17.0')) ok_(product_is_obsolete('thunderbird', '30')) ok_(product_is_obsolete('seamonkey', '2.0')) ok_(product_is_obsolete('seamonkey', '2.19')) ok_(product_is_obsolete('other-things', '3000')) ok_(not product_is_obsolete('firefox', '33.0.2')) ok_(not product_is_obsolete('firefox', '34.0')) ok_(not product_is_obsolete('firefox-esr', '31.0')) ok_(not product_is_obsolete('thunderbird', '31')) ok_(not product_is_obsolete('seamonkey', '2.30')) class TestViews(TestCase): def setUp(self): pvnames = [ 'Firefox 3.6', 'Firefox 4.0', 'Firefox 4.0.1', 'Firefox 4.2', 'Firefox 4.2.3', 'Firefox 24.0', ] self.pvs = [Product.objects.create(name=pv) for pv in pvnames] def test_product_view_min_version(self): """Should not include versions below minimum.""" pview = ProductView() pview.kwargs = {'slug': 'firefox'} with patch.dict(pview.minimum_versions, {'firefox': Version('4.2')}): self.assertListEqual(pview.get_queryset(), [self.pvs[5], self.pvs[4], self.pvs[3]]) with patch.dict(pview.minimum_versions, {'firefox': Version('22.0')}): self.assertListEqual(pview.get_queryset(), [self.pvs[5]]) def test_product_version_view_filter_major(self): """Given a major version should return all minor versions.""" pview = ProductVersionView() pview.kwargs = {'product': 'firefox', 'version': '4'} self.assertListEqual(pview.get_queryset(), [self.pvs[4], self.pvs[3], self.pvs[2], self.pvs[1]]) def test_product_version_view_filter_minor(self): """Given a minor version should return all point versions.""" pview = ProductVersionView() pview.kwargs = {'product': 'firefox', 'version': '4.2'} self.assertListEqual(pview.get_queryset(), [self.pvs[4], self.pvs[3]]) class TestLastModified(TestCase): def setUp(self): self.next_id = 1 self.rf = RequestFactory() def new_advisory(self, mfsa_id=None, title='WILMAAAA!', impact='Critical', announced='August 18, 2014', fixed_in=None, html='Wilma finally leaves Fred for a brontosaurus.'): if mfsa_id is None: mfsa_id = '2014-{0:0>2}'.format(self.next_id) self.next_id += 1 if fixed_in is None: fixed_in = ['Firefox 29', 'Thunderbird 29'] return add_or_update_advisory({ 'mfsa_id': mfsa_id, 'title': title, 'impact': impact, 'announced': announced, 'fixed_in': fixed_in, }, html) def test_latest_queryset_all(self): """Should return all advisories for the all page.""" advisories = [self.new_advisory() for i in range(10)] req = self.rf.get('/') req.resolver_match = Mock() req.resolver_match.url_name = 'security.advisories' qs = latest_queryset(req, {}) self.assertListEqual(advisories, list(qs.order_by('year', 'order'))) def test_latest_queryset_single(self): """Should return a single advisory based on PK.""" advisories = [self.new_advisory() for i in range(10)] req = self.rf.get('/') req.resolver_match = Mock() req.resolver_match.url_name = 'security.advisory' qs = latest_queryset(req, {'pk': '2014-05'}) self.assertEqual(advisories[4], qs.get()) def test_latest_queryset_product(self): """Should advisories for a single product.""" advisories_fx = [self.new_advisory(fixed_in=['Firefox 30.0']) for i in range(5)] for i in range(5): self.new_advisory(fixed_in=['Thunderbird 30.0']) req = self.rf.get('/') req.resolver_match = Mock() req.resolver_match.url_name = 'security.product-advisories' qs = latest_queryset(req, {'slug': 'firefox'}) self.assertListEqual(advisories_fx, list(qs.order_by('year', 'order'))) def test_latest_queryset_product_version(self): """Should advisories for a single product version.""" advisories_30 = [self.new_advisory(fixed_in=['Firefox 30.{0}'.format(i)]) for i in range(5)] advisories_29 = [self.new_advisory(fixed_in=['Firefox 29.0.{0}'.format(i)]) for i in range(1, 5)] # make sure the one with no point version is included advisories_29.append(self.new_advisory(fixed_in=['Firefox 29.0'])) # make sure the one outside of 29.0 isn't included self.new_advisory(fixed_in=['Firefox 29.1']) req = self.rf.get('/') req.resolver_match = Mock() req.resolver_match.url_name = 'security.product-version-advisories' qs = latest_queryset(req, {'product': 'firefox', 'version': '30'}) self.assertListEqual(advisories_30, list(qs.order_by('year', 'order'))) qs = latest_queryset(req, {'product': 'firefox', 'version': '30.1'}) self.assertEqual(advisories_30[1], qs.get()) qs = latest_queryset(req, {'product': 'firefox', 'version': '29.0'}) self.assertListEqual(advisories_29, list(qs.order_by('year', 'order'))) class TestKVRedirects(TestCase): def _test_names(self, url_component, expected): # old urls lack '/en-US' prefix, but that will be the first redirect. path = '/en-US/security/known-vulnerabilities/{0}.html'.format(url_component) resp = self.client.get(path) eq_(resp.status_code, 301) eq_(expected, resp['Location'].split('/')[-2]) def test_correct_redirects(self): self._test_names('firefox', 'firefox') self._test_names('firefoxESR', 'firefox-esr') self._test_names('firefox20', 'firefox-2.0') self._test_names('thunderbird15', 'thunderbird-1.5') self._test_names('suite17', 'mozilla-suite') def test_spaces_removed(self): """Should succeed even if accidental spaces are in the URL. Bug 1171181. """ self._test_names('firefox3%20%200', 'firefox-3.0') def test_unknown_is_404(self): """Should 410 instead of 500 if an unknown url matches the redirector. Bug 1171181. """ path = '/en-US/security/known-vulnerabilities/the-dude-abides-15.html' resp = self.client.get(path) eq_(resp.status_code, 410)
mpl-2.0
4eek/edx-platform
common/test/acceptance/pages/lms/auto_auth.py
66
3293
""" Auto-auth page (used to automatically log in during testing). """ import re import urllib from bok_choy.page_object import PageObject, unguarded from . import AUTH_BASE_URL class AutoAuthPage(PageObject): """ The automatic authorization page. When allowed via the django settings file, visiting this url will create a user and log them in. """ CONTENT_REGEX = r'.+? user (?P<username>\S+) \((?P<email>.+?)\) with password \S+ and user_id (?P<user_id>\d+)$' def __init__(self, browser, username=None, email=None, password=None, staff=None, course_id=None, enrollment_mode=None, roles=None): """ Auto-auth is an end-point for HTTP GET requests. By default, it will create accounts with random user credentials, but you can also specify credentials using querystring parameters. `username`, `email`, and `password` are the user's credentials (strings) `staff` is a boolean indicating whether the user is global staff. `course_id` is the ID of the course to enroll the student in. Currently, this has the form "org/number/run" Note that "global staff" is NOT the same as course staff. """ super(AutoAuthPage, self).__init__(browser) # This will eventually hold the details about the user account self._user_info = None # Create query string parameters if provided self._params = {} if username is not None: self._params['username'] = username if email is not None: self._params['email'] = email if password is not None: self._params['password'] = password if staff is not None: self._params['staff'] = "true" if staff else "false" if course_id is not None: self._params['course_id'] = course_id if enrollment_mode: self._params['enrollment_mode'] = enrollment_mode if roles is not None: self._params['roles'] = roles @property def url(self): """ Construct the URL. """ url = AUTH_BASE_URL + "/auto_auth" query_str = urllib.urlencode(self._params) if query_str: url += "?" + query_str return url def is_browser_on_page(self): return True if self.get_user_info() is not None else False @unguarded def get_user_info(self): """Parse the auto auth page body to extract relevant details about the user that was logged in.""" message = self.q(css='BODY').text[0] match = re.match(self.CONTENT_REGEX, message) if not match: return None else: user_info = match.groupdict() user_info['user_id'] = int(user_info['user_id']) return user_info @property def user_info(self): """A dictionary containing details about the user account.""" if self._user_info is None: user_info = self.get_user_info() if user_info is not None: self._user_info = self.get_user_info() return self._user_info def get_user_id(self): """ Finds and returns the user_id """ return self.user_info['user_id']
agpl-3.0
Lujeni/ansible
lib/ansible/modules/network/nxos/nxos_reboot.py
18
2450
#!/usr/bin/python # # 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.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: nxos_reboot extends_documentation_fragment: nxos version_added: 2.2 short_description: Reboot a network device. description: - Reboot a network device. author: - Jason Edelman (@jedelman8) - Gabriele Gerbino (@GGabriele) notes: - Tested against NXOSv 7.3.(0)D1(1) on VIRL - The module will fail due to timeout issues, but the reboot will be performed anyway. options: confirm: description: - Safeguard boolean. Set to true if you're sure you want to reboot. required: false default: false type: bool ''' EXAMPLES = ''' - nxos_reboot: confirm: true ''' RETURN = ''' rebooted: description: Whether the device was instructed to reboot. returned: success type: bool sample: true ''' from ansible.module_utils.network.nxos.nxos import load_config from ansible.module_utils.network.nxos.nxos import nxos_argument_spec from ansible.module_utils.basic import AnsibleModule def reboot(module): cmds = 'terminal dont-ask ; reload' opts = {'ignore_timeout': True} load_config(module, cmds, False, opts) def main(): argument_spec = dict( confirm=dict(default=False, type='bool') ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = dict(changed=False, warnings=warnings) if module.params['confirm']: if not module.check_mode: reboot(module) results['changed'] = True module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
MicBrain/cvmfs
python/cvmfs/history.py
2
2111
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by René Meusel This file is part of the CernVM File System auxiliary tools. """ import datetime from _common import DatabaseObject class RevisionTag: """ Specific revisions in CernVM-FS 2.1.x repositories have named tags """ @staticmethod def sql_query(): return '''SELECT name, hash, revision, timestamp, channel, description FROM tags ORDER BY timestamp DESC''' def __init__(self, sql_result): self.name = sql_result[0] self.hash = sql_result[1] self.revision = int(sql_result[2]) self.timestamp = datetime.datetime.fromtimestamp(int(sql_result[3])) self.channel = int(sql_result[4]) self.description = sql_result[5] def __str__(self): return "<RevisionTag '" + self.name + "'>" def __repr__(self): return self.__str__() class History(DatabaseObject): """ Wrapper around CernVM-FS 2.1.x repository history databases """ @staticmethod def open(history_path): """ Initializes a History Database from a local file path """ f = open(history_path) return History(f) def __init__(self, history_file): DatabaseObject.__init__(self, history_file) self._read_properties() def __str__(self): return "<History for '" + self.repository_name + "'>" def __repr__(self): return self.__str__() def __iter__(self): return self.list_tags().__iter__() def list_tags(self): results = self.run_sql(RevisionTag.sql_query()) return [ RevisionTag(sql_res) for sql_res in results ] def _read_properties(self): self.read_properties_table(lambda prop_key, prop_value: self._read_property(prop_key, prop_value)) assert hasattr(self, 'schema') and self.schema == '1.0' def _read_property(self, prop_key, prop_value): if prop_key == "schema": self.schema = prop_value if prop_key == "fqrn": self.repository_name = prop_value
bsd-3-clause
holycrepe/anki
aqt/errors.py
16
3576
# Copyright: Damien Elmes <anki@ichi2.net> # -*- coding: utf-8 -*- # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html import sys import cgi from anki.lang import _ from aqt.qt import * from aqt.utils import showText, showWarning class ErrorHandler(QObject): "Catch stderr and write into buffer." ivl = 100 def __init__(self, mw): QObject.__init__(self, mw) self.mw = mw self.timer = None self.connect(self, SIGNAL("errorTimer"), self._setTimer) self.pool = "" sys.stderr = self def write(self, data): # make sure we have unicode if not isinstance(data, unicode): data = unicode(data, "utf8", "replace") # dump to stdout sys.stdout.write(data.encode("utf-8")) # save in buffer self.pool += data # and update timer self.setTimer() def setTimer(self): # we can't create a timer from a different thread, so we post a # message to the object on the main thread self.emit(SIGNAL("errorTimer")) def _setTimer(self): if not self.timer: self.timer = QTimer(self.mw) self.mw.connect(self.timer, SIGNAL("timeout()"), self.onTimeout) self.timer.setInterval(self.ivl) self.timer.setSingleShot(True) self.timer.start() def tempFolderMsg(self): return _("""\ The permissions on your system's temporary folder are incorrect, and Anki is \ not able to correct them automatically. Please search for 'temp folder' in the \ Anki manual for more information.""") def onTimeout(self): error = cgi.escape(self.pool) self.pool = "" self.mw.progress.clear() if "abortSchemaMod" in error: return if "Pyaudio not" in error: return showWarning(_("Please install PyAudio")) if "install mplayer" in error: return showWarning(_("Please install mplayer")) if "no default output" in error: return showWarning(_("Please connect a microphone, and ensure " "other programs are not using the audio device.")) if "invalidTempFolder" in error: return showWarning(self.tempFolderMsg()) if "disk I/O error" in error: return showWarning(_("""\ An error occurred while accessing the database. Possible causes: - Antivirus, firewall, backup, or synchronization software may be \ interfering with Anki. Try disabling such software and see if the \ problem goes away. - Your disk may be full. - The Documents/Anki folder may be on a network drive. - Files in the Documents/Anki folder may not be writeable. - Your hard disk may have errors. It's a good idea to run Tools>Check Database to ensure your collection \ is not corrupt. """)) stdText = _("""\ An error occurred. It may have been caused by a harmless bug, <br> or your deck may have a problem. <p>To confirm it's not a problem with your deck, please run <b>Tools &gt; Check Database</b>. <p>If that doesn't fix the problem, please copy the following<br> into a bug report:""") pluginText = _("""\ An error occurred in an add-on.<br> Please post on the add-on forum:<br>%s<br>""") pluginText %= "https://anki.tenderapp.com/discussions/add-ons" if "addon" in error: txt = pluginText else: txt = stdText # show dialog txt = txt + "<div style='white-space: pre-wrap'>" + error + "</div>" showText(txt, type="html")
agpl-3.0
bwencke/eastmonroe
lib/werkzeug/contrib/testtools.py
319
2449
# -*- coding: utf-8 -*- """ werkzeug.contrib.testtools ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module implements extended wrappers for simplified testing. `TestResponse` A response wrapper which adds various cached attributes for simplified assertions on various content types. :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from werkzeug.utils import cached_property, import_string from werkzeug.wrappers import Response from warnings import warn warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and ' 'will be removed with Werkzeug 1.0')) class ContentAccessors(object): """ A mixin class for response objects that provides a couple of useful accessors for unittesting. """ def xml(self): """Get an etree if possible.""" if 'xml' not in self.mimetype: raise AttributeError( 'Not a XML response (Content-Type: %s)' % self.mimetype) for module in ['xml.etree.ElementTree', 'ElementTree', 'elementtree.ElementTree']: etree = import_string(module, silent=True) if etree is not None: return etree.XML(self.body) raise RuntimeError('You must have ElementTree installed ' 'to use TestResponse.xml') xml = cached_property(xml) def lxml(self): """Get an lxml etree if possible.""" if ('html' not in self.mimetype and 'xml' not in self.mimetype): raise AttributeError('Not an HTML/XML response') from lxml import etree try: from lxml.html import fromstring except ImportError: fromstring = etree.HTML if self.mimetype=='text/html': return fromstring(self.data) return etree.XML(self.data) lxml = cached_property(lxml) def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.mimetype: raise AttributeError('Not a JSON response') try: from simplejson import loads except ImportError: from json import loads return loads(self.data) json = cached_property(json) class TestResponse(Response, ContentAccessors): """Pass this to `werkzeug.test.Client` for easier unittesting."""
apache-2.0
crafty78/ansible
lib/ansible/module_utils/redhat.py
78
10206
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), James Laska # 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. # # 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 os import re import types import ConfigParser class RegistrationBase(object): def __init__(self, module, username=None, password=None): self.module = module self.username = username self.password = password def configure(self): raise NotImplementedError("Must be implemented by a sub-class") def enable(self): # Remove any existing redhat.repo redhat_repo = '/etc/yum.repos.d/redhat.repo' if os.path.isfile(redhat_repo): os.unlink(redhat_repo) def register(self): raise NotImplementedError("Must be implemented by a sub-class") def unregister(self): raise NotImplementedError("Must be implemented by a sub-class") def unsubscribe(self): raise NotImplementedError("Must be implemented by a sub-class") def update_plugin_conf(self, plugin, enabled=True): plugin_conf = '/etc/yum/pluginconf.d/%s.conf' % plugin if os.path.isfile(plugin_conf): cfg = ConfigParser.ConfigParser() cfg.read([plugin_conf]) if enabled: cfg.set('main', 'enabled', 1) else: cfg.set('main', 'enabled', 0) fd = open(plugin_conf, 'rwa+') cfg.write(fd) fd.close() def subscribe(self, **kwargs): raise NotImplementedError("Must be implemented by a sub-class") class Rhsm(RegistrationBase): def __init__(self, module, username=None, password=None): RegistrationBase.__init__(self, module, username, password) self.config = self._read_config() self.module = module def _read_config(self, rhsm_conf='/etc/rhsm/rhsm.conf'): ''' Load RHSM configuration from /etc/rhsm/rhsm.conf. Returns: * ConfigParser object ''' # Read RHSM defaults ... cp = ConfigParser.ConfigParser() cp.read(rhsm_conf) # Add support for specifying a default value w/o having to standup some configuration # Yeah, I know this should be subclassed ... but, oh well def get_option_default(self, key, default=''): sect, opt = key.split('.', 1) if self.has_section(sect) and self.has_option(sect, opt): return self.get(sect, opt) else: return default cp.get_option = types.MethodType(get_option_default, cp, ConfigParser.ConfigParser) return cp def enable(self): ''' Enable the system to receive updates from subscription-manager. This involves updating affected yum plugins and removing any conflicting yum repositories. ''' RegistrationBase.enable(self) self.update_plugin_conf('rhnplugin', False) self.update_plugin_conf('subscription-manager', True) def configure(self, **kwargs): ''' Configure the system as directed for registration with RHN Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'config'] # Pass supplied **kwargs as parameters to subscription-manager. Ignore # non-configuration parameters and replace '_' with '.'. For example, # 'server_hostname' becomes '--system.hostname'. for k,v in kwargs.items(): if re.search(r'^(system|rhsm)_', k): args.append('--%s=%s' % (k.replace('_','.'), v)) self.module.run_command(args, check_rc=True) @property def is_registered(self): ''' Determine whether the current system Returns: * Boolean - whether the current system is currently registered to RHN. ''' # Quick version... if False: return os.path.isfile('/etc/pki/consumer/cert.pem') and \ os.path.isfile('/etc/pki/consumer/key.pem') args = ['subscription-manager', 'identity'] rc, stdout, stderr = self.module.run_command(args, check_rc=False) if rc == 0: return True else: return False def register(self, username, password, autosubscribe, activationkey): ''' Register the current system to the provided RHN server Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'register'] # Generate command arguments if activationkey: args.append('--activationkey "%s"' % activationkey) else: if autosubscribe: args.append('--autosubscribe') if username: args.extend(['--username', username]) if password: args.extend(['--password', password]) # Do the needful... rc, stderr, stdout = self.module.run_command(args, check_rc=True) def unsubscribe(self): ''' Unsubscribe a system from all subscribed channels Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'unsubscribe', '--all'] rc, stderr, stdout = self.module.run_command(args, check_rc=True) def unregister(self): ''' Unregister a currently registered system Raises: * Exception - if error occurs while running command ''' args = ['subscription-manager', 'unregister'] rc, stderr, stdout = self.module.run_command(args, check_rc=True) def subscribe(self, regexp): ''' Subscribe current system to available pools matching the specified regular expression Raises: * Exception - if error occurs while running command ''' # Available pools ready for subscription available_pools = RhsmPools(self.module) for pool in available_pools.filter(regexp): pool.subscribe() class RhsmPool(object): ''' Convenience class for housing subscription information ''' def __init__(self, module, **kwargs): self.module = module for k,v in kwargs.items(): setattr(self, k, v) def __str__(self): return str(self.__getattribute__('_name')) def subscribe(self): args = "subscription-manager subscribe --pool %s" % self.PoolId rc, stdout, stderr = self.module.run_command(args, check_rc=True) if rc == 0: return True else: return False class RhsmPools(object): """ This class is used for manipulating pools subscriptions with RHSM """ def __init__(self, module): self.module = module self.products = self._load_product_list() def __iter__(self): return self.products.__iter__() def _load_product_list(self): """ Loads list of all available pools for system in data structure """ args = "subscription-manager list --available" rc, stdout, stderr = self.module.run_command(args, check_rc=True) products = [] for line in stdout.split('\n'): # Remove leading+trailing whitespace line = line.strip() # An empty line implies the end of an output group if len(line) == 0: continue # If a colon ':' is found, parse elif ':' in line: (key, value) = line.split(':',1) key = key.strip().replace(" ", "") # To unify value = value.strip() if key in ['ProductName', 'SubscriptionName']: # Remember the name for later processing products.append(RhsmPool(self.module, _name=value, key=value)) elif products: # Associate value with most recently recorded product products[-1].__setattr__(key, value) # FIXME - log some warning? #else: # warnings.warn("Unhandled subscription key/value: %s/%s" % (key,value)) return products def filter(self, regexp='^$'): ''' Return a list of RhsmPools whose name matches the provided regular expression ''' r = re.compile(regexp) for product in self.products: if r.search(product._name): yield product
gpl-3.0
Denisolt/Tensorflow_Chat_Bot
local/lib/python2.7/site-packages/tensorflow/python/training/training.py
6
11555
# 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. # ============================================================================== # pylint: disable=line-too-long """This library provides a set of classes and functions that helps train models. ## Optimizers The Optimizer base class provides methods to compute gradients for a loss and apply gradients to variables. A collection of subclasses implement classic optimization algorithms such as GradientDescent and Adagrad. You never instantiate the Optimizer class itself, but instead instantiate one of the subclasses. @@Optimizer @@GradientDescentOptimizer @@AdadeltaOptimizer @@AdagradOptimizer @@AdagradDAOptimizer @@MomentumOptimizer @@AdamOptimizer @@FtrlOptimizer @@ProximalGradientDescentOptimizer @@ProximalAdagradOptimizer @@RMSPropOptimizer ## Gradient Computation TensorFlow provides functions to compute the derivatives for a given TensorFlow computation graph, adding operations to the graph. The optimizer classes automatically compute derivatives on your graph, but creators of new Optimizers or expert users can call the lower-level functions below. @@gradients @@AggregationMethod @@stop_gradient @@hessians ## Gradient Clipping TensorFlow provides several operations that you can use to add clipping functions to your graph. You can use these functions to perform general data clipping, but they're particularly useful for handling exploding or vanishing gradients. @@clip_by_value @@clip_by_norm @@clip_by_average_norm @@clip_by_global_norm @@global_norm ## Decaying the learning rate @@exponential_decay @@inverse_time_decay @@natural_exp_decay @@piecewise_constant @@polynomial_decay ## Moving Averages Some training algorithms, such as GradientDescent and Momentum often benefit from maintaining a moving average of variables during optimization. Using the moving averages for evaluations often improve results significantly. @@ExponentialMovingAverage ## Coordinator and QueueRunner See [Threading and Queues](../../how_tos/threading_and_queues/index.md) for how to use threads and queues. For documentation on the Queue API, see [Queues](../../api_docs/python/io_ops.md#queues). @@Coordinator @@QueueRunner @@add_queue_runner @@start_queue_runners ## Distributed execution See [Distributed TensorFlow](../../how_tos/distributed/index.md) for more information about how to configure a distributed TensorFlow program. @@Server @@Supervisor @@SessionManager @@ClusterSpec @@replica_device_setter @@Scaffold @@MonitoredTrainingSession @@SessionCreator @@ChiefSessionCreator @@WorkerSessionCreator @@MonitoredSession ## Summary Operations The following ops output [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) protocol buffers as serialized string tensors. You can fetch the output of a summary op in a session, and pass it to a [SummaryWriter](../../api_docs/python/train.md#SummaryWriter) to append it to an event file. Event files contain [`Event`](https://www.tensorflow.org/code/tensorflow/core/util/event.proto) protos that can contain `Summary` protos along with the timestamp and step. You can then use TensorBoard to visualize the contents of the event files. See [TensorBoard and Summaries](../../how_tos/summaries_and_tensorboard/index.md) for more details. @@scalar_summary @@image_summary @@audio_summary @@histogram_summary @@zero_fraction @@merge_summary @@merge_all_summaries ## Adding Summaries to Event Files See [Summaries and TensorBoard](../../how_tos/summaries_and_tensorboard/index.md) for an overview of summaries, event files, and visualization in TensorBoard. @@SummaryWriter @@SummaryWriterCache @@summary_iterator ## Training utilities @@global_step @@basic_train_loop @@get_global_step @@assert_global_step @@write_graph @@SessionRunHook @@LoggingTensorHook @@StopAtStepHook @@CheckpointSaverHook @@NewCheckpointReader @@StepCounterHook @@NanLossDuringTrainingError @@NanTensorHook @@SummarySaverHook @@SessionRunArgs @@SessionRunContext @@SessionRunValues @@LooperThread """ # pylint: enable=line-too-long # Optimizers. from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys as _sys from tensorflow.python.ops import io_ops as _io_ops from tensorflow.python.ops import state_ops as _state_ops from tensorflow.python.util.all_util import remove_undocumented # pylint: disable=g-bad-import-order,unused-import from tensorflow.python.training.adadelta import AdadeltaOptimizer from tensorflow.python.training.adagrad import AdagradOptimizer from tensorflow.python.training.adagrad_da import AdagradDAOptimizer from tensorflow.python.training.proximal_adagrad import ProximalAdagradOptimizer from tensorflow.python.training.adam import AdamOptimizer from tensorflow.python.training.ftrl import FtrlOptimizer from tensorflow.python.training.momentum import MomentumOptimizer from tensorflow.python.training.moving_averages import ExponentialMovingAverage from tensorflow.python.training.optimizer import Optimizer from tensorflow.python.training.rmsprop import RMSPropOptimizer from tensorflow.python.training.gradient_descent import GradientDescentOptimizer from tensorflow.python.training.proximal_gradient_descent import ProximalGradientDescentOptimizer from tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizer from tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizerV2 # Utility classes for training. from tensorflow.python.training.coordinator import Coordinator from tensorflow.python.training.coordinator import LooperThread # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.training.queue_runner import * # For the module level doc. from tensorflow.python.training import input as _input from tensorflow.python.training.input import * # pylint: enable=wildcard-import from tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook from tensorflow.python.training.basic_session_run_hooks import StopAtStepHook from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook from tensorflow.python.training.basic_session_run_hooks import StepCounterHook from tensorflow.python.training.basic_session_run_hooks import NanLossDuringTrainingError from tensorflow.python.training.basic_session_run_hooks import NanTensorHook from tensorflow.python.training.basic_session_run_hooks import SummarySaverHook from tensorflow.python.training.basic_loops import basic_train_loop from tensorflow.python.training.device_setter import replica_device_setter from tensorflow.python.training.monitored_session import Scaffold from tensorflow.python.training.monitored_session import MonitoredTrainingSession from tensorflow.python.training.monitored_session import SessionCreator from tensorflow.python.training.monitored_session import ChiefSessionCreator from tensorflow.python.training.monitored_session import WorkerSessionCreator from tensorflow.python.training.monitored_session import MonitoredSession from tensorflow.python.training.saver import Saver from tensorflow.python.training.saver import checkpoint_exists from tensorflow.python.training.saver import generate_checkpoint_state_proto from tensorflow.python.training.saver import get_checkpoint_mtimes from tensorflow.python.training.saver import get_checkpoint_state from tensorflow.python.training.saver import latest_checkpoint from tensorflow.python.training.saver import update_checkpoint_state from tensorflow.python.training.saver import export_meta_graph from tensorflow.python.training.saver import import_meta_graph from tensorflow.python.training.session_run_hook import SessionRunHook from tensorflow.python.training.session_run_hook import SessionRunArgs from tensorflow.python.training.session_run_hook import SessionRunContext from tensorflow.python.training.session_run_hook import SessionRunValues from tensorflow.python.training.session_manager import SessionManager from tensorflow.python.training.summary_io import summary_iterator from tensorflow.python.training.summary_io import SummaryWriter from tensorflow.python.training.summary_io import SummaryWriterCache from tensorflow.python.training.supervisor import Supervisor from tensorflow.python.training.training_util import write_graph from tensorflow.python.training.training_util import global_step from tensorflow.python.training.training_util import get_global_step from tensorflow.python.training.training_util import assert_global_step from tensorflow.python.pywrap_tensorflow import do_quantize_training_on_graphdef from tensorflow.python.pywrap_tensorflow import NewCheckpointReader # pylint: disable=wildcard-import # Training data protos. from tensorflow.core.example.example_pb2 import * from tensorflow.core.example.feature_pb2 import * from tensorflow.core.protobuf.saver_pb2 import * # Utility op. Open Source. TODO(touts): move to nn? from tensorflow.python.training.learning_rate_decay import * # pylint: enable=wildcard-import # Distributed computing support. from tensorflow.core.protobuf.tensorflow_server_pb2 import ClusterDef from tensorflow.core.protobuf.tensorflow_server_pb2 import JobDef from tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef from tensorflow.python.training.server_lib import ClusterSpec from tensorflow.python.training.server_lib import Server # Symbols whitelisted for export without documentation. _allowed_symbols = [ # TODO(cwhipkey): review these and move to contrib or expose through # documentation. "generate_checkpoint_state_proto", # Used internally by saver. "checkpoint_exists", # Only used in test? "get_checkpoint_mtimes", # Only used in test? # Legacy: remove. "do_quantize_training_on_graphdef", # At least use grah_def, not graphdef. # No uses within tensorflow. "queue_runner", # Use tf.train.start_queue_runner etc directly. # This is also imported internally. # TODO(drpng): document these. The reference in howtos/distributed does # not link. "SyncReplicasOptimizer", "SyncReplicasOptimizerV2", # Protobufs: "BytesList", # from example_pb2. "ClusterDef", "Example", # from example_pb2 "Feature", # from example_pb2 "Features", # from example_pb2 "FeatureList", # from example_pb2 "FeatureLists", # from example_pb2 "FloatList", # from example_pb2. "Int64List", # from example_pb2. "JobDef", "SaverDef", # From saver_pb2. "SequenceExample", # from example_pb2. "ServerDef", ] # Include extra modules for docstrings because: # * Input methods in tf.train are documented in io_ops. # * Saver methods in tf.train are documented in state_ops. remove_undocumented(__name__, _allowed_symbols, [_sys.modules[__name__], _io_ops, _state_ops])
gpl-3.0
darkleons/BE
addons/report_webkit/wizard/report_webkit_actions.py
382
6537
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Vincent Renaville # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 # ############################################################################## from openerp.tools.translate import _ from openerp.osv import fields, osv class report_webkit_actions(osv.osv_memory): _name = "report.webkit.actions" _description = "Webkit Actions" _columns = { 'print_button':fields.boolean('Add print button', help="Check this to add a Print action for this Report in the sidebar of the corresponding document types"), 'open_action':fields.boolean('Open added action', help="Check this to view the newly added internal print action after creating it (technical view) "), } _defaults = { 'print_button': lambda *a: True, 'open_action': lambda *a: False, } def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Changes the view dynamically @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view. """ if not context: context = {} res = super(report_webkit_actions, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False) record_id = context and context.get('active_id', False) or False active_model = context.get('active_model') if not record_id or (active_model and active_model != 'ir.actions.report.xml'): return res report = self.pool['ir.actions.report.xml'].browse( cr, uid, context.get('active_id'), context=context ) ir_values_obj = self.pool['ir.values'] ids = ir_values_obj.search( cr, uid, [('value','=',report.type+','+str(context.get('active_id')))] ) if ids: res['arch'] = '''<form string="Add Print Buttons"> <label string="Report Action already exist for this report."/> </form> ''' return res def do_action(self, cr, uid, ids, context=None): """ This Function Open added Action. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of report.webkit.actions's ID @param context: A standard dictionary @return: Dictionary of ir.values form. """ if context is None: context = {} report_obj = self.pool['ir.actions.report.xml'] for current in self.browse(cr, uid, ids, context=context): report = report_obj.browse( cr, uid, context.get('active_id'), context=context ) if current.print_button: ir_values_obj = self.pool['ir.values'] res = ir_values_obj.set( cr, uid, 'action', 'client_print_multi', report.report_name, [report.model], 'ir.actions.report.xml,%d' % context.get('active_id', False), isobject=True ) else: ir_values_obj = self.pool['ir.values'] res = ir_values_obj.set( cr, uid, 'action', 'client_print_multi', report.report_name, [report.model,0], 'ir.actions.report.xml,%d' % context.get('active_id', False), isobject=True ) if res[0]: if not current.open_action: return {'type': 'ir.actions.act_window_close'} return { 'name': _('Client Actions Connections'), 'view_type': 'form', 'view_mode': 'form', 'res_id' : res[0], 'res_model': 'ir.values', 'view_id': False, 'type': 'ir.actions.act_window', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
TobyRoseman/SFrame
cxxtest/test/test_cxxtest.py
44
35206
#------------------------------------------------------------------------- # CxxTest: A lightweight C++ unit testing library. # Copyright (c) 2008 Sandia Corporation. # This software is distributed under the LGPL License v3 # For more information, see the COPYING file in the top CxxTest directory. # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains certain rights in this software. #------------------------------------------------------------------------- import shutil import time import sys import os import os.path import glob import difflib import subprocess import re import string if sys.version_info < (2,7): import unittest2 as unittest else: import unittest try: import ply ply_available=True except: ply_available=False try: import cxxtest cxxtest_available=True import cxxtest.cxxtestgen except: cxxtest_available=False currdir = os.path.dirname(os.path.abspath(__file__))+os.sep sampledir = os.path.dirname(os.path.dirname(currdir))+'/sample'+os.sep cxxtestdir = os.path.dirname(os.path.dirname(currdir))+os.sep compilerre = re.compile("^(?P<path>[^:]+)(?P<rest>:.*)$") dirre = re.compile("^([^%s]*/)*" % re.escape(os.sep)) xmlre = re.compile("\"(?P<path>[^\"]*/[^\"]*)\"") datere = re.compile("date=\"[^\"]*\"") # Headers from the cxxtest/sample directory samples = ' '.join(file for file in sorted(glob.glob(sampledir+'*.h'))) guiInputs=currdir+'../sample/gui/GreenYellowRed.h' if sys.platform.startswith('win'): target_suffix = '.exe' command_separator = ' && ' cxxtestdir = '/'.join(cxxtestdir.split('\\')) remove_extra_path_prefixes_on_windows = True else: target_suffix = '' command_separator = '; ' remove_extra_path_prefixes_on_windows = False def find(filename, executable=False, isfile=True, validate=None): # # Use the PATH environment if it is defined and not empty # if "PATH" in os.environ and os.environ["PATH"] != "": search_path = os.environ['PATH'].split(os.pathsep) else: search_path = os.defpath.split(os.pathsep) for path in search_path: test_fname = os.path.join(path, filename) if os.path.exists(test_fname) \ and (not isfile or os.path.isfile(test_fname)) \ and (not executable or os.access(test_fname, os.X_OK)): return os.path.abspath(test_fname) return None def join_commands(command_one, command_two): return command_separator.join([command_one, command_two]) _available = {} def available(compiler, exe_option): if (compiler,exe_option) in _available: return _available[compiler,exe_option] cmd = join_commands("cd %s" % currdir, "%s %s %s %s > %s 2>&1" % (compiler, exe_option, currdir+'anything', currdir+'anything.cpp', currdir+'anything.log')) print("Testing for compiler "+compiler) print("Command: "+cmd) status = subprocess.call(cmd, shell=True) executable = currdir+'anything'+target_suffix flag = status == 0 and os.path.exists(executable) os.remove(currdir+'anything.log') if os.path.exists(executable): os.remove(executable) print("Status: "+str(flag)) _available[compiler,exe_option] = flag return flag def remove_absdir(filename): INPUT=open(filename, 'r') lines = [line.strip() for line in INPUT] INPUT.close() OUTPUT=open(filename, 'w') for line in lines: # remove basedir at front of line match = compilerre.match(line) # see if we can remove the basedir if match: parts = match.groupdict() line = dirre.sub("", parts['path']) + parts['rest'] OUTPUT.write(line+'\n') OUTPUT.close() def normalize_line_for_diff(line): # add spaces around {}<>() line = re.sub("[{}<>()]", r" \0 ", line) # beginnig and ending whitespace line = line.strip() # remove all whitespace # and leave a single space line = ' '.join(line.split()) # remove spaces around "=" line = re.sub(" ?= ?", "=", line) # remove all absolute path prefixes line = ''.join(line.split(cxxtestdir)) if remove_extra_path_prefixes_on_windows: # Take care of inconsistent path prefixes like # "e:\path\to\cxxtest\test", "E:/path/to/cxxtest/test" etc # in output. line = ''.join(line.split(os.path.normcase(cxxtestdir))) line = ''.join(line.split(os.path.normpath(cxxtestdir))) # And some extra relative paths left behind line= re.sub(r'^.*[\\/]([^\\/]+\.(h|cpp))', r'\1', line) # for xml, remove prefixes from everything that looks like a # file path inside "" line = xmlre.sub( lambda match: '"'+re.sub("^[^/]+/", "", match.group(1))+'"', line ) # Remove date info line = datere.sub( lambda match: 'date=""', line) return line def make_diff_readable(diff): i = 0 while i+1 < len(diff): if diff[i][0] == '-' and diff[i+1][0] == '+': l1 = diff[i] l2 = diff[i+1] for j in range(1, min([len(l1), len(l2)])): if l1[j] != l2[j]: if j > 4: j = j-2; l1 = l1[j:] l2 = l2[j:] diff[i] = '-(...)' + l1 diff[i+1] = '+(...)' + l2 break i+=1 def file_diff(filename1, filename2, filtered_reader): remove_absdir(filename1) remove_absdir(filename2) # INPUT=open(filename1, 'r') lines1 = list(filtered_reader(INPUT)) INPUT.close() # INPUT=open(filename2, 'r') lines2 = list(filtered_reader(INPUT)) INPUT.close() # diff = list(difflib.unified_diff(lines2, lines1, fromfile=filename2, tofile=filename1)) if diff: make_diff_readable(diff) raise Exception("ERROR: \n\n%s\n\n%s\n\n" % (lines1, lines2)) diff = '\n'.join(diff) return diff class BaseTestCase(object): fog='' valgrind='' cxxtest_import=False def setUp(self): sys.stderr.write("("+self.__class__.__name__+") ") self.passed=False self.prefix='' self.py_out='' self.py_cpp='' self.px_pre='' self.px_out='' self.build_log='' self.build_target='' def tearDown(self): if not self.passed: return files = [] if os.path.exists(self.py_out): files.append(self.py_out) if os.path.exists(self.py_cpp) and not 'CXXTEST_GCOV_FLAGS' in os.environ: files.append(self.py_cpp) if os.path.exists(self.px_pre): files.append(self.px_pre) if os.path.exists(self.px_out): files.append(self.px_out) if os.path.exists(self.build_log): files.append(self.build_log) if os.path.exists(self.build_target) and not 'CXXTEST_GCOV_FLAGS' in os.environ: files.append(self.build_target) for file in files: try: os.remove(file) except: time.sleep(2) try: os.remove(file) except: print( "Error removing file '%s'" % file) # This is a "generator" that just reads a file and normalizes the lines def file_filter(self, file): for line in file: yield normalize_line_for_diff(line) def check_if_supported(self, filename, msg): target=currdir+'check'+'px'+target_suffix log=currdir+'check'+'_build.log' cmd = join_commands("cd %s" % currdir, "%s %s %s %s. %s%s../ %s > %s 2>&1" % (self.compiler, self.exe_option, target, self.include_option, self.include_option, currdir, filename, log)) status = subprocess.call(cmd, shell=True) os.remove(log) if status != 0 or not os.path.exists(target): self.skipTest(msg) os.remove(target) def init(self, prefix): # self.prefix = self.__class__.__name__+'_'+prefix self.py_out = currdir+self.prefix+'_py.out' self.py_cpp = currdir+self.prefix+'_py.cpp' self.px_pre = currdir+self.prefix+'_px.pre' self.px_out = currdir+self.prefix+'_px.out' self.build_log = currdir+self.prefix+'_build.log' self.build_target = currdir+self.prefix+'px'+target_suffix def check_root(self, prefix='', output=None): self.init(prefix) args = "--have-eh --abort-on-fail --root --error-printer" if self.cxxtest_import: os.chdir(currdir) cxxtest.cxxtestgen.main(['cxxtestgen', self.fog, '-o', self.py_cpp]+re.split('[ ]+',args), True) else: cmd = join_commands("cd %s" % currdir, "%s %s../bin/cxxtestgen %s -o %s %s > %s 2>&1" % (sys.executable, currdir, self.fog, self.py_cpp, args, self.py_out)) status = subprocess.call(cmd, shell=True) self.assertEqual(status, 0, 'Bad return code: %d Error executing cxxtestgen: %s' % (status,cmd)) # files = [self.py_cpp] for i in [1,2]: args = "--have-eh --abort-on-fail --part Part%s.h" % str(i) file = currdir+self.prefix+'_py%s.cpp' % str(i) files.append(file) if self.cxxtest_import: os.chdir(currdir) cxxtest.cxxtestgen.main(['cxxtestgen', self.fog, '-o', file]+re.split('[ ]+',args), True) else: cmd = join_commands("cd %s" % currdir, "%s %s../bin/cxxtestgen %s -o %s %s > %s 2>&1" % (sys.executable, currdir, self.fog, file, args, self.py_out)) status = subprocess.call(cmd, shell=True) self.assertEqual(status, 0, 'Bad return code: %d Error executing cxxtestgen: %s' % (status,cmd)) # cmd = join_commands("cd %s" % currdir, "%s %s %s %s. %s%s../ %s > %s 2>&1" % (self.compiler, self.exe_option, self.build_target, self.include_option, self.include_option, currdir, ' '.join(files), self.build_log)) status = subprocess.call(cmd, shell=True) for file in files: if os.path.exists(file): os.remove(file) self.assertEqual(status, 0, 'Bad return code: %d Error executing command: %s' % (status,cmd)) # cmd = join_commands("cd %s" % currdir, "%s %s -v > %s 2>&1" % (self.valgrind, self.build_target, self.px_pre)) status = subprocess.call(cmd, shell=True) OUTPUT = open(self.px_pre,'a') OUTPUT.write('Error level = '+str(status)+'\n') OUTPUT.close() diffstr = file_diff(self.px_pre, currdir+output, self.file_filter) if not diffstr == '': self.fail("Unexpected differences in output:\n"+diffstr) if self.valgrind != '': self.parse_valgrind(self.px_pre) # self.passed=True def compile(self, prefix='', args=None, compile='', output=None, main=None, failGen=False, run=None, logfile=None, failBuild=False, init=True): """Run cxxtestgen and compile the code that is generated""" if init: self.init(prefix) # if self.cxxtest_import: try: os.chdir(currdir) status = cxxtest.cxxtestgen.main(['cxxtestgen', self.fog, '-o', self.py_cpp]+re.split('[ ]+',args), True) except: status = 1 else: cmd = join_commands("cd %s" % currdir, "%s %s../bin/cxxtestgen %s -o %s %s > %s 2>&1" % (sys.executable, currdir, self.fog, self.py_cpp, args, self.py_out)) status = subprocess.call(cmd, shell=True) if failGen: if status == 0: self.fail('Expected cxxtestgen to fail.') else: self.passed=True return if not self.cxxtest_import: self.assertEqual(status, 0, 'Bad return code: %d Error executing command: %s' % (status,cmd)) # if not main is None: # Compile with main cmd = join_commands("cd %s" % currdir, "%s %s %s %s. %s%s../ %s main.cpp %s > %s 2>&1" % (self.compiler, self.exe_option, self.build_target, self.include_option, self.include_option, currdir, compile, self.py_cpp, self.build_log)) else: # Compile without main cmd = join_commands("cd %s" % currdir, "%s %s %s %s. %s%s../ %s %s > %s 2>&1" % (self.compiler, self.exe_option, self.build_target, self.include_option, self.include_option, currdir, compile, self.py_cpp, self.build_log)) status = subprocess.call(cmd, shell=True) if failBuild: if status == 0: self.fail('Expected compiler to fail.') else: self.passed=True return else: self.assertEqual(status, 0, 'Bad return code: %d Error executing command: %s' % (status,cmd)) # if compile == '' and not output is None: if run is None: cmd = join_commands("cd %s" % currdir, "%s %s -v > %s 2>&1" % (self.valgrind, self.build_target, self.px_pre)) else: cmd = run % (self.valgrind, self.build_target, self.px_pre) status = subprocess.call(cmd, shell=True) OUTPUT = open(self.px_pre,'a') OUTPUT.write('Error level = '+str(status)+'\n') OUTPUT.close() if logfile is None: diffstr = file_diff(self.px_pre, currdir+output, self.file_filter) else: diffstr = file_diff(currdir+logfile, currdir+output, self.file_filter) if not diffstr == '': self.fail("Unexpected differences in output:\n"+diffstr) if self.valgrind != '': self.parse_valgrind(self.px_pre) if not logfile is None: os.remove(currdir+logfile) # if compile == '' and output is None and os.path.exists(self.py_cpp): self.fail("Output cpp file %s should not have been generated." % self.py_cpp) # self.passed=True # # Tests for cxxtestgen # def test_root_or_part(self): """Root/Part""" self.check_root(prefix='root_or_part', output="parts.out") def test_root_plus_part(self): """Root + Part""" self.compile(prefix='root_plus_part', args="--error-printer --root --part "+samples, output="error.out") def test_wildcard(self): """Wildcard input""" self.compile(prefix='wildcard', args='../sample/*.h', main=True, output="wildcard.out") def test_stdio_printer(self): """Stdio printer""" self.compile(prefix='stdio_printer', args="--runner=StdioPrinter "+samples, output="error.out") def test_paren_printer(self): """Paren printer""" self.compile(prefix='paren_printer', args="--runner=ParenPrinter "+samples, output="paren.out") def test_yn_runner(self): """Yes/No runner""" self.compile(prefix='yn_runner', args="--runner=YesNoRunner "+samples, output="runner.out") def test_no_static_init(self): """No static init""" self.compile(prefix='no_static_init', args="--error-printer --no-static-init "+samples, output="error.out") def test_samples_file(self): """Samples file""" # Create a file with the list of sample files OUTPUT = open(currdir+'Samples.txt','w') for line in sorted(glob.glob(sampledir+'*.h')): OUTPUT.write(line+'\n') OUTPUT.close() self.compile(prefix='samples_file', args="--error-printer --headers Samples.txt", output="error.out") os.remove(currdir+'Samples.txt') def test_have_std(self): """Have Std""" self.compile(prefix='have_std', args="--runner=StdioPrinter --have-std HaveStd.h", output="std.out") def test_comments(self): """Comments""" self.compile(prefix='comments', args="--error-printer Comments.h", output="comments.out") def test_longlong(self): """Long long""" self.check_if_supported('longlong.cpp', "Long long is not supported by this compiler") self.compile(prefix='longlong', args="--error-printer --longlong=\"long long\" LongLong.h", output="longlong.out") def test_int64(self): """Int64""" self.check_if_supported('int64.cpp', "64-bit integers are not supported by this compiler") self.compile(prefix='int64', args="--error-printer --longlong=__int64 Int64.h", output="int64.out") def test_include(self): """Include""" self.compile(prefix='include', args="--include=VoidTraits.h --include=LongTraits.h --error-printer IncludeTest.h", output="include.out") # # Template file tests # def test_preamble(self): """Preamble""" self.compile(prefix='preamble', args="--template=preamble.tpl "+samples, output="preamble.out") def test_activate_all(self): """Activate all""" self.compile(prefix='activate_all', args="--template=activate.tpl "+samples, output="error.out") def test_only_suite(self): """Only Suite""" self.compile(prefix='only_suite', args="--template=%s../sample/only.tpl %s" % (currdir, samples), run="%s %s SimpleTest > %s 2>&1", output="suite.out") def test_only_test(self): """Only Test""" self.compile(prefix='only_test', args="--template=%s../sample/only.tpl %s" % (currdir, samples), run="%s %s SimpleTest testAddition > %s 2>&1", output="suite_test.out") def test_have_std_tpl(self): """Have Std - Template""" self.compile(prefix='have_std_tpl', args="--template=HaveStd.tpl HaveStd.h", output="std.out") def test_exceptions_tpl(self): """Exceptions - Template""" self.compile(prefix='exceptions_tpl', args="--template=HaveEH.tpl "+self.ehNormals, output="eh_normals.out") # # Test cases which do not require exception handling # def test_no_errors(self): """No errors""" self.compile(prefix='no_errors', args="--error-printer GoodSuite.h", output="good.out") def test_infinite_values(self): """Infinite values""" self.compile(prefix='infinite_values', args="--error-printer --have-std TestNonFinite.h", output="infinite.out") def test_max_dump_size(self): """Max dump size""" self.compile(prefix='max_dump_size', args="--error-printer --include=MaxDump.h DynamicMax.h SameData.h", output='max.out') def test_wide_char(self): """Wide char""" self.check_if_supported('wchar.cpp', "The file wchar.cpp is not supported.") self.compile(prefix='wide_char', args="--error-printer WideCharTest.h", output="wchar.out") #def test_factor(self): #"""Factor""" #self.compile(prefix='factor', args="--error-printer --factor Factor.h", output="factor.out") def test_user_traits(self): """User traits""" self.compile(prefix='user_traits', args="--template=UserTraits.tpl UserTraits.h", output='user.out') normals = " ".join(currdir+file for file in ["LessThanEquals.h","Relation.h","DefaultTraits.h","DoubleCall.h","SameData.h","SameFiles.h","Tsm.h","TraitsTest.h","MockTest.h","SameZero.h"]) def test_normal_behavior_xunit(self): """Normal Behavior with XUnit Output""" self.compile(prefix='normal_behavior_xunit', args="--xunit-printer "+self.normals, logfile='TEST-cxxtest.xml', output="normal.xml") def test_normal_behavior(self): """Normal Behavior""" self.compile(prefix='normal_behavior', args="--error-printer "+self.normals, output="normal.out") def test_normal_plus_abort(self): """Normal + Abort""" self.compile(prefix='normal_plus_abort', args="--error-printer --have-eh --abort-on-fail "+self.normals, output="abort.out") def test_stl_traits(self): """STL Traits""" self.check_if_supported('stpltpl.cpp', "The file stpltpl.cpp is not supported.") self.compile(prefix='stl_traits', args="--error-printer StlTraits.h", output="stl.out") def test_normal_behavior_world(self): """Normal Behavior with World""" self.compile(prefix='normal_behavior_world', args="--error-printer --world=myworld "+self.normals, output="world.out") # # Test cases which do require exception handling # def test_throw_wo_std(self): """Throw w/o Std""" self.compile(prefix='test_throw_wo_std', args="--template=ThrowNoStd.tpl ThrowNoStd.h", output='throw.out') ehNormals = "Exceptions.h DynamicAbort.h" def test_exceptions(self): """Exceptions""" self.compile(prefix='exceptions', args="--error-printer --have-eh "+self.ehNormals, output="eh_normals.out") def test_exceptions_plus_abort(self): """Exceptions plus abort""" self.compile(prefix='exceptions', args="--error-printer --abort-on-fail --have-eh DynamicAbort.h DeepAbort.h ThrowsAssert.h", output="eh_plus_abort.out") def test_default_abort(self): """Default abort""" self.compile(prefix='default_abort', args="--error-printer --include=DefaultAbort.h "+self.ehNormals+ " DeepAbort.h ThrowsAssert.h", output="default_abort.out") def test_default_no_abort(self): """Default no abort""" self.compile(prefix='default_no_abort', args="--error-printer "+self.ehNormals+" DeepAbort.h ThrowsAssert.h", output="default_abort.out") # # Global Fixtures # def test_global_fixtures(self): """Global fixtures""" self.compile(prefix='global_fixtures', args="--error-printer GlobalFixtures.h WorldFixtures.h", output="gfxs.out") def test_gf_suw_fails(self): """GF:SUW fails""" self.compile(prefix='gf_suw_fails', args="--error-printer SetUpWorldFails.h", output="suwf.out") def test_gf_suw_error(self): """GF:SUW error""" self.compile(prefix='gf_suw_error', args="--error-printer SetUpWorldError.h", output="suwe.out") def test_gf_suw_throws(self): """GF:SUW throws""" self.compile(prefix='gf_suw_throws', args="--error-printer SetUpWorldThrows.h", output="suwt.out") def test_gf_su_fails(self): """GF:SU fails""" self.compile(prefix='gf_su_fails', args="--error-printer GfSetUpFails.h", output="gfsuf.out") def test_gf_su_throws(self): """GF:SU throws""" self.compile(prefix='gf_su_throws', args="--error-printer GfSetUpThrows.h", output="gfsut.out") def test_gf_td_fails(self): """GF:TD fails""" self.compile(prefix='gf_td_fails', args="--error-printer GfTearDownFails.h", output="gftdf.out") def test_gf_td_throws(self): """GF:TD throws""" self.compile(prefix='gf_td_throws', args="--error-printer GfTearDownThrows.h", output="gftdt.out") def test_gf_tdw_fails(self): """GF:TDW fails""" self.compile(prefix='gf_tdw_fails', args="--error-printer TearDownWorldFails.h", output="tdwf.out") def test_gf_tdw_throws(self): """GF:TDW throws""" self.compile(prefix='gf_tdw_throws', args="--error-printer TearDownWorldThrows.h", output="tdwt.out") def test_gf_suw_fails_XML(self): """GF:SUW fails""" self.compile(prefix='gf_suw_fails', args="--xunit-printer SetUpWorldFails.h", output="suwf.out") # # GUI # def test_gui(self): """GUI""" self.compile(prefix='gui', args='--gui=DummyGui %s' % guiInputs, output ="gui.out") def test_gui_runner(self): """GUI + runner""" self.compile(prefix='gui_runner', args="--gui=DummyGui --runner=ParenPrinter %s" % guiInputs, output="gui_paren.out") def test_qt_gui(self): """QT GUI""" self.compile(prefix='qt_gui', args="--gui=QtGui GoodSuite.h", compile=self.qtFlags) def test_win32_gui(self): """Win32 GUI""" self.compile(prefix='win32_gui', args="--gui=Win32Gui GoodSuite.h", compile=self.w32Flags) def test_win32_unicode(self): """Win32 Unicode""" self.compile(prefix='win32_unicode', args="--gui=Win32Gui GoodSuite.h", compile=self.w32Flags+' -DUNICODE') def test_x11_gui(self): """X11 GUI""" self.check_if_supported('wchar.cpp', "Cannot compile wchar.cpp") self.compile(prefix='x11_gui', args="--gui=X11Gui GoodSuite.h", compile=self.x11Flags) # # Tests for when the compiler doesn't support exceptions # def test_no_exceptions(self): """No exceptions""" if self.no_eh_option is None: self.skipTest("This compiler does not have an exception handling option") self.compile(prefix='no_exceptions', args='--runner=StdioPrinter NoEh.h', output="no_eh.out", compile=self.no_eh_option) def test_force_no_eh(self): """Force no EH""" if self.no_eh_option is None: self.skipTest("This compiler does not have an exception handling option") self.compile(prefix="force_no_eh", args="--runner=StdioPrinter --no-eh ForceNoEh.h", output="no_eh.out", compile=self.no_eh_option) # # Invalid input to cxxtestgen # def test_no_tests(self): """No tests""" self.compile(prefix='no_tests', args='EmptySuite.h', failGen=True) def test_missing_input(self): """Missing input""" self.compile(prefix='missing_input', args='--template=NoSuchFile.h', failGen=True) def test_missing_template(self): """Missing template""" self.compile(prefix='missing_template', args='--template=NoSuchFile.h '+samples, failGen=True) def test_inheritance(self): """Test relying on inheritance""" self.compile(prefix='inheritance', args='--error-printer InheritedTest.h', output='inheritance_old.out') # # Tests that illustrate differences between the different C++ parsers # def test_namespace1(self): """Nested namespace declarations""" if self.fog == '': self.compile(prefix='namespace1', args='Namespace1.h', main=True, failBuild=True) else: self.compile(prefix='namespace1', args='Namespace1.h', main=True, output="namespace.out") def test_namespace2(self): """Explicit namespace declarations""" self.compile(prefix='namespace2', args='Namespace2.h', main=True, output="namespace.out") def test_inheritance(self): """Test relying on inheritance""" if self.fog == '': self.compile(prefix='inheritance', args='--error-printer InheritedTest.h', failGen=True) else: self.compile(prefix='inheritance', args='--error-printer InheritedTest.h', output='inheritance.out') def test_simple_inheritance(self): """Test relying on simple inheritance""" self.compile(prefix='simple_inheritance', args='--error-printer SimpleInheritedTest.h', output='simple_inheritance.out') def test_simple_inheritance2(self): """Test relying on simple inheritance (2)""" if self.fog == '': self.compile(prefix='simple_inheritance2', args='--error-printer SimpleInheritedTest2.h', failGen=True) else: self.compile(prefix='simple_inheritance2', args='--error-printer SimpleInheritedTest2.h', output='simple_inheritance2.out') def test_comments2(self): """Comments2""" if self.fog == '': self.compile(prefix='comments2', args="--error-printer Comments2.h", failBuild=True) else: self.compile(prefix='comments2', args="--error-printer Comments2.h", output='comments2.out') def test_cpp_template1(self): """C++ Templates""" if self.fog == '': self.compile(prefix='cpp_template1', args="--error-printer CppTemplateTest.h", failGen=True) else: self.compile(prefix='cpp_template1', args="--error-printer CppTemplateTest.h", output='template.out') def test_bad1(self): """BadTest1""" if self.fog == '': self.compile(prefix='bad1', args="--error-printer BadTest.h", failGen=True) else: self.compile(prefix='bad1', args="--error-printer BadTest.h", output='bad.out') # # Testing path manipulation # def test_normal_sympath(self): """Normal Behavior - symbolic path""" _files = " ".join(["LessThanEquals.h","Relation.h","DefaultTraits.h","DoubleCall.h","SameData.h","SameFiles.h","Tsm.h","TraitsTest.h","MockTest.h","SameZero.h"]) prefix = 'normal_sympath' self.init(prefix=prefix) try: os.remove('test_sympath') except: pass try: shutil.rmtree('../test_sympath') except: pass os.mkdir('../test_sympath') os.symlink('../test_sympath', 'test_sympath') self.py_cpp = 'test_sympath/'+prefix+'_py.cpp' self.compile(prefix=prefix, init=False, args="--error-printer "+_files, output="normal.out") os.remove('test_sympath') shutil.rmtree('../test_sympath') def test_normal_relpath(self): """Normal Behavior - relative path""" _files = " ".join(["LessThanEquals.h","Relation.h","DefaultTraits.h","DoubleCall.h","SameData.h","SameFiles.h","Tsm.h","TraitsTest.h","MockTest.h","SameZero.h"]) prefix = 'normal_relative' self.init(prefix=prefix) try: shutil.rmtree('../test_relpath') except: pass os.mkdir('../test_relpath') self.py_cpp = '../test_relpath/'+prefix+'_py.cpp' self.compile(prefix=prefix, init=False, args="--error-printer "+_files, output="normal.out") shutil.rmtree('../test_relpath') class TestCpp(BaseTestCase, unittest.TestCase): # Compiler specifics exe_option = '-o' include_option = '-I' compiler='c++ -Wall -W -Werror -g' no_eh_option = None qtFlags='-Ifake' x11Flags='-Ifake' w32Flags='-Ifake' def run(self, *args, **kwds): if available('c++', '-o'): return unittest.TestCase.run(self, *args, **kwds) def setUp(self): BaseTestCase.setUp(self) def tearDown(self): BaseTestCase.tearDown(self) class TestCppFOG(TestCpp): fog='-f' def run(self, *args, **kwds): if ply_available: return TestCpp.run(self, *args, **kwds) class TestGpp(BaseTestCase, unittest.TestCase): # Compiler specifics exe_option = '-o' include_option = '-I' compiler='g++ -g -ansi -pedantic -Wmissing-declarations -Werror -Wall -W -Wshadow -Woverloaded-virtual -Wnon-virtual-dtor -Wreorder -Wsign-promo %s' % os.environ.get('CXXTEST_GCOV_FLAGS','') no_eh_option = '-fno-exceptions' qtFlags='-Ifake' x11Flags='-Ifake' w32Flags='-Ifake' def run(self, *args, **kwds): if available('g++', '-o'): return unittest.TestCase.run(self, *args, **kwds) def setUp(self): BaseTestCase.setUp(self) def tearDown(self): BaseTestCase.tearDown(self) class TestGppPy(TestGpp): def run(self, *args, **kwds): if cxxtest_available: self.cxxtest_import = True status = TestGpp.run(self, *args, **kwds) self.cxxtest_import = False return status class TestGppFOG(TestGpp): fog='-f' def run(self, *args, **kwds): if ply_available: return TestGpp.run(self, *args, **kwds) class TestGppFOGPy(TestGppFOG): def run(self, *args, **kwds): if cxxtest_available: self.cxxtest_import = True status = TestGppFOG.run(self, *args, **kwds) self.cxxtest_import = False return status class TestGppValgrind(TestGpp): valgrind='valgrind --tool=memcheck --leak-check=yes' def file_filter(self, file): for line in file: if line.startswith('=='): continue # Some *very* old versions of valgrind produce lines like: # free: in use at exit: 0 bytes in 0 blocks. # free: 2 allocs, 2 frees, 360 bytes allocated. if line.startswith('free: '): continue yield normalize_line_for_diff(line) def run(self, *args, **kwds): if find('valgrind') is None: return return TestGpp.run(self, *args, **kwds) def parse_valgrind(self, fname): # There is a well-known leak on Mac OSX platforms... if sys.platform == 'darwin': min_leak = 16 else: min_leak = 0 # INPUT = open(fname, 'r') for line in INPUT: if not line.startswith('=='): continue tokens = re.split('[ \t]+', line) if len(tokens) < 4: continue if tokens[1] == 'definitely' and tokens[2] == 'lost:': if eval(tokens[3]) > min_leak: self.fail("Valgrind Error: "+ ' '.join(tokens[1:])) if tokens[1] == 'possibly' and tokens[2] == 'lost:': if eval(tokens[3]) > min_leak: self.fail("Valgrind Error: "+ ' '.join(tokens[1:])) class TestGppFOGValgrind(TestGppValgrind): fog='-f' def run(self, *args, **kwds): if ply_available: return TestGppValgrind.run(self, *args, **kwds) class TestClang(BaseTestCase, unittest.TestCase): # Compiler specifics exe_option = '-o' include_option = '-I' compiler='clang++ -v -g -Wall -W -Wshadow -Woverloaded-virtual -Wnon-virtual-dtor -Wreorder -Wsign-promo' no_eh_option = '-fno-exceptions' qtFlags='-Ifake' x11Flags='-Ifake' w32Flags='-Ifake' def run(self, *args, **kwds): if available('clang++', '-o'): return unittest.TestCase.run(self, *args, **kwds) def setUp(self): BaseTestCase.setUp(self) def tearDown(self): BaseTestCase.tearDown(self) class TestClangFOG(TestClang): fog='-f' def run(self, *args, **kwds): if ply_available: return TestClang.run(self, *args, **kwds) class TestCL(BaseTestCase, unittest.TestCase): # Compiler specifics exe_option = '-o' include_option = '-I' compiler='cl -nologo -GX -W4'# -WX' no_eh_option = '-GX-' qtFlags='-Ifake' x11Flags='-Ifake' w32Flags='-Ifake' def run(self, *args, **kwds): if available('cl', '-o'): return unittest.TestCase.run(self, *args, **kwds) def setUp(self): BaseTestCase.setUp(self) def tearDown(self): BaseTestCase.tearDown(self) class TestCLFOG(TestCL): fog='-f' def run(self, *args, **kwds): if ply_available: return TestCL.run(self, *args, **kwds) if __name__ == '__main__': unittest.main()
bsd-3-clause
lancezlin/ml_template_py
lib/python2.7/site-packages/terminado/management.py
7
11358
"""Terminal management for exposing terminals to a web interface using Tornado. """ from __future__ import absolute_import, print_function import sys if sys.version_info[0] < 3: byte_code = ord else: byte_code = lambda x: x unicode = str from collections import deque import itertools import logging import os import signal from ptyprocess import PtyProcessUnicode from tornado import gen from tornado.ioloop import IOLoop ENV_PREFIX = "PYXTERM_" # Environment variable prefix DEFAULT_TERM_TYPE = "xterm" class PtyWithClients(object): def __init__(self, ptyproc): self.ptyproc = ptyproc self.clients = [] # Store the last few things read, so when a new client connects, # it can show e.g. the most recent prompt, rather than absolutely # nothing. self.read_buffer = deque([], maxlen=10) def resize_to_smallest(self): """Set the terminal size to that of the smallest client dimensions. A terminal not using the full space available is much nicer than a terminal trying to use more than the available space, so we keep it sized to the smallest client. """ minrows = mincols = 10001 for client in self.clients: rows, cols = client.size if rows is not None and rows < minrows: minrows = rows if cols is not None and cols < mincols: mincols = cols if minrows == 10001 or mincols == 10001: return rows, cols = self.ptyproc.getwinsize() if (rows, cols) != (minrows, mincols): self.ptyproc.setwinsize(minrows, mincols) def kill(self, sig=signal.SIGTERM): self.ptyproc.kill(sig) @gen.coroutine def terminate(self, force=False): '''This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. ''' loop = IOLoop.current() sleep = lambda : gen.Task(loop.add_timeout, loop.time() + self.ptyproc.delayafterterminate) if not self.ptyproc.isalive(): raise gen.Return(True) try: self.kill(signal.SIGHUP) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) self.kill(signal.SIGCONT) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) self.kill(signal.SIGINT) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) self.kill(signal.SIGTERM) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) if force: self.kill(signal.SIGKILL) yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) else: raise gen.Return(False) raise gen.Return(False) except OSError: # I think there are kernel timing issues that sometimes cause # this to happen. I think isalive() reports True, but the # process is dead to the kernel. # Make one last attempt to see if the kernel is up to date. yield sleep() if not self.ptyproc.isalive(): raise gen.Return(True) else: raise gen.Return(False) def _update_removing(target, changes): """Like dict.update(), but remove keys where the value is None. """ for k, v in changes.items(): if v is None: target.pop(k, None) else: target[k] = v class TermManagerBase(object): """Base class for a terminal manager.""" def __init__(self, shell_command, server_url="", term_settings={}, extra_env=None, ioloop=None): self.shell_command = shell_command self.server_url = server_url self.term_settings = term_settings self.extra_env = extra_env self.log = logging.getLogger(__name__) self.ptys_by_fd = {} if ioloop is not None: self.ioloop = ioloop else: import tornado.ioloop self.ioloop = tornado.ioloop.IOLoop.instance() def make_term_env(self, height=25, width=80, winheight=0, winwidth=0, **kwargs): """Build the environment variables for the process in the terminal.""" env = os.environ.copy() env["TERM"] = self.term_settings.get("type",DEFAULT_TERM_TYPE) dimensions = "%dx%d" % (width, height) if winwidth and winheight: dimensions += ";%dx%d" % (winwidth, winheight) env[ENV_PREFIX+"DIMENSIONS"] = dimensions env["COLUMNS"] = str(width) env["LINES"] = str(height) if self.server_url: env[ENV_PREFIX+"URL"] = self.server_url if self.extra_env: _update_removing(env, self.extra_env) return env def new_terminal(self, **kwargs): """Make a new terminal, return a :class:`PtyWithClients` instance.""" options = self.term_settings.copy() options['shell_command'] = self.shell_command options.update(kwargs) argv = options['shell_command'] env = self.make_term_env(**options) pty = PtyProcessUnicode.spawn(argv, env=env, cwd=options.get('cwd', None)) return PtyWithClients(pty) def start_reading(self, ptywclients): """Connect a terminal to the tornado event loop to read data from it.""" fd = ptywclients.ptyproc.fd self.ptys_by_fd[fd] = ptywclients self.ioloop.add_handler(fd, self.pty_read, self.ioloop.READ) def on_eof(self, ptywclients): """Called when the pty has closed. """ # Stop trying to read from that terminal fd = ptywclients.ptyproc.fd self.log.info("EOF on FD %d; stopping reading", fd) del self.ptys_by_fd[fd] self.ioloop.remove_handler(fd) # This closes the fd, and should result in the process being reaped. ptywclients.ptyproc.close() def pty_read(self, fd, events=None): """Called by the event loop when there is pty data ready to read.""" ptywclients = self.ptys_by_fd[fd] try: s = ptywclients.ptyproc.read(65536) ptywclients.read_buffer.append(s) for client in ptywclients.clients: client.on_pty_read(s) except EOFError: self.on_eof(ptywclients) for client in ptywclients.clients: client.on_pty_died() def get_terminal(self, url_component=None): """Override in a subclass to give a terminal to a new websocket connection The :class:`TermSocket` handler works with zero or one URL components (capturing groups in the URL spec regex). If it receives one, it is passed as the ``url_component`` parameter; otherwise, this is None. """ raise NotImplementedError def client_disconnected(self, websocket): """Override this to e.g. kill terminals on client disconnection. """ pass @gen.coroutine def shutdown(self): yield self.kill_all() @gen.coroutine def kill_all(self): futures = [] for term in self.ptys_by_fd.values(): futures.append(term.terminate(force=True)) # wait for futures to finish for f in futures: yield f class SingleTermManager(TermManagerBase): """All connections to the websocket share a common terminal.""" def __init__(self, **kwargs): super(SingleTermManager, self).__init__(**kwargs) self.terminal = None def get_terminal(self, url_component=None): if self.terminal is None: self.terminal = self.new_terminal() self.start_reading(self.terminal) return self.terminal @gen.coroutine def kill_all(self): yield super(SingleTermManager, self).kill_all() self.terminal = None class MaxTerminalsReached(Exception): def __init__(self, max_terminals): self.max_terminals = max_terminals def __str__(self): return "Cannot create more than %d terminals" % self.max_terminals class UniqueTermManager(TermManagerBase): """Give each websocket a unique terminal to use.""" def __init__(self, max_terminals=None, **kwargs): super(UniqueTermManager, self).__init__(**kwargs) self.max_terminals = max_terminals def get_terminal(self, url_component=None): if self.max_terminals and len(self.ptys_by_fd) >= self.max_terminals: raise MaxTerminalsReached(self.max_terminals) term = self.new_terminal() self.start_reading(term) return term def client_disconnected(self, websocket): """Send terminal SIGHUP when client disconnects.""" self.log.info("Websocket closed, sending SIGHUP to terminal.") if websocket.terminal: websocket.terminal.kill(signal.SIGHUP) class NamedTermManager(TermManagerBase): """Share terminals between websockets connected to the same endpoint. """ def __init__(self, max_terminals=None, **kwargs): super(NamedTermManager, self).__init__(**kwargs) self.max_terminals = max_terminals self.terminals = {} def get_terminal(self, term_name): assert term_name is not None if term_name in self.terminals: return self.terminals[term_name] if self.max_terminals and len(self.terminals) >= self.max_terminals: raise MaxTerminalsReached(self.max_terminals) # Create new terminal self.log.info("New terminal with specified name: %s", term_name) term = self.new_terminal() term.term_name = term_name self.terminals[term_name] = term self.start_reading(term) return term name_template = "%d" def _next_available_name(self): for n in itertools.count(start=1): name = self.name_template % n if name not in self.terminals: return name def new_named_terminal(self): name = self._next_available_name() term = self.new_terminal() self.log.info("New terminal with automatic name: %s", name) term.term_name = name self.terminals[name] = term self.start_reading(term) return name, term def kill(self, name, sig=signal.SIGTERM): term = self.terminals[name] term.kill() # This should lead to an EOF @gen.coroutine def terminate(self, name, force=False): term = self.terminals[name] yield term.terminate(force=force) def on_eof(self, ptywclients): super(NamedTermManager, self).on_eof(ptywclients) name = ptywclients.term_name self.log.info("Terminal %s closed", name) self.terminals.pop(name, None) @gen.coroutine def kill_all(self): yield super(NamedTermManager, self).kill_all() self.terminals = {}
mit
kevinxw/namebench
tools/convert_servers_to_csv.py
174
3169
#!/usr/bin/env python # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tool to convert listing to CSV format.""" __author__ = 'tstromberg@google.com (Thomas Stromberg)' import csv import re import sys import check_nameserver_popularity import GeoIP sys.path.append('..') #sys.path.append('/Users/tstromberg/namebench') import third_party from libnamebench import addr_util from libnamebench import nameserver_list from libnamebench import config output = csv.writer(open('output.csv', 'w')) #output.writerow(['IP', 'Name', 'Hostname', 'Country/Region/City', 'Coords', 'ASN', 'Label', 'Status', 'Refs']) gi = GeoIP.open('/usr/local/share/GeoLiteCity.dat', GeoIP.GEOIP_MEMORY_CACHE) asn_lookup = GeoIP.open('/usr/local/share/GeoIPASNum.dat', GeoIP.GEOIP_MEMORY_CACHE) ns_hash = config.GetLocalNameServerList() for ip in ns_hash: try: details = gi.record_by_addr(ip) except SystemError: pass if not details: details = {} city = details.get('city', '') if city: city = city.decode('latin-1') country = details.get('country_name', '') if country: country = country.decode('latin-1') latitude = details.get('latitude', '') longitude = details.get('longitude', '') country_code = details.get('country_code', '') region = details.get('region_name', '') if region: region = region.decode('latin-1') hostname = ns_hash[ip].get('hostname', '') geo = '/'.join([x for x in [country_code, region, city] if x and not x.isdigit()]).encode('utf-8') coords = ','.join(map(str, [latitude,longitude])) status = ns_hash[ip].get('notes', '') refs = None asn = asn_lookup.org_by_addr(ip) labels = ' '.join(list(ns_hash[ip]['labels'])) urls = check_nameserver_popularity.GetUrls(ip) use_keywords = set() if ns_hash[ip]['name'] and 'UNKNOWN' not in ns_hash[ip]['name']: for word in ns_hash[ip]['name'].split(' ')[0].split('/'): use_keywords.add(word.lower()) use_keywords.add(re.sub('[\W_]', '', word.lower())) if '-' in word: use_keywords.add(word.lower().replace('-', '')) if hostname and hostname != ip: use_keywords.add(addr_util.GetDomainPartOfHostname(ip)) for bad_word in ('ns', 'dns'): if bad_word in use_keywords: use_keywords.remove(bad_word) print use_keywords context_urls = [] for url in urls: for keyword in use_keywords: if re.search(keyword, url, re.I): context_urls.append(url) break if context_urls: urls = context_urls row = [ip, labels, ns_hash[ip]['name'], hostname, geo, coords, asn, status[0:30], ' '.join(urls[:2])] print row output.writerow(row)
apache-2.0
dprog-philippe-docourt/django-qr-code
setup.py
1
1589
import re from setuptools import setup # Get version without importing with open('qr_code/__init__.py', 'rb') as f: VERSION = str(re.search('__version__ = \'(.+?)\'', f.read().decode('utf-8')).group(1)) setup( name='django-qr-code', version=VERSION, packages=['qr_code', 'qr_code.qrcode', 'qr_code.templatetags'], url='https://github.com/dprog-philippe-docourt/django-qr-code', license='BSD 3-clause', author='Philippe Docourt', author_email='philippe@docourt.ch', maintainer='Philippe Docourt', description='An application that provides tools for displaying QR codes on your Django site.', long_description="""This application provides tools for displaying QR codes on your `Django <https://www.djangoproject.com/>`_ site. This application depends on the `Segno QR Code generator <https://pypi.org/project/segno/>`_. This app makes no usage of the Django models and therefore do not use any database. Only Python >= 3.6 is supported.""", install_requires=['segno', 'django>=2.2'], python_requires='>=3', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet :: WWW/HTTP', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3 :: Only', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.0', 'Framework :: Django :: 3.1', 'Natural Language :: English' ], keywords='qr code django', )
bsd-3-clause
Troyhy/django-registration
registration/models.py
20
10561
import datetime import hashlib import random import re from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.db import transaction from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: from django.contrib.auth.models import User try: from django.utils.timezone import now as datetime_now except ImportError: datetime_now = datetime.datetime.now SHA1_RE = re.compile('^[a-f0-9]{40}$') class RegistrationManager(models.Manager): """ Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. """ def activate_user(self, activation_key): """ Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, the activation key is reset to the string constant ``RegistrationProfile.ACTIVATED`` after successful activation. """ # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): try: profile = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not profile.activation_key_expired(): user = profile.user user.is_active = True user.save() profile.activation_key = self.model.ACTIVATED profile.save() return user return False def create_inactive_user(self, username, email, password, site, send_email=True): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. """ new_user = User.objects.create_user(username, email, password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) if send_email: registration_profile.send_activation_email(site) return new_user create_inactive_user = transaction.commit_on_success(create_inactive_user) def create_profile(self, user): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ salt = hashlib.sha1(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') activation_key = hashlib.sha1(salt+username).hexdigest() return self.create(user=user, activation_key=activation_key) def delete_expired_users(self): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for profile in self.all(): try: if profile.activation_key_expired(): user = profile.user if not user.is_active: user.delete() profile.delete() except User.DoesNotExist: profile.delete() class RegistrationProfile(models.Model): """ A simple profile which stores an activation key for use during user account registration. Generally, you will not want to interact directly with instances of this model; the provided manager includes methods for creating and activating new accounts, as well as for cleaning out accounts which have never been activated. While it is possible to use this model as the value of the ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do so. This model's sole purpose is to store data temporarily during account registration and activation. """ ACTIVATED = u"ALREADY_ACTIVATED" user = models.ForeignKey(User, unique=True, verbose_name=_('user')) activation_key = models.CharField(_('activation key'), max_length=40) objects = RegistrationManager() class Meta: verbose_name = _('registration profile') verbose_name_plural = _('registration profiles') def __unicode__(self): return u"Registration information for %s" % self.user def activation_key_expired(self): """ Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, the key will have been reset to the string constant ``ACTIVATED``. Re-activating is not permitted, and so this method returns ``True`` in this case. 2. Otherwise, the date the user signed up is incremented by the number of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of days after signup during which a user is allowed to activate their account); if the result is less than or equal to the current date, the key has expired and this method returns ``True``. """ expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) return self.activation_key == self.ACTIVATED or \ (self.user.date_joined + expiration_date <= datetime_now()) activation_key_expired.boolean = True def send_activation_email(self, site): """ Send an activation email to the user associated with this ``RegistrationProfile``. The activation email will make use of two templates: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the body of the email. These templates will each receive the following context variables: ``activation_key`` The activation key for the new account. ``expiration_days`` The number of days remaining during which the account may be activated. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.models.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. """ ctx_dict = {'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site} subject = render_to_string('registration/activation_email_subject.txt', ctx_dict) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('registration/activation_email.txt', ctx_dict) self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
bsd-3-clause
adazey/Muzez
libs/youtube_dl/extractor/trutv.py
52
2002
# coding: utf-8 from __future__ import unicode_literals import re from .turner import TurnerBaseIE class TruTVIE(TurnerBaseIE): _VALID_URL = r'https?://(?:www\.)?trutv\.com(?:(?P<path>/shows/[^/]+/videos/[^/?#]+?)\.html|/full-episodes/[^/]+/(?P<id>\d+))' _TEST = { 'url': 'http://www.trutv.com/shows/10-things/videos/you-wont-believe-these-sports-bets.html', 'md5': '2cdc844f317579fed1a7251b087ff417', 'info_dict': { 'id': '/shows/10-things/videos/you-wont-believe-these-sports-bets', 'ext': 'mp4', 'title': 'You Won\'t Believe These Sports Bets', 'description': 'Jamie Lee sits down with a bookie to discuss the bizarre world of illegal sports betting.', 'upload_date': '20130305', } } def _real_extract(self, url): path, video_id = re.match(self._VALID_URL, url).groups() auth_required = False if path: data_src = 'http://www.trutv.com/video/cvp/v2/xml/content.xml?id=%s.xml' % path else: webpage = self._download_webpage(url, video_id) video_id = self._search_regex( r"TTV\.TVE\.episodeId\s*=\s*'([^']+)';", webpage, 'video id', default=video_id) auth_required = self._search_regex( r'TTV\.TVE\.authRequired\s*=\s*(true|false);', webpage, 'auth required', default='false') == 'true' data_src = 'http://www.trutv.com/tveverywhere/services/cvpXML.do?titleId=' + video_id return self._extract_cvp_info( data_src, path, { 'secure': { 'media_src': 'http://androidhls-secure.cdn.turner.com/trutv/big', 'tokenizer_src': 'http://www.trutv.com/tveverywhere/processors/services/token_ipadAdobe.do', }, }, { 'url': url, 'site_name': 'truTV', 'auth_required': auth_required, })
gpl-3.0
team-vigir/vigir_behavior_synthesis
vigir_ltl_synthesizer/src/vigir_ltl_synthesizer/StructuredSlugsParser/compiler.py
3
29068
#!/usr/bin/python # # Translates a structured specification into an unstructured one that is suitable to be read by the slugs synthesis tool import math import os import sys import resource import subprocess import signal from Parser import Parser from re import match import StringIO # ===================================================== # Allocate global parser and parser context variables: # - which APs there are # - how the numbers are encoded # ===================================================== p = Parser() booleanAPs = [] numberAPs = [] numberAPLimits = {} numberAPNofBits = {} translatedNames = {} # ===================================================== # Lexer for the LTL formulas # ===================================================== def tokenize(str): res = [] while str: # Ignoring stuff if str[0].isspace() or (str[0]=='\n'): str = str[1:] continue # Match words m = match('[a-zA-Z_.\'@]+[a-zA-Z0-9_.\'@]*', str) if m: currentSymbol = m.group(0) if (currentSymbol in ["X","F","G","U","W","FALSE","TRUE","next","LEASTSIGNIFICANTBITOVERWRITES"]): res.append((currentSymbol,)) else: currentSymbol = m.group(0) if currentSymbol in booleanAPs: res.append(('boolID', m.group(0))) else: res.append(('numID', m.group(0))) str = str[m.end(0):] continue # Match numbers m = match('[0-9]+', str) if m: res.append(('numeral', m.group(0))) str = str[m.end(0):] continue # Single-literal element res.append((str[0],)) str = str[1:] return res # ===================================================== # Simplify the specifications # ===================================================== def clean_tree(tree): """ Cleans a parse Tree, i.e. removes brackets and so on """ if tree[0] in p.terminals: return tree if (tree[0]=="Brackets"): return clean_tree(tree[2]) elif (tree[0]=="Implication") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="Atomic") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="Conjunction") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="Biimplication") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="Disjunction") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="Xor") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="LeastSignificantBitOverwriteExpression") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="BinaryTemporalFormula") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="BooleanAtomicFormula") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="BooleanAtomicFormula") and (len(tree)!=2): raise Exception("BooleanAtomic formula must have only one successor") elif (tree[0]=="UnaryFormula") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="MultiplicativeNumber") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="NumberExpression") and (len(tree)==2): return clean_tree(tree[1]) elif (tree[0]=="AtomicNumberExpression"): if len(tree)!=2: raise ValueError("AtomicNumberExpression must have length 2") return clean_tree(tree[1]) elif (tree[0]=="AtomicFormula"): if len(tree)!=2: raise ValueError("AtomicFormula must have length 2") return clean_tree(tree[1]) elif (tree[0]=="Implication"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[3])] elif (tree[0]=="Conjunction"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[3])] elif (tree[0]=="Biimplication"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[3])] elif (tree[0]=="Disjunction"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[3])] elif (tree[0]=="Xor"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[3])] elif (tree[0]=="BinaryTemporalFormula"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[2]),clean_tree(tree[3])] elif (tree[0]=="UnaryFormula"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[2])] elif (tree[0]=="MultiplicativeNumber"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[2]),clean_tree(tree[3])] elif (tree[0]=="NumberExpression"): return [tree[0],clean_tree(tree[1]),clean_tree(tree[2]),clean_tree(tree[3])] elif (tree[0]=="BinaryTemporalOperator"): # Remove the "superfluous indirection" return clean_tree(tree[1]) elif (tree[0]=="UnaryTemporalOperator"): # Remove the "superfluous indirection" return clean_tree(tree[1]) elif (tree[0]=="Assignment"): # Flatten "id" case A = [tree[0],tree[1][1]] A.extend(tree[2:]) return A else: A = [tree[0]] for x in tree[1:]: A.append(clean_tree(x)) return A def flatten_as_much_as_possible(tree): """ Flattens nested disjunctions/conjunctions """ # Ground case? if len(tree)==1: return tree if (type(tree)==type("A")) or (type(tree)==type(u"A")): # TODO: How to do this in the way intended? return tree newTree = [] for a in tree: newTree.append(flatten_as_much_as_possible(a)) tree = newTree # Conjunction if (tree[0]=="Conjunction"): parts = [tree[0]] for a in tree[1:]: if a[0]=="Conjunction": parts.extend(a[1:]) else: parts.append(a) return parts # Disjunction if (tree[0]=="Disjunction"): parts = [tree[0]] for a in tree[1:]: if a[0]=="Disjunction": parts.extend(a[1:]) else: parts.append(a) return parts # Xor if (tree[0]=="Xor"): parts = [tree[0]] for a in tree[1:]: if a[0]=="Xor": parts.extend(a[1:]) else: parts.append(a) return parts # Every other case return tree # ===================================================== # Print Tree function # ===================================================== def printTree(tree,depth=0): if isinstance(tree,str): print >>sys.stderr," "*depth+tree else: print >>sys.stderr," "*depth+tree[0] for a in tree[1:]: printTree(a,depth+2) # ===================================================== # The Parsing function # ===================================================== def parseLTL(ltlTxt,reasonForNotBeingASlugsFormula): try: input = tokenize(ltlTxt) # print >>sys.stderr, input tree = p.parse(input) except p.ParseErrors, exception: for t,e in exception.errors: if t[0] == p.EOF: print >>sys.stderr, "Formula end not expected here" continue found = repr(t[0]) print >>sys.stderr, "Error in the property line: "+ltlTxt print >>sys.stderr, "... which could not have been a slugs Polish notation line because of: "+ reasonForNotBeingASlugsFormula print >>sys.stderr, "Could not parse %s, "%found print >>sys.stderr, "Wanted a token of one of the following forms: "+", ".join([ repr(s) for s in e ]) raise # Convert to a tree cleaned_tree = flatten_as_much_as_possible(clean_tree(tree)) return cleaned_tree # ===================================================== # Slugs functions for working with numbers # This function computes a "memory structure" for the # slugs input whose final value is the result of the comparison # ===================================================== #------------------------------------------ # Computation Recursion function # Assumes that every variable starts from 0 #------------------------------------------ def recurseCalculationSubformula(tree,memoryStructureParts, isPrimed): if (tree[0]=="NumberExpression"): assert len(tree)==4 # Everything else would have been filtered out already part1MemoryStructurePointers = recurseCalculationSubformula(tree[1],memoryStructureParts, isPrimed) part2MemoryStructurePointers = recurseCalculationSubformula(tree[3],memoryStructureParts, isPrimed) # Addition? if tree[2][0]=="AdditionOperator": if len(part1MemoryStructurePointers)==0: return part2MemoryStructurePointers if len(part2MemoryStructurePointers)==0: return part1MemoryStructurePointers # Order the result by the number of bits if len(part2MemoryStructurePointers)<len(part1MemoryStructurePointers): part1MemoryStructurePointers, part2MemoryStructurePointers = part2MemoryStructurePointers, part1MemoryStructurePointers startingPosition = len(memoryStructureParts) memoryStructureParts.append(["^",part1MemoryStructurePointers[0],part2MemoryStructurePointers[0]]) memoryStructureParts.append(["&",part1MemoryStructurePointers[0],part2MemoryStructurePointers[0]]) # First part: Joint part of the word for i in xrange(1,len(part1MemoryStructurePointers)): memoryStructureParts.append(["^ ^",part1MemoryStructurePointers[i],part2MemoryStructurePointers[i],"?",str(len(memoryStructureParts)-1)]) memoryStructureParts.append(["| | &",part1MemoryStructurePointers[i],part2MemoryStructurePointers[i],"& ?",str(len(memoryStructureParts)-2),part1MemoryStructurePointers[i],"& ?",str(len(memoryStructureParts)-2),part2MemoryStructurePointers[i]]) # Second part: Part of the word where j1 is shorter than j2 for i in xrange(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers)): memoryStructureParts.append(["^",part2MemoryStructurePointers[i],"?",str(len(memoryStructureParts)-1)]) memoryStructureParts.append(["&",part2MemoryStructurePointers[i],"?",str(len(memoryStructureParts)-2)]) # Return new value including the final bit return ["? "+str(i*2+startingPosition) for i in xrange(0,len(part2MemoryStructurePointers))]+["? "+str(len(memoryStructureParts)-1)] # Subtraction? elif tree[2][0]=="SubtractionOperator": raise Exception("Subtraction is currently unsupported due to semantic difficulties") else: raise Exception("Found unsupported NumberExpression operator:"+tree[2][0]) # Parse Numeral elif (tree[0]=="numeral"): parameter = int(tree[1]) result = [] while parameter != 0: if (parameter % 2)==1: result.append("1") else: result.append("0") parameter = parameter / 2 return result # Work on NumID elif (tree[0]=="numID"): apName = tree[1] primedLocally = apName[len(apName)-1]=="'" if primedLocally and isPrimed: raise Exception("Variable is used primed in the scope of a next-operator, which is not supported: "+apName) if primedLocally: apName = apName[0:len(apName)-1] if (not primedLocally) and (not isPrimed): return translatedNames[apName] else: return [a+"'" for a in translatedNames[apName]] elif (tree[0]=="NumberBrackets"): print >>sys.stderr,tree assert tree[1]==('(',) assert tree[3]==(')',) return recurseCalculationSubformula(tree[2],memoryStructureParts, isPrimed) # Overwrite the least significant bits of some expression elif tree[0]=="LeastSignificantBitOverwriteExpression": part1MemoryStructurePointers = recurseCalculationSubformula(tree[1],memoryStructureParts, isPrimed) part2MemoryStructurePointers = recurseCalculationSubformula(tree[3],memoryStructureParts, isPrimed) assert len(part1MemoryStructurePointers)<len(part2MemoryStructurePointers) return part1MemoryStructurePointers+part2MemoryStructurePointers[len(part1MemoryStructurePointers):] else: raise Exception("Found currently unsupported calculator subformula type:"+tree[0]) #----------------------------------------------- # Special function that implicitly adds the lower # bounds to all variable occurrences. In this # way, it does not have to be considered in the # actual translation algorithm. #----------------------------------------------- def addMinimumValueToAllVariables(tree): if tree[0]=="numID": apName = tree[1] primed = apName[len(apName)-1]=="'" if primed: apName = apName[0:len(apName)-1] (minimum,maximum) = numberAPLimits[apName] if minimum==0: return tree else: return ("NumberExpression",tree,("AdditionOperator",),("numeral",str(minimum))) elif tree[0] in p.terminals: return tree else: return tuple([tree[0]] + [addMinimumValueToAllVariables(a) for a in tree[1:]]) #----------------------------------------------- # Main Function. Takes the formula tree and adds #----------------------------------------------- def computeCalculationSubformula(tree, isPrimed): memoryStructureParts = [] part1MemoryStructurePointers = recurseCalculationSubformula(addMinimumValueToAllVariables(tree[1]),memoryStructureParts, isPrimed) part2MemoryStructurePointers = recurseCalculationSubformula(addMinimumValueToAllVariables(tree[3]),memoryStructureParts, isPrimed) print >>sys.stderr,"P1: "+str(part1MemoryStructurePointers) print >>sys.stderr,"P2: "+str(part2MemoryStructurePointers) print >>sys.stderr,"MSPatComp: "+str(memoryStructureParts) # Pick the correct comparison operator # -> Greater or Greater-Equal if (tree[2][1][0]=="GreaterOperator") or (tree[2][1][0]=="GreaterEqualOperator"): thisParts = ["0"] if tree[2][1][0]=="GreaterOperator" else ["1"] for i in xrange(0,min(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers))): thisParts = ["|","&",part1MemoryStructurePointers[i],"!",part2MemoryStructurePointers[i],"& | !",part2MemoryStructurePointers[i],part1MemoryStructurePointers[i]]+thisParts for i in xrange(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers)): thisParts = ["& !",part2MemoryStructurePointers[i]]+thisParts for i in xrange(len(part2MemoryStructurePointers),len(part1MemoryStructurePointers)): thisParts = ["|",part1MemoryStructurePointers[i]]+thisParts memoryStructureParts.append(thisParts) # -> Smaller or Smaller-Equal elif (tree[2][1][0]=="SmallerOperator") or (tree[2][1][0]=="SmallerEqualOperator"): thisParts = ["0"] if tree[2][1][0]=="SmallerOperator" else ["1"] for i in xrange(0,min(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers))): thisParts = ["|","& !",part1MemoryStructurePointers[i],part2MemoryStructurePointers[i],"& |",part2MemoryStructurePointers[i],"!",part1MemoryStructurePointers[i]]+thisParts for i in xrange(len(part2MemoryStructurePointers),len(part1MemoryStructurePointers)): thisParts = ["& !",part1MemoryStructurePointers[i]]+thisParts for i in xrange(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers)): thisParts = ["|",part2MemoryStructurePointers[i]]+thisParts memoryStructureParts.append(thisParts) # -> Equal Operator or Unequal Operator elif (tree[2][1][0]=="EqualOperator") or (tree[2][1][0]=="UnequalOperator"): thisParts = ["1"] for i in xrange(0,min(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers))): thisParts = ["&","! ^",part1MemoryStructurePointers[i],part2MemoryStructurePointers[i]]+thisParts for i in xrange(len(part2MemoryStructurePointers),len(part1MemoryStructurePointers)): thisParts = ["& !",part1MemoryStructurePointers[i]]+thisParts for i in xrange(len(part1MemoryStructurePointers),len(part2MemoryStructurePointers)): thisParts = ["& !",part2MemoryStructurePointers[i]]+thisParts if (tree[2][1][0]=="UnequalOperator"): memoryStructureParts.append(["!"]+thisParts) else: memoryStructureParts.append(thisParts) else: raise Exception("Found unsupported Number Comparison operator:"+tree[2][1][0]) # Return memory structure return ["$",str(len(memoryStructureParts))] + [b for a in memoryStructureParts for b in a] # ============================================ # Build Slugs file - Temporal logic properties # ============================================ def parseSimpleFormula(tree, isPrimed): if (tree[0]=="Formula"): assert len(tree)==2 return parseSimpleFormula(tree[1],isPrimed) if (tree[0]=="Biimplication"): b1 = parseSimpleFormula(tree[1],isPrimed) b2 = parseSimpleFormula(tree[2],isPrimed) return ["|","&","!"]+b1+["!"]+b2+["&"]+b1+b2 if (tree[0]=="Implication"): b1 = parseSimpleFormula(tree[1],isPrimed) b2 = parseSimpleFormula(tree[2],isPrimed) return ["|","!"]+b1+b2 if (tree[0]=="Conjunction"): ret = parseSimpleFormula(tree[1],isPrimed) for a in tree[2:]: ret = ["&"]+ret+parseSimpleFormula(a,isPrimed) return ret if (tree[0]=="Disjunction"): ret = parseSimpleFormula(tree[1],isPrimed) for a in tree[2:]: ret = ["|"]+ret+parseSimpleFormula(a,isPrimed) return ret if (tree[0]=="UnaryFormula"): if tree[1][0]=="NotOperator": return ["!"]+parseSimpleFormula(tree[2],isPrimed) elif tree[1][0]=="NextOperator": if isPrimed: raise "Nested nexts are not allowed." return parseSimpleFormula(tree[2],True) if (tree[0]=="Assignment"): var = tree[1] if isPrimed: if "'" in var: raise Exception("Cannot parse input formula: variable is both primed and in the scope of a next-operator") var = var + "'" return [var] if (tree[0]=="TRUE"): return ["1"] if (tree[0]=="FALSE"): return ["0"] if (tree[0]=="CalculationSubformula"): assert len(tree)==4 return computeCalculationSubformula(tree,isPrimed) print >>sys.stderr, "Cannot parse sub-tree!" print >>sys.stderr, tree raise Exception("Slugs parsing error") def translateToSlugsFormat(tree): tokens = parseSimpleFormula(tree,False) print >>sys.stderr,tokens return " ".join(tokens) # ============================================ # Function to check if an input line is already # in slugs internal form. Checks that there # will be one element on the stack left when # applying the operations from right to left # ============================================ def isValidRecursiveSlugsProperty(tokens): tokens = [a for a in tokens if a!=""] if "$" in tokens: return (True,"Found a '$' in the property.") stacksize = 0 for i in xrange(len(tokens)-1,-1,-1): currentToken = tokens[i] if currentToken=="|" or currentToken=="&" or currentToken=="^": if stacksize<2: return (False,"Rejected part due to stack underflow") stacksize -= 1 elif currentToken=="!": pass elif currentToken=="1" or currentToken=="0": stacksize += 1 else: # Check if valid input or output bit if currentToken[len(currentToken)-1] == "'": currentToken = currentToken[0:len(currentToken)-1] if currentToken in booleanAPs: stacksize += 1 elif currentToken=="0" or currentToken=="1": stacksize += 1 else: return (False,"Rejected part \""+tokens[i]+"\" when reading right-to-left.") return (stacksize==1,"Stack size at end: "+str(stacksize)) # ============================================ # Main worker # ============================================ def performConversion(inputFile,thoroughly): specFile = open(inputFile,"r") mode = "" lines = {"[ENV_TRANS]":[],"[ENV_INIT]":[],"[INPUT]":[],"[OUTPUT]":[],"[SYS_TRANS]":[],"[SYS_INIT]":[],"[ENV_LIVENESS]":[],"[SYS_LIVENESS]":[],"[OBSERVABLE_INPUT]":[],"[UNOBSERVABLE_INPUT]":[],"[CONTROLLABLE_INPUT]":[] } for line in specFile.readlines(): line = line.strip() if line == "": pass elif line.startswith("["): mode = line # if not mode in lines: # lines[mode] = [] else: if mode=="" and line.startswith("#"): # Initial comments pass else: lines[mode].append(line) specFile.close() # --------------------------------------- # Reparse input lines # Create information along the way that # encodes the possible values # --------------------------------------- translatedIOLines = {"[INPUT]":[],"[OUTPUT]":[],"[OBSERVABLE_INPUT]":[],"[UNOBSERVABLE_INPUT]":[],"[CONTROLLABLE_INPUT]":[]} for variableType in ["[INPUT]","[OUTPUT]","[OBSERVABLE_INPUT]","[UNOBSERVABLE_INPUT]","[CONTROLLABLE_INPUT]"]: for line in lines[variableType]: if line.startswith("#"): translatedIOLines[variableType].append(line.strip()) if "'" in line: print >>sys.stderr, "Error with atomic signal name "+line+": the name must not contain any \"'\" characters" raise Exception("Translation error") if "@" in line: print >>sys.stderr, "Error with atomic signal name "+line+": the name must not contain any \"@\" characters" raise Exception("Translation error") if ":" in line: parts = line.split(":") parts = [a.strip() for a in parts] if len(parts)!=2: print >>sys.stderr, "Error reading line '"+line+"' in section "+variableType+": Too many ':'s!" raise Exception("Failed to translate file.") parts2 = parts[1].split("...") if len(parts2)!=2: print >>sys.stderr, "Error reading line '"+line+"' in section "+variableType+": Syntax should be name:from...to, where the latter two are numbers" raise Exception("Failed to translate file.") try: minValue = int(parts2[0]) maxValue = int(parts2[1]) except ValueError: print >>sys.stderr, "Error reading line '"+line+"' in section "+variableType+": the minimal and maximal values are not given as numbers" raise Exception("Failed to translate file.") if minValue>maxValue: print >>sys.stderr, "Error reading line '"+line+"' in section "+variableType+": the minimal value should be smaller than the maximum one (or at least equal)" raise Exception("Failed to translate file.") # Fill the dictionaries numberAPLimits, translatedNames with information variable = parts[0] numberAPs.append(parts[0]) numberAPs.append(parts[0]+"'") numberAPLimits[parts[0]] = (minValue,maxValue) nofBits = 0 while (2**nofBits <= (maxValue-minValue)): nofBits += 1 numberAPNofBits[variable] = nofBits # Translate name into bits in a way such that the first bit carries not only the original name, but also min and max information translatedNames[parts[0]] = [parts[0]+"@"+str(i)+("."+str(minValue)+"."+str(maxValue) if i==0 else "") for i in xrange(0,nofBits)] translatedIOLines[variableType] = translatedIOLines[variableType] + translatedNames[parts[0]] booleanAPs.extend(translatedNames[parts[0]]) # Define limits limitDiff = maxValue - minValue + 1 # +1 because the range is inclusive if (2**numberAPNofBits[variable]) != limitDiff: propertyDestination = "ENV" if variableType.endswith("INPUT]") else "SYS" # Init constraint tokens = ["0"] for i in xrange(0,numberAPNofBits[variable]): if 2**i & limitDiff: tokens = ["| !",translatedNames[variable][i]]+tokens else: tokens = ["& !",translatedNames[variable][i]]+tokens lines["["+propertyDestination+"_INIT]"].append("## Variable limits: "+str(minValue)+"<="+variable+"<="+str(maxValue)) lines["["+propertyDestination+"_INIT]"].append(" ".join(tokens)) # Transition constraint for previous state -- only if using the "--thorougly mode" if thoroughly: lines["["+propertyDestination+"_TRANS]"].append("## Variable limits: "+str(minValue)+"<="+variable+"<="+str(maxValue)) lines["["+propertyDestination+"_TRANS]"].append(" ".join(tokens)) # Trans constraint for next states tokens = ["0"] for i in xrange(0,numberAPNofBits[variable]): if 2**i & limitDiff: tokens = ["| !",translatedNames[variable][i]+"'"]+tokens else: tokens = ["& !",translatedNames[variable][i]+"'"]+tokens lines["["+propertyDestination+"_TRANS]"].append("## Variable limits: "+str(minValue)+"<="+variable+"'<="+str(maxValue)) lines["["+propertyDestination+"_TRANS]"].append(" ".join(tokens)) else: # A "normal" atomic proposition line = line.strip() booleanAPs.append(line) booleanAPs.append(line+"'") translatedIOLines[variableType].append(line) # --------------------------------------- # Output new input/output lines # --------------------------------------- for variableType in ["[INPUT]","[OUTPUT]","[OBSERVABLE_INPUT]","[UNOBSERVABLE_INPUT]","[CONTROLLABLE_INPUT]"]: if len(translatedIOLines[variableType])>0: print variableType for a in translatedIOLines[variableType]: print a print "" # --------------------------------------- # Go through the properties and translate # --------------------------------------- for propertyType in ["[ENV_TRANS]","[ENV_INIT]","[SYS_TRANS]","[SYS_INIT]","[ENV_LIVENESS]","[SYS_LIVENESS]"]: if len(lines[propertyType])>0: print propertyType # Test for conformance with recursive definition for a in lines[propertyType]: print >>sys.stderr, a.strip().split(" ") if a.strip()[0:1] == "#": print a else: (isSlugsFormula,reasonForNotBeingASlugsFormula) = isValidRecursiveSlugsProperty(a.strip().split(" ")) if isSlugsFormula: print a else: print >>sys.stderr,a # Try to parse! tree = parseLTL(a,reasonForNotBeingASlugsFormula) # printTree(tree) currentLine = translateToSlugsFormat(tree) print currentLine print "" # ================================== # Entry point # ================================== if __name__ == "__main__": if len(sys.argv)<2: print >>sys.stderr, "Error: Need input file parameter" sys.exit(1) inputFile = None thoroughly = False for parameter in sys.argv[1:]: if parameter.startswith("-"): if parameter=="--thorougly": thoroughly = True else: print >>sys.stderr, "Error: did not understand parameter '"+parameter+"'" sys.exit(1) else: if inputFile!=None: print >>sys.stderr, "Error: more than one file name given." sys.exit(1) inputFile = parameter performConversion(inputFile,thoroughly) print >>sys.stderr, translatedNames
bsd-3-clause
40223220/worktogether
static/Brython3.1.1-20150328-091302/Lib/base64.py
733
13975
#! /usr/bin/env python3 """RFC 3548: Base16, Base32, Base64 Data Encodings""" # Modified 04-Oct-1995 by Jack Jansen to use binascii module # Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support # Modified 22-May-2007 by Guido van Rossum to use bytes everywhere import re import struct import binascii __all__ = [ # Legacy interface exports traditional RFC 1521 Base64 encodings 'encode', 'decode', 'encodebytes', 'decodebytes', # Generalized interface for other encodings 'b64encode', 'b64decode', 'b32encode', 'b32decode', 'b16encode', 'b16decode', # Standard Base64 encoding 'standard_b64encode', 'standard_b64decode', # Some common Base64 alternatives. As referenced by RFC 3458, see thread # starting at: # # http://zgp.org/pipermail/p2p-hackers/2001-September/000316.html 'urlsafe_b64encode', 'urlsafe_b64decode', ] bytes_types = (bytes, bytearray) # Types acceptable as binary data def _bytes_from_decode_data(s): if isinstance(s, str): try: return s.encode('ascii') except UnicodeEncodeError: raise ValueError('string argument should contain only ASCII characters') elif isinstance(s, bytes_types): return s else: raise TypeError("argument should be bytes or ASCII string, not %s" % s.__class__.__name__) # Base64 encoding/decoding uses binascii def b64encode(s, altchars=None): """Encode a byte string using Base64. s is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. The encoded byte string is returned. """ if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) # Strip off the trailing newline encoded = binascii.b2a_base64(s)[:-1] if altchars is not None: if not isinstance(altchars, bytes_types): raise TypeError("expected bytes, not %s" % altchars.__class__.__name__) assert len(altchars) == 2, repr(altchars) return encoded.translate(bytes.maketrans(b'+/', altchars)) return encoded def b64decode(s, altchars=None, validate=False): """Decode a Base64 encoded byte string. s is the byte string to decode. Optional altchars must be a string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is returned. A binascii.Error is raised if s is incorrectly padded. If validate is False (the default), non-base64-alphabet characters are discarded prior to the padding check. If validate is True, non-base64-alphabet characters in the input result in a binascii.Error. """ s = _bytes_from_decode_data(s) if altchars is not None: altchars = _bytes_from_decode_data(altchars) assert len(altchars) == 2, repr(altchars) s = s.translate(bytes.maketrans(altchars, b'+/')) if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s): raise binascii.Error('Non-base64 digit found') return binascii.a2b_base64(s) def standard_b64encode(s): """Encode a byte string using the standard Base64 alphabet. s is the byte string to encode. The encoded byte string is returned. """ return b64encode(s) def standard_b64decode(s): """Decode a byte string encoded with the standard Base64 alphabet. s is the byte string to decode. The decoded byte string is returned. binascii.Error is raised if the input is incorrectly padded or if there are non-alphabet characters present in the input. """ return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/') def urlsafe_b64encode(s): """Encode a byte string using a url-safe Base64 alphabet. s is the byte string to encode. The encoded byte string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ return b64encode(s).translate(_urlsafe_encode_translation) def urlsafe_b64decode(s): """Decode a byte string encoded with the standard Base64 alphabet. s is the byte string to decode. The decoded byte string is returned. binascii.Error is raised if the input is incorrectly padded or if there are non-alphabet characters present in the input. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ s = _bytes_from_decode_data(s) s = s.translate(_urlsafe_decode_translation) return b64decode(s) # Base32 encoding/decoding must be done in Python _b32alphabet = { 0: b'A', 9: b'J', 18: b'S', 27: b'3', 1: b'B', 10: b'K', 19: b'T', 28: b'4', 2: b'C', 11: b'L', 20: b'U', 29: b'5', 3: b'D', 12: b'M', 21: b'V', 30: b'6', 4: b'E', 13: b'N', 22: b'W', 31: b'7', 5: b'F', 14: b'O', 23: b'X', 6: b'G', 15: b'P', 24: b'Y', 7: b'H', 16: b'Q', 25: b'Z', 8: b'I', 17: b'R', 26: b'2', } _b32tab = [v[0] for k, v in sorted(_b32alphabet.items())] _b32rev = dict([(v[0], k) for k, v in _b32alphabet.items()]) def b32encode(s): """Encode a byte string using Base32. s is the byte string to encode. The encoded byte string is returned. """ if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) quanta, leftover = divmod(len(s), 5) # Pad the last quantum with zero bits if necessary if leftover: s = s + bytes(5 - leftover) # Don't use += ! quanta += 1 encoded = bytearray() for i in range(quanta): # c1 and c2 are 16 bits wide, c3 is 8 bits wide. The intent of this # code is to process the 40 bits in units of 5 bits. So we take the 1 # leftover bit of c1 and tack it onto c2. Then we take the 2 leftover # bits of c2 and tack them onto c3. The shifts and masks are intended # to give us values of exactly 5 bits in width. c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5]) c2 += (c1 & 1) << 16 # 17 bits wide c3 += (c2 & 3) << 8 # 10 bits wide encoded += bytes([_b32tab[c1 >> 11], # bits 1 - 5 _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10 _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15 _b32tab[c2 >> 12], # bits 16 - 20 (1 - 5) _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10) _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15) _b32tab[c3 >> 5], # bits 31 - 35 (1 - 5) _b32tab[c3 & 0x1f], # bits 36 - 40 (1 - 5) ]) # Adjust for any leftover partial quanta if leftover == 1: encoded[-6:] = b'======' elif leftover == 2: encoded[-4:] = b'====' elif leftover == 3: encoded[-3:] = b'===' elif leftover == 4: encoded[-1:] = b'=' return bytes(encoded) def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded byte string. s is the byte string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The decoded byte string is returned. binascii.Error is raised if the input is incorrectly padded or if there are non-alphabet characters present in the input. """ s = _bytes_from_decode_data(s) quanta, leftover = divmod(len(s), 8) if leftover: raise binascii.Error('Incorrect padding') # Handle section 2.4 zero and one mapping. The flag map01 will be either # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01 is not None: map01 = _bytes_from_decode_data(map01) assert len(map01) == 1, repr(map01) s = s.translate(bytes.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad # characters because this will tell us how many null bytes to remove from # the end of the decoded string. padchars = 0 mo = re.search(b'(?P<pad>[=]*)$', s) if mo: padchars = len(mo.group('pad')) if padchars > 0: s = s[:-padchars] # Now decode the full quanta parts = [] acc = 0 shift = 35 for c in s: val = _b32rev.get(c) if val is None: raise binascii.Error('Non-base32 digit found') acc += _b32rev[c] << shift shift -= 5 if shift < 0: parts.append(binascii.unhexlify(bytes('%010x' % acc, "ascii"))) acc = 0 shift = 35 # Process the last, partial quanta last = binascii.unhexlify(bytes('%010x' % acc, "ascii")) if padchars == 0: last = b'' # No characters elif padchars == 1: last = last[:-1] elif padchars == 3: last = last[:-2] elif padchars == 4: last = last[:-3] elif padchars == 6: last = last[:-4] else: raise binascii.Error('Incorrect padding') parts.append(last) return b''.join(parts) # RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns # lowercase. The RFC also recommends against accepting input case # insensitively. def b16encode(s): """Encode a byte string using Base16. s is the byte string to encode. The encoded byte string is returned. """ if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) return binascii.hexlify(s).upper() def b16decode(s, casefold=False): """Decode a Base16 encoded byte string. s is the byte string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded byte string is returned. binascii.Error is raised if s were incorrectly padded or if there are non-alphabet characters present in the string. """ s = _bytes_from_decode_data(s) if casefold: s = s.upper() if re.search(b'[^0-9A-F]', s): raise binascii.Error('Non-base16 digit found') return binascii.unhexlify(s) # Legacy interface. This code could be cleaned up since I don't believe # binascii has any line length limitations. It just doesn't seem worth it # though. The files should be opened in binary mode. MAXLINESIZE = 76 # Excluding the CRLF MAXBINSIZE = (MAXLINESIZE//4)*3 def encode(input, output): """Encode a file; input and output are binary files.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s)) if not ns: break s += ns line = binascii.b2a_base64(s) output.write(line) def decode(input, output): """Decode a file; input and output are binary files.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s) def encodebytes(s): """Encode a bytestring into a bytestring containing multiple lines of base-64 data.""" if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return b"".join(pieces) def encodestring(s): """Legacy alias of encodebytes().""" import warnings warnings.warn("encodestring() is a deprecated alias, use encodebytes()", DeprecationWarning, 2) return encodebytes(s) def decodebytes(s): """Decode a bytestring of base-64 data into a bytestring.""" if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) return binascii.a2b_base64(s) def decodestring(s): """Legacy alias of decodebytes().""" import warnings warnings.warn("decodestring() is a deprecated alias, use decodebytes()", DeprecationWarning, 2) return decodebytes(s) # Usable as a script... def main(): """Small main program""" import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') except getopt.error as msg: sys.stdout = sys.stderr print(msg) print("""usage: %s [-d|-e|-u|-t] [file|-] -d, -u: decode -e: encode (default) -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]) sys.exit(2) func = encode for o, a in opts: if o == '-e': func = encode if o == '-d': func = decode if o == '-u': func = decode if o == '-t': test(); return if args and args[0] != '-': with open(args[0], 'rb') as f: func(f, sys.stdout.buffer) else: func(sys.stdin.buffer, sys.stdout.buffer) def test(): s0 = b"Aladdin:open sesame" print(repr(s0)) s1 = encodebytes(s0) print(repr(s1)) s2 = decodebytes(s1) print(repr(s2)) assert s0 == s2 if __name__ == '__main__': main()
gpl-3.0
TiVo/samza
samza-test/src/main/python/integration_tests.py
25
1141
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # 'License'); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os dir = os.path.dirname(os.path.abspath(__file__)) test = { 'deployment_code': os.path.join(dir, 'deployment.py'), 'perf_code': os.path.join(dir, 'perf.py'), 'configs_directory': os.path.join(dir, 'configs'), 'test_code': [ os.path.join(dir, 'tests', 'smoke_tests.py'), os.path.join(dir, 'tests', 'performance_tests.py'), ], }
apache-2.0
jbeich/Aquaria
ExternalLibs/freetype2/src/tools/docmaker/tohtml.py
395
18731
# ToHTML (c) 2002, 2003, 2005, 2006, 2007, 2008 # David Turner <david@freetype.org> from sources import * from content import * from formatter import * import time # The following defines the HTML header used by all generated pages. html_header_1 = """\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>\ """ html_header_2 = """\ API Reference</title> <style type="text/css"> body { font-family: Verdana, Geneva, Arial, Helvetica, serif; color: #000000; background: #FFFFFF; } p { text-align: justify; } h1 { text-align: center; } li { text-align: justify; } td { padding: 0 0.5em 0 0.5em; } td.left { padding: 0 0.5em 0 0.5em; text-align: left; } a:link { color: #0000EF; } a:visited { color: #51188E; } a:hover { color: #FF0000; } span.keyword { font-family: monospace; text-align: left; white-space: pre; color: darkblue; } pre.colored { color: blue; } ul.empty { list-style-type: none; } </style> </head> <body> """ html_header_3 = """ <table align=center><tr><td><font size=-1>[<a href="\ """ html_header_3i = """ <table align=center><tr><td width="100%"></td> <td><font size=-1>[<a href="\ """ html_header_4 = """\ ">Index</a>]</font></td> <td width="100%"></td> <td><font size=-1>[<a href="\ """ html_header_5 = """\ ">TOC</a>]</font></td></tr></table> <center><h1>\ """ html_header_5t = """\ ">Index</a>]</font></td> <td width="100%"></td></tr></table> <center><h1>\ """ html_header_6 = """\ API Reference</h1></center> """ # The HTML footer used by all generated pages. html_footer = """\ </body> </html>\ """ # The header and footer used for each section. section_title_header = "<center><h1>" section_title_footer = "</h1></center>" # The header and footer used for code segments. code_header = '<pre class="colored">' code_footer = '</pre>' # Paragraph header and footer. para_header = "<p>" para_footer = "</p>" # Block header and footer. block_header = '<table align=center width="75%"><tr><td>' block_footer_start = """\ </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="\ """ block_footer_middle = """\ ">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="\ """ block_footer_end = """\ ">TOC</a>]</font></td></tr></table> """ # Description header/footer. description_header = '<table align=center width="87%"><tr><td>' description_footer = "</td></tr></table><br>" # Marker header/inter/footer combination. marker_header = '<table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>' marker_inter = "</b></em></td></tr><tr><td>" marker_footer = "</td></tr></table>" # Header location header/footer. header_location_header = '<table align=center width="87%"><tr><td>' header_location_footer = "</td></tr></table><br>" # Source code extracts header/footer. source_header = '<table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre>\n' source_footer = "\n</pre></table><br>" # Chapter header/inter/footer. chapter_header = '<br><table align=center width="75%"><tr><td><h2>' chapter_inter = '</h2><ul class="empty"><li>' chapter_footer = '</li></ul></td></tr></table>' # Index footer. index_footer_start = """\ <hr> <table><tr><td width="100%"></td> <td><font size=-2>[<a href="\ """ index_footer_end = """\ ">TOC</a>]</font></td></tr></table> """ # TOC footer. toc_footer_start = """\ <hr> <table><tr><td><font size=-2>[<a href="\ """ toc_footer_end = """\ ">Index</a>]</font></td> <td width="100%"></td> </tr></table> """ # source language keyword coloration/styling keyword_prefix = '<span class="keyword">' keyword_suffix = '</span>' section_synopsis_header = '<h2>Synopsis</h2>' section_synopsis_footer = '' # Translate a single line of source to HTML. This will convert # a "<" into "&lt.", ">" into "&gt.", etc. def html_quote( line ): result = string.replace( line, "&", "&amp;" ) result = string.replace( result, "<", "&lt;" ) result = string.replace( result, ">", "&gt;" ) return result # same as 'html_quote', but ignores left and right brackets def html_quote0( line ): return string.replace( line, "&", "&amp;" ) def dump_html_code( lines, prefix = "" ): # clean the last empty lines l = len( self.lines ) while l > 0 and string.strip( self.lines[l - 1] ) == "": l = l - 1 # The code footer should be directly appended to the last code # line to avoid an additional blank line. print prefix + code_header, for line in self.lines[0 : l + 1]: print '\n' + prefix + html_quote( line ), print prefix + code_footer, class HtmlFormatter( Formatter ): def __init__( self, processor, project_title, file_prefix ): Formatter.__init__( self, processor ) global html_header_1, html_header_2, html_header_3 global html_header_4, html_header_5, html_footer if file_prefix: file_prefix = file_prefix + "-" else: file_prefix = "" self.headers = processor.headers self.project_title = project_title self.file_prefix = file_prefix self.html_header = html_header_1 + project_title + \ html_header_2 + \ html_header_3 + file_prefix + "index.html" + \ html_header_4 + file_prefix + "toc.html" + \ html_header_5 + project_title + \ html_header_6 self.html_index_header = html_header_1 + project_title + \ html_header_2 + \ html_header_3i + file_prefix + "toc.html" + \ html_header_5 + project_title + \ html_header_6 self.html_toc_header = html_header_1 + project_title + \ html_header_2 + \ html_header_3 + file_prefix + "index.html" + \ html_header_5t + project_title + \ html_header_6 self.html_footer = "<center><font size=""-2"">generated on " + \ time.asctime( time.localtime( time.time() ) ) + \ "</font></center>" + html_footer self.columns = 3 def make_section_url( self, section ): return self.file_prefix + section.name + ".html" def make_block_url( self, block ): return self.make_section_url( block.section ) + "#" + block.name def make_html_words( self, words ): """ convert a series of simple words into some HTML text """ line = "" if words: line = html_quote( words[0] ) for w in words[1:]: line = line + " " + html_quote( w ) return line def make_html_word( self, word ): """analyze a simple word to detect cross-references and styling""" # look for cross-references m = re_crossref.match( word ) if m: try: name = m.group( 1 ) rest = m.group( 2 ) block = self.identifiers[name] url = self.make_block_url( block ) return '<a href="' + url + '">' + name + '</a>' + rest except: # we detected a cross-reference to an unknown item sys.stderr.write( \ "WARNING: undefined cross reference '" + name + "'.\n" ) return '?' + name + '?' + rest # look for italics and bolds m = re_italic.match( word ) if m: name = m.group( 1 ) rest = m.group( 3 ) return '<i>' + name + '</i>' + rest m = re_bold.match( word ) if m: name = m.group( 1 ) rest = m.group( 3 ) return '<b>' + name + '</b>' + rest return html_quote( word ) def make_html_para( self, words ): """ convert words of a paragraph into tagged HTML text, handle xrefs """ line = "" if words: line = self.make_html_word( words[0] ) for word in words[1:]: line = line + " " + self.make_html_word( word ) # convert `...' quotations into real left and right single quotes line = re.sub( r"(^|\W)`(.*?)'(\W|$)", \ r'\1&lsquo;\2&rsquo;\3', \ line ) # convert tilde into non-breakable space line = string.replace( line, "~", "&nbsp;" ) return para_header + line + para_footer def make_html_code( self, lines ): """ convert a code sequence to HTML """ line = code_header + '\n' for l in lines: line = line + html_quote( l ) + '\n' return line + code_footer def make_html_items( self, items ): """ convert a field's content into some valid HTML """ lines = [] for item in items: if item.lines: lines.append( self.make_html_code( item.lines ) ) else: lines.append( self.make_html_para( item.words ) ) return string.join( lines, '\n' ) def print_html_items( self, items ): print self.make_html_items( items ) def print_html_field( self, field ): if field.name: print "<table><tr valign=top><td><b>" + field.name + "</b></td><td>" print self.make_html_items( field.items ) if field.name: print "</td></tr></table>" def html_source_quote( self, line, block_name = None ): result = "" while line: m = re_source_crossref.match( line ) if m: name = m.group( 2 ) prefix = html_quote( m.group( 1 ) ) length = len( m.group( 0 ) ) if name == block_name: # this is the current block name, if any result = result + prefix + '<b>' + name + '</b>' elif re_source_keywords.match( name ): # this is a C keyword result = result + prefix + keyword_prefix + name + keyword_suffix elif self.identifiers.has_key( name ): # this is a known identifier block = self.identifiers[name] result = result + prefix + '<a href="' + \ self.make_block_url( block ) + '">' + name + '</a>' else: result = result + html_quote( line[:length] ) line = line[length:] else: result = result + html_quote( line ) line = [] return result def print_html_field_list( self, fields ): print "<p></p>" print "<table cellpadding=3 border=0>" for field in fields: if len( field.name ) > 22: print "<tr valign=top><td colspan=0><b>" + field.name + "</b></td></tr>" print "<tr valign=top><td></td><td>" else: print "<tr valign=top><td><b>" + field.name + "</b></td><td>" self.print_html_items( field.items ) print "</td></tr>" print "</table>" def print_html_markup( self, markup ): table_fields = [] for field in markup.fields: if field.name: # we begin a new series of field or value definitions, we # will record them in the 'table_fields' list before outputting # all of them as a single table # table_fields.append( field ) else: if table_fields: self.print_html_field_list( table_fields ) table_fields = [] self.print_html_items( field.items ) if table_fields: self.print_html_field_list( table_fields ) # # Formatting the index # def index_enter( self ): print self.html_index_header self.index_items = {} def index_name_enter( self, name ): block = self.identifiers[name] url = self.make_block_url( block ) self.index_items[name] = url def index_exit( self ): # block_index already contains the sorted list of index names count = len( self.block_index ) rows = ( count + self.columns - 1 ) / self.columns print "<table align=center border=0 cellpadding=0 cellspacing=0>" for r in range( rows ): line = "<tr>" for c in range( self.columns ): i = r + c * rows if i < count: bname = self.block_index[r + c * rows] url = self.index_items[bname] line = line + '<td><a href="' + url + '">' + bname + '</a></td>' else: line = line + '<td></td>' line = line + "</tr>" print line print "</table>" print index_footer_start + \ self.file_prefix + "toc.html" + \ index_footer_end print self.html_footer self.index_items = {} def index_dump( self, index_filename = None ): if index_filename == None: index_filename = self.file_prefix + "index.html" Formatter.index_dump( self, index_filename ) # # Formatting the table of content # def toc_enter( self ): print self.html_toc_header print "<center><h1>Table of Contents</h1></center>" def toc_chapter_enter( self, chapter ): print chapter_header + string.join( chapter.title ) + chapter_inter print "<table cellpadding=5>" def toc_section_enter( self, section ): print '<tr valign=top><td class="left">' print '<a href="' + self.make_section_url( section ) + '">' + \ section.title + '</a></td><td>' print self.make_html_para( section.abstract ) def toc_section_exit( self, section ): print "</td></tr>" def toc_chapter_exit( self, chapter ): print "</table>" print chapter_footer def toc_index( self, index_filename ): print chapter_header + \ '<a href="' + index_filename + '">Global Index</a>' + \ chapter_inter + chapter_footer def toc_exit( self ): print toc_footer_start + \ self.file_prefix + "index.html" + \ toc_footer_end print self.html_footer def toc_dump( self, toc_filename = None, index_filename = None ): if toc_filename == None: toc_filename = self.file_prefix + "toc.html" if index_filename == None: index_filename = self.file_prefix + "index.html" Formatter.toc_dump( self, toc_filename, index_filename ) # # Formatting sections # def section_enter( self, section ): print self.html_header print section_title_header print section.title print section_title_footer maxwidth = 0 for b in section.blocks.values(): if len( b.name ) > maxwidth: maxwidth = len( b.name ) width = 70 # XXX magic number if maxwidth <> 0: # print section synopsis print section_synopsis_header print "<table align=center cellspacing=5 cellpadding=0 border=0>" columns = width / maxwidth if columns < 1: columns = 1 count = len( section.block_names ) rows = ( count + columns - 1 ) / columns for r in range( rows ): line = "<tr>" for c in range( columns ): i = r + c * rows line = line + '<td></td><td>' if i < count: name = section.block_names[i] line = line + '<a href="#' + name + '">' + name + '</a>' line = line + '</td>' line = line + "</tr>" print line print "</table><br><br>" print section_synopsis_footer print description_header print self.make_html_items( section.description ) print description_footer def block_enter( self, block ): print block_header # place html anchor if needed if block.name: print '<h4><a name="' + block.name + '">' + block.name + '</a></h4>' # dump the block C source lines now if block.code: header = '' for f in self.headers.keys(): if block.source.filename.find( f ) >= 0: header = self.headers[f] + ' (' + f + ')' break; # if not header: # sys.stderr.write( \ # 'WARNING: No header macro for ' + block.source.filename + '.\n' ) if header: print header_location_header print 'Defined in ' + header + '.' print header_location_footer print source_header for l in block.code: print self.html_source_quote( l, block.name ) print source_footer def markup_enter( self, markup, block ): if markup.tag == "description": print description_header else: print marker_header + markup.tag + marker_inter self.print_html_markup( markup ) def markup_exit( self, markup, block ): if markup.tag == "description": print description_footer else: print marker_footer def block_exit( self, block ): print block_footer_start + self.file_prefix + "index.html" + \ block_footer_middle + self.file_prefix + "toc.html" + \ block_footer_end def section_exit( self, section ): print html_footer def section_dump_all( self ): for section in self.sections: self.section_dump( section, self.file_prefix + section.name + '.html' ) # eof
gpl-2.0
Meriipu/quodlibet
quodlibet/packages/raven/context.py
13
3769
""" raven.context ~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from collections import Mapping, Iterable from threading import local from weakref import ref as weakref from raven.utils.compat import iteritems try: from thread import get_ident as get_thread_ident except ImportError: from _thread import get_ident as get_thread_ident _active_contexts = local() def get_active_contexts(): """Returns all the active contexts for the current thread.""" try: return list(_active_contexts.contexts) except AttributeError: return [] class Context(local, Mapping, Iterable): """ Stores context until cleared. >>> def view_handler(view_func, *args, **kwargs): >>> context = Context() >>> context.merge(tags={'key': 'value'}) >>> try: >>> return view_func(*args, **kwargs) >>> finally: >>> context.clear() """ def __init__(self, client=None): breadcrumbs = raven.breadcrumbs.make_buffer( client is None or client.enable_breadcrumbs) if client is not None: client = weakref(client) self._client = client # Because the thread auto activates the thread local this also # means that we auto activate this thing. Only if someone decides # to deactivate manually later another call to activate is # technically necessary. self.activate() self.data = {} self.exceptions_to_skip = set() self.breadcrumbs = breadcrumbs @property def client(self): if self._client is None: return None return self._client() def __hash__(self): return id(self) def __eq__(self, other): return self is other def __ne__(self, other): return not self.__eq__(other) def __getitem__(self, key): return self.data[key] def __iter__(self): return iter(self.data) def __len__(self): return len(self.data) def __repr__(self): return '<%s: %s>' % (type(self).__name__, self.data) def __enter__(self): self.activate() return self def __exit__(self, exc_type, exc_value, tb): self.deactivate() def activate(self, sticky=False): if sticky: self._sticky_thread = get_thread_ident() _active_contexts.__dict__.setdefault('contexts', set()).add(self) def deactivate(self): try: _active_contexts.contexts.discard(self) except AttributeError: pass def merge(self, data, activate=True): if activate: self.activate() d = self.data for key, value in iteritems(data): if key in ('tags', 'extra'): d.setdefault(key, {}) for t_key, t_value in iteritems(value): d[key][t_key] = t_value else: d[key] = value def set(self, data): self.data = data def get(self): return self.data def clear(self, deactivate=None): self.data = {} self.exceptions_to_skip.clear() self.breadcrumbs.clear() # If the caller did not specify if it wants to deactivate the # context for the thread we only deactivate it if we're not the # thread that created the context (main thread). if deactivate is None: client = self.client if client is not None: deactivate = get_thread_ident() != client.main_thread_id if deactivate: self.deactivate() import raven.breadcrumbs
gpl-2.0
rajsadho/django
tests/gis_tests/gdal_tests/test_srs.py
304
11694
import unittest from unittest import skipUnless from django.contrib.gis.gdal import HAS_GDAL if HAS_GDAL: from django.contrib.gis.gdal import SpatialReference, CoordTransform, GDALException, SRSException class TestSRS: def __init__(self, wkt, **kwargs): self.wkt = wkt for key, value in kwargs.items(): setattr(self, key, value) # Some Spatial Reference examples srlist = ( TestSRS( 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,' 'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",' '0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', proj='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ', epsg=4326, projected=False, geographic=True, local=False, lin_name='unknown', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199, auth={'GEOGCS': ('EPSG', '4326'), 'spheroid': ('EPSG', '7030')}, attr=(('DATUM', 'WGS_1984'), (('SPHEROID', 1), '6378137'), ('primem|authority', 'EPSG'),), ), TestSRS( 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.28333333333333],' 'PARAMETER["standard_parallel_2",28.38333333333333],' 'PARAMETER["latitude_of_origin",27.83333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],' 'AUTHORITY["EPSG","32140"]]', proj=None, epsg=32140, projected=True, geographic=False, local=False, lin_name='metre', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199, auth={'PROJCS': ('EPSG', '32140'), 'spheroid': ('EPSG', '7019'), 'unit': ('EPSG', '9001')}, attr=( ('DATUM', 'North_American_Datum_1983'), (('SPHEROID', 2), '298.257222101'), ('PROJECTION', 'Lambert_Conformal_Conic_2SP'), ), ), TestSRS( 'PROJCS["NAD_1983_StatePlane_Texas_South_Central_FIPS_4204_Feet",' 'GEOGCS["GCS_North_American_1983",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],' 'UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["False_Easting",1968500.0],PARAMETER["False_Northing",13123333.33333333],' 'PARAMETER["Central_Meridian",-99.0],PARAMETER["Standard_Parallel_1",28.38333333333333],' 'PARAMETER["Standard_Parallel_2",30.28333333333334],PARAMETER["Latitude_Of_Origin",27.83333333333333],' 'UNIT["Foot_US",0.3048006096012192]]', proj=None, epsg=None, projected=True, geographic=False, local=False, lin_name='Foot_US', ang_name='Degree', lin_units=0.3048006096012192, ang_units=0.0174532925199, auth={'PROJCS': (None, None)}, attr=(('PROJCS|GeOgCs|spheroid', 'GRS_1980'), (('projcs', 9), 'UNIT'), (('projcs', 11), None),), ), # This is really ESRI format, not WKT -- but the import should work the same TestSRS( 'LOCAL_CS["Non-Earth (Meter)",LOCAL_DATUM["Local Datum",0],UNIT["Meter",1.0],AXIS["X",EAST],AXIS["Y",NORTH]]', esri=True, proj=None, epsg=None, projected=False, geographic=False, local=True, lin_name='Meter', ang_name='degree', lin_units=1.0, ang_units=0.0174532925199, attr=(('LOCAL_DATUM', 'Local Datum'), ('unit', 'Meter')), ), ) # Well-Known Names well_known = ( TestSRS( 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,' 'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', wk='WGS84', name='WGS 84', attrs=(('GEOGCS|AUTHORITY', 1, '4326'), ('SPHEROID', 'WGS 84')), ), TestSRS( 'GEOGCS["WGS 72",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26,' 'AUTHORITY["EPSG","7043"]],AUTHORITY["EPSG","6322"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4322"]]', wk='WGS72', name='WGS 72', attrs=(('GEOGCS|AUTHORITY', 1, '4322'), ('SPHEROID', 'WGS 72')), ), TestSRS( 'GEOGCS["NAD27",DATUM["North_American_Datum_1927",' 'SPHEROID["Clarke 1866",6378206.4,294.9786982138982,' 'AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4267"]]', wk='NAD27', name='NAD27', attrs=(('GEOGCS|AUTHORITY', 1, '4267'), ('SPHEROID', 'Clarke 1866')) ), TestSRS( 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,' 'AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]]', wk='NAD83', name='NAD83', attrs=(('GEOGCS|AUTHORITY', 1, '4269'), ('SPHEROID', 'GRS 1980')), ), TestSRS( 'PROJCS["NZGD49 / Karamea Circuit",GEOGCS["NZGD49",' 'DATUM["New_Zealand_Geodetic_Datum_1949",' 'SPHEROID["International 1924",6378388,297,' 'AUTHORITY["EPSG","7022"]],' 'TOWGS84[59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993],' 'AUTHORITY["EPSG","6272"]],PRIMEM["Greenwich",0,' 'AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4272"]],' 'PROJECTION["Transverse_Mercator"],' 'PARAMETER["latitude_of_origin",-41.28991152777778],' 'PARAMETER["central_meridian",172.1090281944444],' 'PARAMETER["scale_factor",1],PARAMETER["false_easting",300000],' 'PARAMETER["false_northing",700000],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","27216"]]', wk='EPSG:27216', name='NZGD49 / Karamea Circuit', attrs=(('PROJECTION', 'Transverse_Mercator'), ('SPHEROID', 'International 1924')), ), ) bad_srlist = ( 'Foobar', 'OOJCS["NAD83 / Texas South Central",GEOGCS["NAD83",' 'DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.28333333333333],' 'PARAMETER["standard_parallel_2",28.38333333333333],' 'PARAMETER["latitude_of_origin",27.83333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,' 'AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32140"]]', ) @skipUnless(HAS_GDAL, "GDAL is required") class SpatialRefTest(unittest.TestCase): def test01_wkt(self): "Testing initialization on valid OGC WKT." for s in srlist: SpatialReference(s.wkt) def test02_bad_wkt(self): "Testing initialization on invalid WKT." for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, GDALException): pass else: self.fail('Should not have initialized on bad WKT "%s"!') def test03_get_wkt(self): "Testing getting the WKT." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.wkt, srs.wkt) def test04_proj(self): "Test PROJ.4 import and export." for s in srlist: if s.proj: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.proj) self.assertEqual(srs1.proj, srs2.proj) def test05_epsg(self): "Test EPSG import." for s in srlist: if s.epsg: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.epsg) srs3 = SpatialReference(str(s.epsg)) srs4 = SpatialReference('EPSG:%d' % s.epsg) for srs in (srs1, srs2, srs3, srs4): for attr, expected in s.attr: self.assertEqual(expected, srs[attr]) def test07_boolean_props(self): "Testing the boolean properties." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.projected, srs.projected) self.assertEqual(s.geographic, srs.geographic) def test08_angular_linear(self): "Testing the linear and angular units routines." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.ang_name, srs.angular_name) self.assertEqual(s.lin_name, srs.linear_name) self.assertAlmostEqual(s.ang_units, srs.angular_units, 9) self.assertAlmostEqual(s.lin_units, srs.linear_units, 9) def test09_authority(self): "Testing the authority name & code routines." for s in srlist: if hasattr(s, 'auth'): srs = SpatialReference(s.wkt) for target, tup in s.auth.items(): self.assertEqual(tup[0], srs.auth_name(target)) self.assertEqual(tup[1], srs.auth_code(target)) def test10_attributes(self): "Testing the attribute retrieval routines." for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: att = tup[0] # Attribute to test exp = tup[1] # Expected result self.assertEqual(exp, srs[att]) def test11_wellknown(self): "Testing Well Known Names of Spatial References." for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if len(tup) == 2: key = tup[0] exp = tup[1] elif len(tup) == 3: key = tup[:2] exp = tup[2] self.assertEqual(srs[key], exp) def test12_coordtransform(self): "Testing initialization of a CoordTransform." target = SpatialReference('WGS84') for s in srlist: if s.proj: CoordTransform(SpatialReference(s.wkt), target) def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference('WGS84') self.assertRaises(TypeError, s1.__getitem__, 0) self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo')) self.assertEqual('WGS 84', s1['GEOGCS']) self.assertEqual('WGS_1984', s1['DATUM']) self.assertEqual('EPSG', s1['AUTHORITY']) self.assertEqual(4326, int(s1['AUTHORITY', 1])) self.assertIsNone(s1['FOOBAR'])
bsd-3-clause
PyPlanet/PyPlanet
pyplanet/conf/backends/python.py
1
1598
import importlib import os from pyplanet.conf.backends.base import ConfigBackend from pyplanet.core.exceptions import ImproperlyConfigured class PythonConfigBackend(ConfigBackend): name = 'python' def __init__(self, **options): super().__init__(**options) self.module = None def load(self): # Make sure we load the defaults first. super().load() # Prepare the loading. self.module = os.environ.get('PYPLANET_SETTINGS_MODULE', 'settings') if not self.module: raise ImproperlyConfigured( 'Settings module is not defined! Please define PYPLANET_SETTINGS_MODULE in your environment or start script.' ) # Add the module itself to the configuration. self.settings['SETTINGS_MODULE'] = self.module # Load the module, put the settings into the local context. try: module = importlib.import_module(self.module) except ModuleNotFoundError as e: raise ImproperlyConfigured( 'The settings module doesn\'t contain any submodules or files to load! Please make sure ' 'your settings module exist or contains the files base.py and apps.py. Your module: {}'.format(self.module) ) from e # Load from the modules. processed = 0 for setting in dir(module): if setting.isupper(): self.settings[setting] = getattr(module, setting) processed += 1 # Check for empty results. if processed < 1: raise ImproperlyConfigured( 'The settings module doesn\'t contain any submodules or files to load! Please make sure ' 'your settings module exist or contains the files base.py and apps.py. Your module: {}'.format(self.module) )
gpl-3.0
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/PyQt4/QtCore/__init__/QMetaMethod.py
2
4241
# encoding: utf-8 # module PyQt4.QtCore # from /usr/lib/python2.7/dist-packages/PyQt4/QtCore.so # by generator 1.135 # no doc # imports import sip as __sip class QMetaMethod(): # skipped bases: <type 'sip.simplewrapper'> """ QMetaMethod() QMetaMethod(QMetaMethod) """ def access(self): # real signature unknown; restored from __doc__ """ QMetaMethod.access() -> QMetaMethod.Access """ pass def invoke(self, QObject, *__args): # real signature unknown; restored from __doc__ with multiple overloads """ QMetaMethod.invoke(QObject, Qt.ConnectionType, QGenericReturnArgument, QGenericArgument value0=QGenericArgument(0,0), QGenericArgument value1=QGenericArgument(0,0), QGenericArgument value2=QGenericArgument(0,0), QGenericArgument value3=QGenericArgument(0,0), QGenericArgument value4=QGenericArgument(0,0), QGenericArgument value5=QGenericArgument(0,0), QGenericArgument value6=QGenericArgument(0,0), QGenericArgument value7=QGenericArgument(0,0), QGenericArgument value8=QGenericArgument(0,0), QGenericArgument value9=QGenericArgument(0,0)) -> object QMetaMethod.invoke(QObject, QGenericReturnArgument, QGenericArgument value0=QGenericArgument(0,0), QGenericArgument value1=QGenericArgument(0,0), QGenericArgument value2=QGenericArgument(0,0), QGenericArgument value3=QGenericArgument(0,0), QGenericArgument value4=QGenericArgument(0,0), QGenericArgument value5=QGenericArgument(0,0), QGenericArgument value6=QGenericArgument(0,0), QGenericArgument value7=QGenericArgument(0,0), QGenericArgument value8=QGenericArgument(0,0), QGenericArgument value9=QGenericArgument(0,0)) -> object QMetaMethod.invoke(QObject, Qt.ConnectionType, QGenericArgument value0=QGenericArgument(0,0), QGenericArgument value1=QGenericArgument(0,0), QGenericArgument value2=QGenericArgument(0,0), QGenericArgument value3=QGenericArgument(0,0), QGenericArgument value4=QGenericArgument(0,0), QGenericArgument value5=QGenericArgument(0,0), QGenericArgument value6=QGenericArgument(0,0), QGenericArgument value7=QGenericArgument(0,0), QGenericArgument value8=QGenericArgument(0,0), QGenericArgument value9=QGenericArgument(0,0)) -> object QMetaMethod.invoke(QObject, QGenericArgument value0=QGenericArgument(0,0), QGenericArgument value1=QGenericArgument(0,0), QGenericArgument value2=QGenericArgument(0,0), QGenericArgument value3=QGenericArgument(0,0), QGenericArgument value4=QGenericArgument(0,0), QGenericArgument value5=QGenericArgument(0,0), QGenericArgument value6=QGenericArgument(0,0), QGenericArgument value7=QGenericArgument(0,0), QGenericArgument value8=QGenericArgument(0,0), QGenericArgument value9=QGenericArgument(0,0)) -> object """ pass def methodIndex(self): # real signature unknown; restored from __doc__ """ QMetaMethod.methodIndex() -> int """ return 0 def methodType(self): # real signature unknown; restored from __doc__ """ QMetaMethod.methodType() -> QMetaMethod.MethodType """ pass def parameterNames(self): # real signature unknown; restored from __doc__ """ QMetaMethod.parameterNames() -> list-of-QByteArray """ pass def parameterTypes(self): # real signature unknown; restored from __doc__ """ QMetaMethod.parameterTypes() -> list-of-QByteArray """ pass def signature(self): # real signature unknown; restored from __doc__ """ QMetaMethod.signature() -> str """ return "" def tag(self): # real signature unknown; restored from __doc__ """ QMetaMethod.tag() -> str """ return "" def typeName(self): # real signature unknown; restored from __doc__ """ QMetaMethod.typeName() -> str """ return "" def __init__(self, QMetaMethod=None): # real signature unknown; restored from __doc__ with multiple overloads pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" Access = None # (!) real value is '' Constructor = 3 Method = 0 MethodType = None # (!) real value is '' Private = 0 Protected = 1 Public = 2 Signal = 1 Slot = 2
gpl-2.0
keis/smoke
tests/test_mixed.py
1
1963
import pytest import mock from hamcrest import assert_that from matchmock import called_once_with from smoke import signal, Broker class Source(object): spam = signal() egg = signal(name='egg') class Mixed(Source, Broker): pass @pytest.fixture def listener(): return mock.Mock() @pytest.fixture def mixed(): return Mixed() def test_subscribe_signal_publish_broker(mixed, listener): sentinel = object() mixed.spam.subscribe(listener.spam_cb) mixed.publish(mixed.spam, s=sentinel) assert_that(listener.spam_cb, called_once_with(s=sentinel)) def test_subscribe_broker_publish_signal(mixed, listener): sentinel = object() mixed.subscribe(mixed.spam, listener.spam_cb) mixed.spam(s=sentinel) assert_that(listener.spam_cb, called_once_with(s=sentinel)) def test_subscribe_broker_publish_signal_with_name(mixed, listener): sentinel = object() mixed.subscribe(mixed.egg, listener.egg_cb) mixed.egg(s=sentinel) assert_that(listener.egg_cb, called_once_with(s=sentinel)) @pytest.mark.skip(reason="Not supported, for now") def test_subscribe_signal_publish_boundsignal(mixed, listener): # Supporting this in a general way might be a bit to intrusive as # boundmethod and function and other things implementing the descriptor # protocol would be consider equal as well. sentinel = object() mixed.subscribe(Mixed.spam, listener.spam_cb) mixed.publish(mixed.spam, s=sentinel) assert_that(listener.spam_cb, called_once_with(s=sentinel)) def test_subscribe_by_name(mixed, listener): sentinel = object() mixed.subscribe('egg', listener.egg_cb) mixed.egg(s=sentinel) assert_that(listener.egg_cb, called_once_with(s=sentinel)) def test_publish_override(mixed, listener): sentinel = object() mixed.publish = mock.Mock(wraps=mixed.publish) mixed.egg(s=sentinel) assert_that(mixed.publish, called_once_with(mixed.egg, s=sentinel))
mit
daltonmaag/brotli
tools/rfc-format.py
99
2111
#!/usr/bin/python # # Takes an .nroff source file and prints a text file in RFC format. # # Usage: rfc-format.py <source file> import re import sys from subprocess import Popen, PIPE def Readfile(fn): f = open(fn, "r") return f.read() def FixNroffOutput(buf): p = re.compile(r'(.*)FORMFEED(\[Page\s+\d+\])$') strip_empty = False out = "" for line in buf.split("\n"): line = line.replace("\xe2\x80\x99", "'") line = line.replace("\xe2\x80\x90", "-") for i in range(len(line)): if ord(line[i]) > 128: print >>sys.stderr, "Invalid character %d\n" % ord(line[i]) m = p.search(line) if strip_empty and len(line) == 0: continue if m: out += p.sub(r'\1 \2\n\f', line) out += "\n" strip_empty = True else: out += "%s\n" % line strip_empty = False return out.rstrip("\n") def Nroff(buf): p = Popen(["nroff", "-ms"], stdin=PIPE, stdout=PIPE) out, err = p.communicate(input=buf) return FixNroffOutput(out) def FormatTocLine(section, title, page): line = "" level = 1 if section: level = section.count(".") for i in range(level): line += " " if section: line += "%s " % section line += "%s " % title pagenum = "%d" % page nspace = 72 - len(line) - len(pagenum) if nspace % 2: line += " " for i in range(nspace / 2): line += ". " line += "%d\n" % page return line def CreateToc(buf): p1 = re.compile(r'^((\d+\.)+)\s+(.*)$') p2 = re.compile(r'^(Appendix [A-Z].)\s+(.*)$') p3 = re.compile(r'\[Page (\d+)\]$') found = 0 page = 1 out = "" for line in buf.split("\n"): m1 = p1.search(line) m2 = p2.search(line) m3 = p3.search(line) if m1: out += FormatTocLine(m1.group(1), m1.group(3), page) elif m2: out += FormatTocLine(m2.group(1), m2.group(2), page) elif line.startswith("Authors"): out += FormatTocLine(None, line, page) elif m3: page = int(m3.group(1)) + 1 return out src = Readfile(sys.argv[1]) out = Nroff(src) toc = CreateToc(out) src = src.replace("INSERT_TOC_HERE", toc) print Nroff(src)
apache-2.0
SaM-Solutions/samba
source4/heimdal/lib/wind/util.py
88
1978
#!/usr/local/bin/python # -*- coding: iso-8859-1 -*- # $Id$ # Copyright (c) 2004 Kungliga Tekniska Högskolan # (Royal Institute of Technology, Stockholm, Sweden). # 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 Institute 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 INSTITUTE 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 INSTITUTE 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. def subList(l, sl) : """return the index of sl in l or None""" lLen = len(l) slLen = len(sl) for i in range(lLen - slLen + 1): j = 0 while j < slLen and l[i + j] == sl[j]: j += 1 if j == slLen: return i return None
gpl-3.0
AladdinSonni/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/net/regressionwindow.py
165
2381
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # FIXME: This probably belongs in the buildbot module. class RegressionWindow(object): def __init__(self, build_before_failure, failing_build, failing_tests=None): self._build_before_failure = build_before_failure self._failing_build = failing_build self._failing_tests = failing_tests self._revisions = None def build_before_failure(self): return self._build_before_failure def failing_build(self): return self._failing_build def failing_tests(self): return self._failing_tests def revisions(self): # Cache revisions to avoid excessive allocations. if not self._revisions: self._revisions = range(self._failing_build.revision(), self._build_before_failure.revision(), -1) self._revisions.reverse() return self._revisions
bsd-3-clause
laginimaineb/android_fde_bruteforce
structures.py
1
2262
import struct from StringIO import StringIO #The crypt_mnt_ftr structure - see /system/vold/cryptfs.h CRYPT_MNT_FTR = [('magic' , 'I'), ('major_version' , 'H'), ('minor_version' , 'H'), ('ftr_size' , 'I'), ('flags' , 'I'), ('keysize' , 'I'), ('crypt_size' , 'I'), ('fs_size' , 'Q'), ('failed_decrypt_count' , 'I'), ('crypto_type_name' , '64s'), ('spare2' , 'I'), ('master_key' , '48s'), ('salt' , '16s'), ('persist_data_offset_0' , 'Q'), ('persist_data_offset_1' , 'Q'), ('persist_data_size' , 'I'), ('kdf_type' , 'B'), ('N_factor' , 'B'), ('r_factor' , 'B'), ('p_factor' , 'B'), ('encrypted_upto' , 'Q'), ('hash_first_block' , '32s'), ('keymaster_blob' , '2048s'), ('keymaster_blob_size' , 'I'), ('scrypted_intermediate_key', '32s')] #The qcom_km_key_blob structure - see /hardware/qcom/keymaster/keymaster_qcom.h QCOM_KEY_BLOB = [('magic_num' , 'I'), ('version_num' , 'I'), ('modulus' , '512s'), ('modulus_size' , 'I'), ('public_exponent' , '512s'), ('public_exponent_size' , 'I'), ('iv' , '16s'), ('encrypted_private_exponent' , '512s'), ('encrypted_private_exponent_size' , 'I'), ('hmac' , '32s')] def read_object(data, definition): ''' Unpacks a structure using the given data and definition. ''' reader = StringIO(data) obj = {} object_size = 0 for (name, stype) in definition: object_size += struct.calcsize(stype) obj[name] = struct.unpack(stype, reader.read(struct.calcsize(stype)))[0] obj['object_size'] = object_size obj['raw_data'] = data return obj def read_crypt_mnt_ftr(data): return read_object(data, CRYPT_MNT_FTR) def read_qcom_key_blob(data): return read_object(data, QCOM_KEY_BLOB)
gpl-2.0
mahak/ansible
lib/ansible/inventory/helpers.py
120
1293
# (c) 2017, Ansible by RedHat Inc, # # 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/>. ############################################# from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.utils.vars import combine_vars def sort_groups(groups): return sorted(groups, key=lambda g: (g.depth, g.priority, g.name)) def get_group_vars(groups): """ Combine all the group vars from a list of inventory groups. :param groups: list of ansible.inventory.group.Group objects :rtype: dict """ results = {} for group in sort_groups(groups): results = combine_vars(results, group.get_vars()) return results
gpl-3.0
chaluemwut/fbserver
venv/lib/python2.7/site-packages/scipy/ndimage/tests/test_ndimage.py
9
199791
# Copyright (C) 2003-2005 Peter J. Verveer # # 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. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. from __future__ import division, print_function, absolute_import import warnings import math import sys import numpy from numpy import fft from numpy.testing import (assert_, assert_equal, assert_array_equal, run_module_suite, assert_array_almost_equal, assert_almost_equal, dec) import scipy.ndimage as ndimage eps = 1e-12 def sumsq(a, b): return math.sqrt(((a - b)**2).sum()) class TestNdimage: def setUp(self): # list of numarray data types self.integer_types = [numpy.int8, numpy.uint8, numpy.int16, numpy.uint16, numpy.int32, numpy.uint32, numpy.int64, numpy.uint64] self.float_types = [numpy.float32, numpy.float64] self.types = self.integer_types + self.float_types # list of boundary modes: self.modes = ['nearest', 'wrap', 'reflect', 'mirror', 'constant'] def test_correlate01(self): array = numpy.array([1, 2]) weights = numpy.array([2]) expected = [2, 4] output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate02(self): array = numpy.array([1, 2, 3]) kernel = numpy.array([1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate03(self): array = numpy.array([1]) weights = numpy.array([1, 1]) expected = [2] output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate04(self): array = numpy.array([1, 2]) tcor = [2, 3] tcov = [3, 4] weights = numpy.array([1, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate05(self): array = numpy.array([1, 2, 3]) tcor = [2, 3, 5] tcov = [3, 5, 6] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(tcov, output) def test_correlate06(self): array = numpy.array([1, 2, 3]) tcor = [9, 14, 17] tcov = [7, 10, 15] weights = numpy.array([1, 2, 3]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate07(self): array = numpy.array([1, 2, 3]) expected = [5, 8, 11] weights = numpy.array([1, 2, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate08(self): array = numpy.array([1, 2, 3]) tcor = [1, 2, 5] tcov = [3, 6, 7] weights = numpy.array([1, 2, -1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate09(self): array = [] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate10(self): array = [[]] kernel = numpy.array([[1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) def test_correlate11(self): array = numpy.array([[1, 2, 3], [4, 5, 6]]) kernel = numpy.array([[1, 1], [1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) output = ndimage.convolve(array, kernel) assert_array_almost_equal([[12, 16, 18], [18, 22, 24]], output) def test_correlate12(self): array = numpy.array([[1, 2, 3], [4, 5, 6]]) kernel = numpy.array([[1, 0], [0, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) output = ndimage.convolve(array, kernel) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) def test_correlate13(self): kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) for type2 in self.types: output = ndimage.correlate(array, kernel, output=type2) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, type2) output = ndimage.convolve(array, kernel, output=type2) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, type2) def test_correlate14(self): kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) for type2 in self.types: output = numpy.zeros(array.shape, type2) ndimage.correlate(array, kernel, output=output) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, type2) ndimage.convolve(array, kernel, output=output) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, type2) def test_correlate15(self): kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate16(self): kernel = numpy.array([[0.5, 0], [0, 0.5]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32) assert_array_almost_equal([[1, 1.5, 2.5], [2.5, 3, 4]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32) assert_array_almost_equal([[3, 4, 4.5], [4.5, 5.5, 6]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate17(self): array = numpy.array([1, 2, 3]) tcor = [3, 5, 6] tcov = [2, 3, 5] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) def test_correlate18(self): kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32, mode='nearest', origin=-1) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32, mode='nearest', origin=-1) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate19(self): kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal([[5, 6, 8], [8, 9, 11]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal([[3, 5, 6], [6, 8, 9]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate20(self): weights = numpy.array([1, 2, 1]) expected = [[5, 10, 15], [7, 14, 21]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) def test_correlate21(self): array = numpy.array([[1, 2, 3], [2, 4, 6]]) expected = [[5, 10, 15], [7, 14, 21]] weights = numpy.array([1, 2, 1]) output = ndimage.correlate1d(array, weights, axis=0) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights, axis=0) assert_array_almost_equal(output, expected) def test_correlate22(self): weights = numpy.array([1, 2, 1]) expected = [[6, 12, 18], [6, 12, 18]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) def test_correlate23(self): weights = numpy.array([1, 2, 1]) expected = [[5, 10, 15], [7, 14, 21]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) def test_correlate24(self): weights = numpy.array([1, 2, 1]) tcor = [[7, 14, 21], [8, 16, 24]] tcov = [[4, 8, 12], [5, 10, 15]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcov) def test_correlate25(self): weights = numpy.array([1, 2, 1]) tcor = [[4, 8, 12], [5, 10, 15]] tcov = [[7, 14, 21], [8, 16, 24]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcov) def test_gauss01(self): input = numpy.array([[1, 2, 3], [2, 4, 6]], numpy.float32) output = ndimage.gaussian_filter(input, 0) assert_array_almost_equal(output, input) def test_gauss02(self): input = numpy.array([[1, 2, 3], [2, 4, 6]], numpy.float32) output = ndimage.gaussian_filter(input, 1.0) assert_equal(input.dtype, output.dtype) assert_equal(input.shape, output.shape) def test_gauss03(self): # single precision data" input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) output = ndimage.gaussian_filter(input, [1.0, 1.0]) assert_equal(input.dtype, output.dtype) assert_equal(input.shape, output.shape) # input.sum() is 49995000.0. With single precision floats, we can't # expect more than 8 digits of accuracy, so use decimal=0 in this test. assert_almost_equal(output.sum(dtype='d'), input.sum(dtype='d'), decimal=0) assert_(sumsq(input, output) > 1.0) def test_gauss04(self): input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) assert_equal(output.dtype.type, numpy.float64) assert_equal(input.shape, output.shape) assert_(sumsq(input, output) > 1.0) def test_gauss05(self): input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], order=1, output=otype) assert_equal(output.dtype.type, numpy.float64) assert_equal(input.shape, output.shape) assert_(sumsq(input, output) > 1.0) def test_gauss06(self): input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) output2 = ndimage.gaussian_filter(input, 1.0, output=otype) assert_array_almost_equal(output1, output2) def test_prewitt01(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) output = ndimage.prewitt(array, 0) assert_array_almost_equal(t, output) def test_prewitt02(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) output = numpy.zeros(array.shape, type) ndimage.prewitt(array, 0, output) assert_array_almost_equal(t, output) def test_prewitt03(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 0) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) def test_prewitt04(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.prewitt(array, -1) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) def test_sobel01(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) output = ndimage.sobel(array, 0) assert_array_almost_equal(t, output) def test_sobel02(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) output = numpy.zeros(array.shape, type) ndimage.sobel(array, 0, output) assert_array_almost_equal(t, output) def test_sobel03(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 0) output = numpy.zeros(array.shape, type) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) def test_sobel04(self): for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.sobel(array, -1) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) def test_laplace01(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) output = ndimage.laplace(array) assert_array_almost_equal(tmp1 + tmp2, output) def test_laplace02(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) output = numpy.zeros(array.shape, type) ndimage.laplace(array, output=output) assert_array_almost_equal(tmp1 + tmp2, output) def test_gaussian_laplace01(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = ndimage.gaussian_laplace(array, 1.0) assert_array_almost_equal(tmp1 + tmp2, output) def test_gaussian_laplace02(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = numpy.zeros(array.shape, type) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp1 + tmp2, output) def test_generic_laplace01(self): def derivative2(input, axis, output, mode, cval, a, b): sigma = [a, b / 2.0] input = numpy.asarray(input) order = [0] * input.ndim order[axis] = 2 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = numpy.zeros(array.shape, type) tmp = ndimage.generic_laplace(array, derivative2, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp, output) def test_gaussian_gradient_magnitude01(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = ndimage.gaussian_gradient_magnitude(array, 1.0) expected = tmp1 * tmp1 + tmp2 * tmp2 expected = numpy.sqrt(expected).astype(type) assert_array_almost_equal(expected, output) def test_gaussian_gradient_magnitude02(self): for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = numpy.zeros(array.shape, type) ndimage.gaussian_gradient_magnitude(array, 1.0, output) expected = tmp1 * tmp1 + tmp2 * tmp2 expected = numpy.sqrt(expected).astype(type) assert_array_almost_equal(expected, output) def test_generic_gradient_magnitude01(self): array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], numpy.float64) def derivative(input, axis, output, mode, cval, a, b): sigma = [a, b / 2.0] input = numpy.asarray(input) order = [0] * input.ndim order[axis] = 1 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) tmp2 = ndimage.generic_gradient_magnitude(array, derivative, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) assert_array_almost_equal(tmp1, tmp2) def test_uniform01(self): array = numpy.array([2, 4, 6]) size = 2 output = ndimage.uniform_filter1d(array, size, origin=-1) assert_array_almost_equal([3, 5, 6], output) def test_uniform02(self): array = numpy.array([1, 2, 3]) filter_shape = [0] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform03(self): array = numpy.array([1, 2, 3]) filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform04(self): array = numpy.array([2, 4, 6]) filter_shape = [2] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal([2, 3, 5], output) def test_uniform05(self): array = [] filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal([], output) def test_uniform06(self): filter_shape = [2, 2] for type1 in self.types: array = numpy.array([[4, 8, 12], [16, 20, 24]], type1) for type2 in self.types: output = ndimage.uniform_filter(array, filter_shape, output=type2) assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) assert_equal(output.dtype.type, type2) def test_minimum_filter01(self): array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([1, 1, 2, 3, 4], output) def test_minimum_filter02(self): array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([1, 1, 2, 3, 4], output) def test_minimum_filter03(self): array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([3, 2, 2, 1, 1], output) def test_minimum_filter04(self): array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([2, 2, 1, 1, 1], output) def test_minimum_filter05(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = numpy.array([2, 3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]], output) def test_minimum_filter06(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 1, 1], [1, 1, 1]] output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]], output) def test_minimum_filter07(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_minimum_filter08(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal([[3, 1, 3, 1, 1], [5, 3, 3, 1, 1], [3, 3, 1, 1, 1]], output) def test_minimum_filter09(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal([[2, 3, 1, 3, 1], [5, 5, 3, 3, 1], [5, 3, 3, 1, 1]], output) def test_maximum_filter01(self): array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([1, 2, 3, 4, 5], output) def test_maximum_filter02(self): array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([2, 3, 4, 5, 5], output) def test_maximum_filter03(self): array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([3, 3, 5, 5, 4], output) def test_maximum_filter04(self): array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([3, 5, 5, 5, 4], output) def test_maximum_filter05(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = numpy.array([2, 3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]], output) def test_maximum_filter06(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 1, 1], [1, 1, 1]] output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]], output) def test_maximum_filter07(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]], output) def test_maximum_filter08(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal([[7, 9, 9, 5, 5], [9, 8, 9, 7, 5], [8, 8, 7, 7, 7]], output) def test_maximum_filter09(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_rank01(self): array = numpy.array([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=2) assert_array_almost_equal(array, output) output = ndimage.percentile_filter(array, 100, size=2) assert_array_almost_equal(array, output) output = ndimage.median_filter(array, 2) assert_array_almost_equal(array, output) def test_rank02(self): array = numpy.array([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=[3]) assert_array_almost_equal(array, output) output = ndimage.percentile_filter(array, 50, size=3) assert_array_almost_equal(array, output) output = ndimage.median_filter(array, (3,)) assert_array_almost_equal(array, output) def test_rank03(self): array = numpy.array([3, 2, 5, 1, 4]) output = ndimage.rank_filter(array, 1, size=[2]) assert_array_almost_equal([3, 3, 5, 5, 4], output) output = ndimage.percentile_filter(array, 100, size=2) assert_array_almost_equal([3, 3, 5, 5, 4], output) def test_rank04(self): array = numpy.array([3, 2, 5, 1, 4]) expected = [3, 3, 2, 4, 4] output = ndimage.rank_filter(array, 1, size=3) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 50, size=3) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, size=3) assert_array_almost_equal(expected, output) def test_rank05(self): array = numpy.array([3, 2, 5, 1, 4]) expected = [3, 3, 2, 4, 4] output = ndimage.rank_filter(array, -2, size=3) assert_array_almost_equal(expected, output) def test_rank06(self): array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[2, 2, 1, 1, 1], [3, 3, 2, 1, 1], [5, 5, 3, 3, 1]] output = ndimage.rank_filter(array, 1, size=[2, 3]) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 17, size=(2, 3)) assert_array_almost_equal(expected, output) def test_rank07(self): array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 5, 5, 5, 4], [5, 5, 7, 5, 4], [6, 8, 8, 7, 5]] output = ndimage.rank_filter(array, -2, size=[2, 3]) assert_array_almost_equal(expected, output) def test_rank08(self): array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 3, 2, 4, 4], [5, 5, 5, 4, 4], [5, 6, 7, 5, 5]] output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) assert_array_almost_equal(expected, output) output = ndimage.rank_filter(array, 3, size=(2, 3)) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, size=(2, 3)) assert_array_almost_equal(expected, output) def test_rank09(self): expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 35, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank10(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]] footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.rank_filter(array, 0, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 0.0, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank11(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]] footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.rank_filter(array, -1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 100.0, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank12(self): expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 50.0, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank13(self): expected = [[5, 2, 5, 1, 1], [5, 8, 3, 5, 5], [6, 6, 5, 5, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=-1) assert_array_almost_equal(expected, output) def test_rank14(self): expected = [[3, 5, 2, 5, 1], [5, 5, 8, 3, 5], [5, 6, 6, 5, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal(expected, output) def test_rank15(self): "rank filter 15" expected = [[2, 3, 1, 4, 1], [5, 3, 7, 1, 1], [5, 5, 3, 3, 3]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 0, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal(expected, output) def test_generic_filter1d01(self): weights = numpy.array([1.1, 2.2, 3.3]) def _filter_func(input, output, fltr, total): fltr = fltr / total for ii in range(input.shape[0] - 2): output[ii] = input[ii] * fltr[0] output[ii] += input[ii + 1] * fltr[1] output[ii] += input[ii + 2] * fltr[2] for type in self.types: a = numpy.arange(12, dtype=type) a.shape = (3,4) r1 = ndimage.correlate1d(a, weights / weights.sum(), 0, origin=-1) r2 = ndimage.generic_filter1d(a, _filter_func, 3, axis=0, origin=-1, extra_arguments=(weights,), extra_keywords={'total': weights.sum()}) assert_array_almost_equal(r1, r2) def test_generic_filter01(self): filter_ = numpy.array([[1.0, 2.0], [3.0, 4.0]]) footprint = numpy.array([[1, 0], [0, 1]]) cf = numpy.array([1., 4.]) def _filter_func(buffer, weights, total=1.0): weights = cf / total return (buffer * weights).sum() for type in self.types: a = numpy.arange(12, dtype=type) a.shape = (3,4) r1 = ndimage.correlate(a, filter_ * footprint) if type in self.float_types: r1 /= 5 else: r1 //= 5 r2 = ndimage.generic_filter(a, _filter_func, footprint=footprint, extra_arguments=(cf,), extra_keywords={'total': cf.sum()}) assert_array_almost_equal(r1, r2) def test_extend01(self): array = numpy.array([1, 2, 3]) weights = numpy.array([1, 0]) expected_values = [[1, 1, 2], [3, 1, 2], [1, 1, 2], [2, 1, 2], [0, 1, 2]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output,expected_value) def test_extend02(self): array = numpy.array([1, 2, 3]) weights = numpy.array([1, 0, 0, 0, 0, 0, 0, 0]) expected_values = [[1, 1, 1], [3, 1, 2], [3, 3, 2], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend03(self): array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 1]) expected_values = [[2, 3, 3], [2, 3, 1], [2, 3, 3], [2, 3, 2], [2, 3, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend04(self): array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend05(self): array = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = numpy.array([[1, 0], [0, 0]]) expected_values = [[[1, 1, 2], [1, 1, 2], [4, 4, 5]], [[9, 7, 8], [3, 1, 2], [6, 4, 5]], [[1, 1, 2], [1, 1, 2], [4, 4, 5]], [[5, 4, 5], [2, 1, 2], [5, 4, 5]], [[0, 0, 0], [0, 1, 2], [0, 4, 5]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend06(self): array = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = numpy.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) expected_values = [[[5, 6, 6], [8, 9, 9], [8, 9, 9]], [[5, 6, 4], [8, 9, 7], [2, 3, 1]], [[5, 6, 6], [8, 9, 9], [8, 9, 9]], [[5, 6, 5], [8, 9, 8], [5, 6, 5]], [[5, 6, 0], [8, 9, 0], [0, 0, 0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend07(self): array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend08(self): array = numpy.array([[1], [2], [3]]) weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) expected_values = [[[3], [3], [3]], [[2], [3], [1]], [[2], [1], [1]], [[1], [2], [3]], [[0], [0], [0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend09(self): array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend10(self): array = numpy.array([[1], [2], [3]]) weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) expected_values = [[[3], [3], [3]], [[2], [3], [1]], [[2], [1], [1]], [[1], [2], [3]], [[0], [0], [0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_boundaries(self): def shift(x): return (x[0] + 0.5,) data = numpy.array([1,2,3,4.]) expected = {'constant': [1.5,2.5,3.5,-1,-1,-1,-1], 'wrap': [1.5,2.5,3.5,1.5,2.5,3.5,1.5], 'mirror': [1.5,2.5,3.5,3.5,2.5,1.5,1.5], 'nearest': [1.5,2.5,3.5,4,4,4,4]} for mode in expected: assert_array_equal(expected[mode], ndimage.geometric_transform(data,shift, cval=-1,mode=mode, output_shape=(7,), order=1)) def test_boundaries2(self): def shift(x): return (x[0] - 0.9,) data = numpy.array([1,2,3,4]) expected = {'constant': [-1,1,2,3], 'wrap': [3,1,2,3], 'mirror': [2,1,2,3], 'nearest': [1,1,2,3]} for mode in expected: assert_array_equal(expected[mode], ndimage.geometric_transform(data,shift, cval=-1,mode=mode, output_shape=(4,))) def test_fourier_gaussian_real01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1) def test_fourier_gaussian_complex01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_fourier_uniform_real01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0) def test_fourier_uniform_complex01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_fourier_shift_real01(self): for shape in [(32, 16), (31, 15)]: for dtype in [numpy.float32, numpy.float64]: expected = numpy.arange(shape[0] * shape[1], dtype=dtype) expected.shape = shape a = fft.rfft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1]) assert_array_almost_equal(a.imag, numpy.zeros(shape)) def test_fourier_shift_complex01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: expected = numpy.arange(shape[0] * shape[1], dtype=type) expected.shape = shape a = fft.fft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_array_almost_equal(a.real[1:, 1:], expected[:-1, :-1]) assert_array_almost_equal(a.imag, numpy.zeros(shape)) def test_fourier_ellipsoid_real01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0) def test_fourier_ellipsoid_complex01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_spline01(self): for type in self.types: data = numpy.ones([], type) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, 1) def test_spline02(self): for type in self.types: data = numpy.array([1]) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, [1]) def test_spline03(self): for type in self.types: data = numpy.ones([], type) for order in range(2, 6): out = ndimage.spline_filter(data, order, output=type) assert_array_almost_equal(out, 1) def test_spline04(self): for type in self.types: data = numpy.ones([4], type) for order in range(2, 6): out = ndimage.spline_filter(data, order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_spline05(self): for type in self.types: data = numpy.ones([4, 4], type) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) def test_geometric_transform01(self): data = numpy.array([1]) def mapping(x): return x for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [1]) def test_geometric_transform01_with_output_parameter(self): data = numpy.array([1]) def mapping(x): return x for order in range(0, 6): out = numpy.empty_like(data) ndimage.geometric_transform(data, mapping, data.shape, output=out) assert_array_almost_equal(out, [1]) out = numpy.empty_like(data).astype(data.dtype.newbyteorder()) ndimage.geometric_transform(data, mapping, data.shape, output=out) assert_array_almost_equal(out, [1]) def test_geometric_transform02(self): data = numpy.ones([4]) def mapping(x): return x for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_geometric_transform03(self): data = numpy.ones([4]) def mapping(x): return (x[0] - 1,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_geometric_transform04(self): data = numpy.array([4, 1, 3, 2]) def mapping(x): return (x[0] - 1,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_geometric_transform05(self): data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) def mapping(x): return (x[0], x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_geometric_transform06(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0], x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_geometric_transform07(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_geometric_transform08(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_geometric_transform10(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1] - 1) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.geometric_transform(filtered, mapping, data.shape, order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_geometric_transform13(self): data = numpy.ones([2], numpy.float64) def mapping(x): return (x[0] // 2,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_geometric_transform14(self): data = [1, 5, 2, 6, 3, 7, 4, 4] def mapping(x): return (2 * x[0],) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 2, 3, 4]) def test_geometric_transform15(self): data = [1, 2, 3, 4] def mapping(x): return (x[0] / 2,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [8], order=order) assert_array_almost_equal(out[::2], [1, 2, 3, 4]) def test_geometric_transform16(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9.0, 10, 11, 12]] def mapping(x): return (x[0], x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (3, 2), order=order) assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) def test_geometric_transform17(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] * 2, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (1, 4), order=order) assert_array_almost_equal(out, [[1, 2, 3, 4]]) def test_geometric_transform18(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] * 2, x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (1, 2), order=order) assert_array_almost_equal(out, [[1, 3]]) def test_geometric_transform19(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0], x[1] / 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (3, 8), order=order) assert_array_almost_equal(out[..., ::2], data) def test_geometric_transform20(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] / 2, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (6, 4), order=order) assert_array_almost_equal(out[::2, ...], data) def test_geometric_transform21(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] / 2, x[1] / 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_geometric_transform22(self): data = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], numpy.float64) def mapping1(x): return (x[0] / 2, x[1] / 2) def mapping2(x): return (x[0] * 2, x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping1, (6, 8), order=order) out = ndimage.geometric_transform(out, mapping2, (3, 4), order=order) assert_array_almost_equal(out, data) def test_geometric_transform23(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (1, x[0] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (2,), order=order) out = out.astype(numpy.int32) assert_array_almost_equal(out, [5, 7]) def test_geometric_transform24(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x, a, b): return (a, x[0] * b) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (2,), order=order, extra_arguments=(1,), extra_keywords={'b': 2}) assert_array_almost_equal(out, [5, 7]) def test_map_coordinates01(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) idx = numpy.indices(data.shape) idx -= 1 for order in range(0, 6): out = ndimage.map_coordinates(data, idx, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_map_coordinates01_with_output_parameter(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) idx = numpy.indices(data.shape) idx -= 1 expected = numpy.array([[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) for order in range(0, 6): out = numpy.empty_like(expected) ndimage.map_coordinates(data, idx, order=order, output=out) assert_array_almost_equal(out, expected) out = numpy.empty_like(expected).astype( expected.dtype.newbyteorder()) ndimage.map_coordinates(data, idx, order=order, output=out) assert_array_almost_equal(out, expected) def test_map_coordinates02(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) idx = numpy.indices(data.shape, numpy.float64) idx -= 0.5 for order in range(0, 6): out1 = ndimage.shift(data, 0.5, order=order) out2 = ndimage.map_coordinates(data, idx, order=order) assert_array_almost_equal(out1, out2) def test_map_coordinates03(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]], order='F') idx = numpy.indices(data.shape) - 1 out = ndimage.map_coordinates(data, idx) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) assert_array_almost_equal(out, ndimage.shift(data, (1, 1))) idx = numpy.indices(data[::2].shape) - 1 out = ndimage.map_coordinates(data[::2], idx) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3]]) assert_array_almost_equal(out, ndimage.shift(data[::2], (1, 1))) idx = numpy.indices(data[:,::2].shape) - 1 out = ndimage.map_coordinates(data[:,::2], idx) assert_array_almost_equal(out, [[0, 0], [0, 4], [0, 7]]) assert_array_almost_equal(out, ndimage.shift(data[:,::2], (1, 1))) # do not run on 32 bit or windows (no sparse memory) @dec.skipif('win32' in sys.platform or numpy.intp(0).itemsize < 8) def test_map_coordinates_large_data(self): # check crash on large data n = 30000 a = numpy.empty(n**2, dtype=numpy.float32).reshape(n, n) # fill the part we might read a[n - 3:,n - 3:] = 0 ndimage.map_coordinates(a, [[n - 1.5], [n - 1.5]], order=1) def test_affine_transform01(self): data = numpy.array([1]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], order=order) assert_array_almost_equal(out, [1]) def test_affine_transform01_with_output_parameter(self): data = numpy.array([1]) for order in range(0, 6): out = numpy.empty_like(data) ndimage.affine_transform(data, [[1]], order=order, output=out) assert_array_almost_equal(out, [1]) out = numpy.empty_like(data).astype(data.dtype.newbyteorder()) ndimage.affine_transform(data, [[1]], order=order, output=out) assert_array_almost_equal(out, [1]) def test_affine_transform02(self): data = numpy.ones([4]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_affine_transform03(self): data = numpy.ones([4]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], -1, order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_affine_transform04(self): data = numpy.array([4, 1, 3, 2]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], -1, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_affine_transform05(self): data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [0, -1], order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_affine_transform06(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [0, -1], order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_affine_transform07(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [-1, 0], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_affine_transform08(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [-1, -1], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_affine_transform09(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.affine_transform(filtered,[[1, 0], [0, 1]], [-1, -1], order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_affine_transform10(self): data = numpy.ones([2], numpy.float64) for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5]], output_shape=(4,), order=order) assert_array_almost_equal(out, [1, 1, 1, 0]) def test_affine_transform11(self): data = [1, 5, 2, 6, 3, 7, 4, 4] for order in range(0, 6): out = ndimage.affine_transform(data, [[2]], 0, (4,), order=order) assert_array_almost_equal(out, [1, 2, 3, 4]) def test_affine_transform12(self): data = [1, 2, 3, 4] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5]], 0, (8,), order=order) assert_array_almost_equal(out[::2], [1, 2, 3, 4]) def test_affine_transform13(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9.0, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 2]], 0, (3, 2), order=order) assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) def test_affine_transform14(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2, 0], [0, 1]], 0, (1, 4), order=order) assert_array_almost_equal(out, [[1, 2, 3, 4]]) def test_affine_transform15(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2, 0], [0, 2]], 0, (1, 2), order=order) assert_array_almost_equal(out, [[1, 3]]) def test_affine_transform16(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0.0], [0, 0.5]], 0, (3, 8), order=order) assert_array_almost_equal(out[..., ::2], data) def test_affine_transform17(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 1]], 0, (6, 4), order=order) assert_array_almost_equal(out[::2, ...], data) def test_affine_transform18(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_affine_transform19(self): data = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], numpy.float64) for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, (6, 8), order=order) out = ndimage.affine_transform(out, [[2.0, 0], [0, 2.0]], 0, (3, 4), order=order) assert_array_almost_equal(out, data) def test_affine_transform20(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0], [2]], 0, (2,), order=order) assert_array_almost_equal(out, [1, 3]) def test_affine_transform21(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2], [0]], 0, (2,), order=order) assert_array_almost_equal(out, [1, 9]) def test_shift01(self): data = numpy.array([1]) for order in range(0, 6): out = ndimage.shift(data, [1], order=order) assert_array_almost_equal(out, [0]) def test_shift02(self): data = numpy.ones([4]) for order in range(0, 6): out = ndimage.shift(data, [1], order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_shift03(self): data = numpy.ones([4]) for order in range(0, 6): out = ndimage.shift(data, -1, order=order) assert_array_almost_equal(out, [1, 1, 1, 0]) def test_shift04(self): data = numpy.array([4, 1, 3, 2]) for order in range(0, 6): out = ndimage.shift(data, 1, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_shift05(self): data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) for order in range(0, 6): out = ndimage.shift(data, [0, 1], order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_shift06(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [0, 1], order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_shift07(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [1, 0], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_shift08(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [1, 1], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_shift09(self): data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_zoom1(self): for order in range(0,6): for z in [2,[2,2]]: arr = numpy.array(list(range(25))).reshape((5,5)).astype(float) arr = ndimage.zoom(arr, z, order=order) assert_equal(arr.shape,(10,10)) assert_(numpy.all(arr[-1,:] != 0)) assert_(numpy.all(arr[-1,:] >= (20 - eps))) assert_(numpy.all(arr[0,:] <= (5 + eps))) assert_(numpy.all(arr >= (0 - eps))) assert_(numpy.all(arr <= (24 + eps))) def test_zoom2(self): arr = numpy.arange(12).reshape((3,4)) out = ndimage.zoom(ndimage.zoom(arr,2),0.5) assert_array_equal(out,arr) def test_zoom3(self): err = numpy.seterr(invalid='ignore') arr = numpy.array([[1, 2]]) try: out1 = ndimage.zoom(arr, (2, 1)) out2 = ndimage.zoom(arr, (1,2)) finally: numpy.seterr(**err) assert_array_almost_equal(out1, numpy.array([[1, 2], [1, 2]])) assert_array_almost_equal(out2, numpy.array([[1, 1, 2, 2]])) def test_zoom_affine01(self): data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [0.5, 0.5], 0, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_zoom_infinity(self): # Ticket #1419 regression test err = numpy.seterr(divide='ignore') try: dim = 8 ndimage.zoom(numpy.zeros((dim, dim)), 1./dim, mode='nearest') finally: numpy.seterr(**err) def test_zoom_zoomfactor_one(self): # Ticket #1122 regression test arr = numpy.zeros((1, 5, 5)) zoom = (1.0, 2.0, 2.0) err = numpy.seterr(invalid='ignore') try: out = ndimage.zoom(arr, zoom, cval=7) finally: numpy.seterr(**err) ref = numpy.zeros((1, 10, 10)) assert_array_almost_equal(out, ref) def test_zoom_output_shape_roundoff(self): arr = numpy.zeros((3, 11, 25)) zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) out = ndimage.zoom(arr, zoom) assert_array_equal(out.shape, (4, 15, 29)) def test_rotate01(self): data = numpy.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 0) assert_array_almost_equal(out, data) def test_rotate02(self): data = numpy.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) assert_array_almost_equal(out, expected) def test_rotate03(self): data = numpy.array([[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0], [0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) assert_array_almost_equal(out, expected) def test_rotate04(self): data = numpy.array([[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90, reshape=False) assert_array_almost_equal(out, expected) def test_rotate05(self): data = numpy.empty((4,3,3)) for i in range(3): data[:,:,i] = numpy.array([[0,0,0], [0,1,0], [0,1,0], [0,0,0]], dtype=numpy.float64) expected = numpy.array([[0,0,0,0], [0,1,1,0], [0,0,0,0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) for i in range(3): assert_array_almost_equal(out[:,:,i], expected) def test_rotate06(self): data = numpy.empty((3,4,3)) for i in range(3): data[:,:,i] = numpy.array([[0,0,0,0], [0,1,1,0], [0,0,0,0]], dtype=numpy.float64) expected = numpy.array([[0,0,0], [0,1,0], [0,1,0], [0,0,0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) for i in range(3): assert_array_almost_equal(out[:,:,i], expected) def test_rotate07(self): data = numpy.array([[[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) data = data.transpose() expected = numpy.array([[[0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0]]] * 2, dtype=numpy.float64) expected = expected.transpose([2,1,0]) for order in range(0, 6): out = ndimage.rotate(data, 90, axes=(0, 1)) assert_array_almost_equal(out, expected) def test_rotate08(self): data = numpy.array([[[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) data = data.transpose() expected = numpy.array([[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) expected = expected.transpose() for order in range(0, 6): out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False) assert_array_almost_equal(out, expected) def test_watershed_ift01(self): data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[-1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift02(self): data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[-1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, 1, 1, 1, -1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, 1, 1, 1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift03(self): data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 0, 3, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, 2, -1, 3, -1, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, -1, 2, -1, 3, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift04(self): data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 0, 3, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift05(self): data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift06(self): data = numpy.array([[0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[-1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift07(self): shape = (7, 6) data = numpy.zeros(shape, dtype=numpy.uint8) data = data.transpose() data[...] = numpy.array([[0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[-1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = numpy.zeros(shape, dtype=numpy.int16) out = out.transpose() ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]], output=out) expected = [[-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_distance_transform_bf01(self): # brute force (bf) distance transform for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 2, 4, 2, 1, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 1, 2, 4, 2, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 2, 1, 2, 3, 3, 3], [4, 4, 4, 4, 6, 4, 4, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 2, 4, 6, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf02(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'cityblock', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 1, 2, 3, 2, 1, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 3, 1, 3, 3, 3, 3], [4, 4, 4, 4, 7, 4, 4, 4, 4], [5, 5, 6, 7, 7, 7, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(expected, ft) def test_distance_transform_bf03(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'chessboard', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 2, 1, 1, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 1, 1, 2, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 4, 2, 2, 2, 4, 3, 3], [4, 4, 5, 6, 6, 6, 5, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 5, 6, 6, 7, 8], [0, 1, 1, 2, 6, 6, 7, 7, 8], [0, 1, 1, 2, 6, 7, 7, 7, 8], [0, 1, 2, 2, 6, 6, 7, 7, 8], [0, 1, 2, 4, 5, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf04(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_bf(data, return_indices=1) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype=numpy.float64) ndimage.distance_transform_bf(data, distances=dt) dts.append(dt) ft = ndimage.distance_transform_bf(data, return_distances=False, return_indices=1) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_bf(data, return_distances=False, return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_bf(data, return_indices=1) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = ndimage.distance_transform_bf(data, distances=dt, return_indices=True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_bf(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_bf(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_bf05(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True, sampling=[2, 2]) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 4, 4, 0, 0, 0], [0, 0, 4, 8, 16, 8, 4, 0, 0], [0, 0, 4, 16, 32, 16, 4, 0, 0], [0, 0, 4, 8, 16, 8, 4, 0, 0], [0, 0, 0, 4, 4, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 2, 1, 2, 3, 3, 3], [4, 4, 4, 4, 6, 4, 4, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 2, 4, 6, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf06(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True, sampling=[2, 1]) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 4, 1, 0, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 1, 4, 9, 4, 1, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 0, 1, 4, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 2, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 6, 5, 5, 5, 5], [6, 6, 6, 6, 7, 6, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 6, 6, 6, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 1, 1, 7, 7, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt01(self): #chamfer type distance (cdt) transform for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_cdt(data, 'cityblock', return_indices=True) bf = ndimage.distance_transform_bf(data, 'cityblock') assert_array_almost_equal(bf, out) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 1, 1, 1, 2, 2, 2], [3, 3, 2, 1, 1, 1, 2, 3, 3], [4, 4, 4, 4, 1, 4, 4, 4, 4], [5, 5, 5, 5, 7, 7, 6, 5, 5], [6, 6, 6, 6, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 1, 1, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8],]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt02(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_cdt(data, 'chessboard', return_indices=True) bf = ndimage.distance_transform_bf(data, 'chessboard') assert_array_almost_equal(bf, out) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 1, 1, 1, 2, 2, 2], [3, 3, 2, 2, 1, 2, 2, 3, 3], [4, 4, 3, 2, 2, 2, 3, 4, 4], [5, 5, 4, 6, 7, 6, 4, 5, 5], [6, 6, 6, 6, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 3, 4, 6, 7, 8], [0, 1, 1, 2, 2, 6, 6, 7, 8], [0, 1, 1, 1, 2, 6, 7, 7, 8], [0, 1, 1, 2, 6, 6, 7, 7, 8], [0, 1, 2, 2, 5, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8],]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt03(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype=numpy.int32) ndimage.distance_transform_cdt(data, distances=dt) dts.append(dt) ft = ndimage.distance_transform_cdt(data, return_distances=False, return_indices=True) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_cdt(data, return_distances=False, return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_cdt(data, return_indices=True) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.int32) ft = ndimage.distance_transform_cdt(data, distances=dt, return_indices=True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_cdt(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.int32) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_cdt(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_edt01(self): #euclidean distance transform (edt) for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_edt(data, return_indices=True) bf = ndimage.distance_transform_bf(data, 'euclidean') assert_array_almost_equal(bf, out) dt = ft - numpy.indices(ft.shape[1:], dtype=ft.dtype) dt = dt.astype(numpy.float64) numpy.multiply(dt, dt, dt) dt = numpy.add.reduce(dt, axis=0) numpy.sqrt(dt, dt) assert_array_almost_equal(bf, dt) def test_distance_transform_edt02(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_edt(data, return_indices=True) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype=numpy.float64) ndimage.distance_transform_edt(data, distances=dt) dts.append(dt) ft = ndimage.distance_transform_edt(data, return_distances=0, return_indices=True) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_edt(data, return_distances=False,return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_edt(data, return_indices=True) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = ndimage.distance_transform_edt(data, distances=dt, return_indices=True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_edt(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_edt(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_edt03(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2]) out = ndimage.distance_transform_edt(data, sampling=[2, 2]) assert_array_almost_equal(ref, out) def test_distance_transform_edt4(self): for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1]) out = ndimage.distance_transform_edt(data, sampling=[2, 1]) assert_array_almost_equal(ref, out) def test_distance_transform_edt5(self): #Ticket #954 regression test out = ndimage.distance_transform_edt(False) assert_array_almost_equal(out, [0.]) def test_generate_structure01(self): struct = ndimage.generate_binary_structure(0, 1) assert_array_almost_equal(struct, 1) def test_generate_structure02(self): struct = ndimage.generate_binary_structure(1, 1) assert_array_almost_equal(struct, [1, 1, 1]) def test_generate_structure03(self): struct = ndimage.generate_binary_structure(2, 1) assert_array_almost_equal(struct, [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) def test_generate_structure04(self): struct = ndimage.generate_binary_structure(2, 2) assert_array_almost_equal(struct, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_iterate_structure01(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] out = ndimage.iterate_structure(struct, 2) assert_array_almost_equal(out, [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]]) def test_iterate_structure02(self): struct = [[0, 1], [1, 1], [0, 1]] out = ndimage.iterate_structure(struct, 2) assert_array_almost_equal(out, [[0, 0, 1], [0, 1, 1], [1, 1, 1], [0, 1, 1], [0, 0, 1]]) def test_iterate_structure03(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] out = ndimage.iterate_structure(struct, 2, 1) expected = [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]] assert_array_almost_equal(out[0], expected) assert_equal(out[1], [2, 2]) def test_binary_erosion01(self): for type in self.types: data = numpy.ones([], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, 1) def test_binary_erosion02(self): for type in self.types: data = numpy.ones([], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, 1) def test_binary_erosion03(self): for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0]) def test_binary_erosion04(self): for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1]) def test_binary_erosion05(self): for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 1, 0]) def test_binary_erosion06(self): for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_erosion07(self): for type in self.types: data = numpy.ones([5], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 1, 1, 1, 0]) def test_binary_erosion08(self): for type in self.types: data = numpy.ones([5], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 1, 1, 1, 1]) def test_binary_erosion09(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 0, 0, 0, 0]) def test_binary_erosion10(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 0, 0, 0, 1]) def test_binary_erosion11(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, [1, 0, 1, 0, 1]) def test_binary_erosion12(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) assert_array_almost_equal(out, [0, 1, 0, 1, 1]) def test_binary_erosion13(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=1) assert_array_almost_equal(out, [1, 1, 0, 1, 0]) def test_binary_erosion14(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 1] out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, [1, 1, 0, 0, 1]) def test_binary_erosion15(self): for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) assert_array_almost_equal(out, [1, 0, 0, 1, 1]) def test_binary_erosion16(self): for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1]]) def test_binary_erosion17(self): for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0]]) def test_binary_erosion18(self): for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0, 0, 0]]) def test_binary_erosion19(self): for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1, 1, 1]]) def test_binary_erosion20(self): for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0, 0, 0], [0, 1, 0], [0, 0, 0]]) def test_binary_erosion21(self): for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_erosion22(self): expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion23(self): struct = ndimage.generate_binary_structure(2, 2) expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion24(self): struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion25(self): struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion26(self): struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_erosion27(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=2) assert_array_almost_equal(out, expected) def test_binary_erosion28(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=2, output=out) assert_array_almost_equal(out, expected) def test_binary_erosion29(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=3) assert_array_almost_equal(out, expected) def test_binary_erosion30(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=3, output=out) assert_array_almost_equal(out, expected) def test_binary_erosion31(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=1, output=out, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_erosion32(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=2) assert_array_almost_equal(out, expected) def test_binary_erosion33(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] mask = [[1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]] data = numpy.array([[0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, mask=mask, iterations=-1) assert_array_almost_equal(out, expected) def test_binary_erosion34(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] mask = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, mask=mask) assert_array_almost_equal(out, expected) def test_binary_erosion35(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] mask = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) tmp = [[0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1]] expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=1, output=out, origin=(-1, -1), mask=mask) assert_array_almost_equal(out, expected) def test_binary_erosion36(self): struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] mask = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] tmp = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) out = ndimage.binary_erosion(data, struct, mask=mask, border_value=1, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_dilation01(self): for type in self.types: data = numpy.ones([], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, 1) def test_binary_dilation02(self): for type in self.types: data = numpy.zeros([], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, 0) def test_binary_dilation03(self): for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1]) def test_binary_dilation04(self): for type in self.types: data = numpy.zeros([1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [0]) def test_binary_dilation05(self): for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_dilation06(self): for type in self.types: data = numpy.zeros([3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [0, 0, 0]) def test_binary_dilation07(self): for type in self.types: data = numpy.zeros([3], type) data[1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_dilation08(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 data[3] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1, 1, 1]) def test_binary_dilation09(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1, 0, 0]) def test_binary_dilation10(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data, origin=-1) assert_array_almost_equal(out, [0, 1, 1, 1, 0]) def test_binary_dilation11(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data, origin=1) assert_array_almost_equal(out, [1, 1, 0, 0, 0]) def test_binary_dilation12(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, [1, 0, 1, 0, 0]) def test_binary_dilation13(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, border_value=1) assert_array_almost_equal(out, [1, 0, 1, 0, 1]) def test_binary_dilation14(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, origin=-1) assert_array_almost_equal(out, [0, 1, 0, 1, 0]) def test_binary_dilation15(self): for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, origin=-1, border_value=1) assert_array_almost_equal(out, [1, 1, 0, 1, 0]) def test_binary_dilation16(self): for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1]]) def test_binary_dilation17(self): for type in self.types: data = numpy.zeros([1, 1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[0]]) def test_binary_dilation18(self): for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1, 1, 1]]) def test_binary_dilation19(self): for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_dilation20(self): for type in self.types: data = numpy.zeros([3, 3], type) data[1, 1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) def test_binary_dilation21(self): struct = ndimage.generate_binary_structure(2, 2) for type in self.types: data = numpy.zeros([3, 3], type) data[1, 1] = 1 out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_dilation22(self): expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, expected) def test_binary_dilation23(self): expected = [[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation24(self): expected = [[1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, origin=(1, 1)) assert_array_almost_equal(out, expected) def test_binary_dilation25(self): expected = [[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation26(self): struct = ndimage.generate_binary_structure(2, 2) expected = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, expected) def test_binary_dilation27(self): struct = [[0, 1], [1, 1]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, expected) def test_binary_dilation28(self): expected = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation29(self): struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=2) assert_array_almost_equal(out, expected) def test_binary_dilation30(self): struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_dilation(data, struct, iterations=2, output=out) assert_array_almost_equal(out, expected) def test_binary_dilation31(self): struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=3) assert_array_almost_equal(out, expected) def test_binary_dilation32(self): struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_dilation(data, struct, iterations=3, output=out) assert_array_almost_equal(out, expected) def test_binary_dilation33(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=-1, mask=mask, border_value=0) assert_array_almost_equal(out, expected) def test_binary_dilation34(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.zeros(mask.shape, bool) out = ndimage.binary_dilation(data, struct, iterations=-1, mask=mask, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation35(self): tmp = [[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) mask = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, mask=mask, origin=(1, 1), border_value=1) assert_array_almost_equal(out, expected) def test_binary_propagation01(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_propagation(data, struct, mask=mask, border_value=0) assert_array_almost_equal(out, expected) def test_binary_propagation02(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.zeros(mask.shape, bool) out = ndimage.binary_propagation(data, struct, mask=mask, border_value=1) assert_array_almost_equal(out, expected) def test_binary_opening01(self): expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_opening(data) assert_array_almost_equal(out, expected) def test_binary_opening02(self): struct = ndimage.generate_binary_structure(2, 2) expected = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_opening(data, struct) assert_array_almost_equal(out, expected) def test_binary_closing01(self): expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_closing(data) assert_array_almost_equal(out, expected) def test_binary_closing02(self): struct = ndimage.generate_binary_structure(2, 2) expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_closing(data, struct) assert_array_almost_equal(out, expected) def test_binary_fill_holes01(self): expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_binary_fill_holes02(self): expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_binary_fill_holes03(self): expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_grey_erosion01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.grey_erosion(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_grey_erosion02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] output = ndimage.grey_erosion(array, footprint=footprint, structure=structure) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_grey_erosion03(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[1, 1, 1], [1, 1, 1]] output = ndimage.grey_erosion(array, footprint=footprint, structure=structure) assert_array_almost_equal([[1, 1, 0, 0, 0], [1, 2, 0, 2, 0], [4, 4, 2, 2, 0]], output) def test_grey_dilation01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] output = ndimage.grey_dilation(array, footprint=footprint) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_grey_dilation02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] structure = [[0, 0, 0], [0, 0, 0]] output = ndimage.grey_dilation(array, footprint=footprint, structure=structure) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_grey_dilation03(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] structure = [[1, 1, 1], [1, 1, 1]] output = ndimage.grey_dilation(array, footprint=footprint, structure=structure) assert_array_almost_equal([[8, 8, 10, 10, 6], [8, 10, 9, 10, 8], [9, 9, 9, 8, 8]], output) def test_grey_opening01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] tmp = ndimage.grey_erosion(array, footprint=footprint) expected = ndimage.grey_dilation(tmp, footprint=footprint) output = ndimage.grey_opening(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_grey_opening02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = ndimage.grey_dilation(tmp, footprint=footprint, structure=structure) output = ndimage.grey_opening(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_grey_closing01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] tmp = ndimage.grey_dilation(array, footprint=footprint) expected = ndimage.grey_erosion(tmp, footprint=footprint) output = ndimage.grey_closing(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_grey_closing02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_dilation(array, footprint=footprint, structure=structure) expected = ndimage.grey_erosion(tmp, footprint=footprint, structure=structure) output = ndimage.grey_closing(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_morphological_gradient01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 - tmp2 output = numpy.zeros(array.shape, array.dtype) ndimage.morphological_gradient(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_morphological_gradient02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 - tmp2 output = ndimage.morphological_gradient(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_morphological_laplace01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 + tmp2 - 2 * array output = numpy.zeros(array.shape, array.dtype) ndimage.morphological_laplace(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_morphological_laplace02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 + tmp2 - 2 * array output = ndimage.morphological_laplace(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_white_tophat01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_opening(array, footprint=footprint, structure=structure) expected = array - tmp output = numpy.zeros(array.shape, array.dtype) ndimage.white_tophat(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_white_tophat02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_opening(array, footprint=footprint, structure=structure) expected = array - tmp output = ndimage.white_tophat(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_black_tophat01(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_closing(array, footprint=footprint, structure=structure) expected = tmp - array output = numpy.zeros(array.shape, array.dtype) ndimage.black_tophat(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_black_tophat02(self): array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_closing(array, footprint=footprint, structure=structure) expected = tmp - array output = ndimage.black_tophat(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_hit_or_miss01(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]], type) out = numpy.zeros(data.shape, bool) ndimage.binary_hit_or_miss(data, struct, output=out) assert_array_almost_equal(expected, out) def test_hit_or_miss02(self): struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 1, 1, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_hit_or_miss(data, struct) assert_array_almost_equal(expected, out) def test_hit_or_miss03(self): struct1 = [[0, 0, 0], [1, 1, 1], [0, 0, 0]] struct2 = [[1, 1, 1], [0, 0, 0], [1, 1, 1]] expected = [[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_hit_or_miss(data, struct1, struct2) assert_array_almost_equal(expected, out) class TestDilateFix: def setUp(self): # dilation related setup self.array = numpy.array([[0, 0, 0, 0, 0,], [0, 0, 0, 0, 0,], [0, 0, 0, 1, 0,], [0, 0, 1, 1, 0,], [0, 0, 0, 0, 0,]], dtype=numpy.uint8) self.sq3x3 = numpy.ones((3, 3)) dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3) self.dilated3x3 = dilated3x3.view(numpy.uint8) def test_dilation_square_structure(self): result = ndimage.grey_dilation(self.array, structure=self.sq3x3) # +1 accounts for difference between grey and binary dilation assert_array_almost_equal(result, self.dilated3x3 + 1) def test_dilation_scalar_size(self): result = ndimage.grey_dilation(self.array, size=3) assert_array_almost_equal(result, self.dilated3x3) if __name__ == "__main__": run_module_suite()
apache-2.0
isabernardes/Heriga
Herigaenv/lib/python2.7/site-packages/django/contrib/auth/management/commands/changepassword.py
136
2610
from __future__ import unicode_literals import getpass from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS from django.utils.encoding import force_str class Command(BaseCommand): help = "Change a user's password for django.contrib.auth." requires_system_checks = False def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=force_str(prompt)) if not p: raise CommandError("aborted") return p def add_arguments(self, parser): parser.add_argument('username', nargs='?', help='Username to change password for; by default, it\'s the current username.') parser.add_argument('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".') def handle(self, *args, **options): if options.get('username'): username = options['username'] else: username = getpass.getuser() UserModel = get_user_model() try: u = UserModel._default_manager.using(options.get('database')).get(**{ UserModel.USERNAME_FIELD: username }) except UserModel.DoesNotExist: raise CommandError("user '%s' does not exist" % username) self.stdout.write("Changing password for user '%s'\n" % u) MAX_TRIES = 3 count = 0 p1, p2 = 1, 2 # To make them initially mismatch. password_validated = False while (p1 != p2 or not password_validated) and count < MAX_TRIES: p1 = self._get_pass() p2 = self._get_pass("Password (again): ") if p1 != p2: self.stdout.write("Passwords do not match. Please try again.\n") count += 1 # Don't validate passwords that don't match. continue try: validate_password(p2, u) except ValidationError as err: self.stderr.write('\n'.join(err.messages)) count += 1 else: password_validated = True if count == MAX_TRIES: raise CommandError("Aborting password change for user '%s' after %s attempts" % (u, count)) u.set_password(p1) u.save() return "Password changed successfully for user '%s'" % u
mit
windweaver828/kspeech
commandtools.py
1
1026
#!/usr/bin/env python def isCommand(command, args): index = 0 for arg in args: if isinstance(arg, list): for ar in arg: if isinstance(ar, list): for a in ar: if isinstance(a, list): index-=1 isCommand(command, a) elif not a in command: break else: index+=1 elif ar in command: index+=1 break if index >= len(args): return True def callCommand(func, args): if args: return func(*args) else: return func() def matchCommand(command, commands): for commdef in commands.keys(): if isCommand(command, commdef): return commands[commdef] else: return False def matchAndCallCommand(command, commands): ret = matchCommand(command, commands) if ret: callCommand(*ret)
gpl-2.0
GitAngel/django
tests/template_tests/filter_tests/test_escape.py
324
1495
from django.template.defaultfilters import escape from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class EscapeTests(SimpleTestCase): """ The "escape" filter works the same whether autoescape is on or off, but it has no effect on strings already marked as safe. """ @setup({'escape01': '{{ a|escape }} {{ b|escape }}'}) def test_escape01(self): output = self.engine.render_to_string('escape01', {"a": "x&y", "b": mark_safe("x&y")}) self.assertEqual(output, "x&amp;y x&y") @setup({'escape02': '{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}'}) def test_escape02(self): output = self.engine.render_to_string('escape02', {"a": "x&y", "b": mark_safe("x&y")}) self.assertEqual(output, "x&amp;y x&y") # It is only applied once, regardless of the number of times it # appears in a chain. @setup({'escape03': '{% autoescape off %}{{ a|escape|escape }}{% endautoescape %}'}) def test_escape03(self): output = self.engine.render_to_string('escape03', {"a": "x&y"}) self.assertEqual(output, "x&amp;y") @setup({'escape04': '{{ a|escape|escape }}'}) def test_escape04(self): output = self.engine.render_to_string('escape04', {"a": "x&y"}) self.assertEqual(output, "x&amp;y") class FunctionTests(SimpleTestCase): def test_non_string_input(self): self.assertEqual(escape(123), '123')
bsd-3-clause
welenofsky/python_koans
python3/libs/colorama/winterm.py
523
4206
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. from . import win32 # from wincon.h class WinColor(object): BLACK = 0 BLUE = 1 GREEN = 2 CYAN = 3 RED = 4 MAGENTA = 5 YELLOW = 6 GREY = 7 # from wincon.h class WinStyle(object): NORMAL = 0x00 # dim text, dim background BRIGHT = 0x08 # bright text, dim background class WinTerm(object): def __init__(self): self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back self._default_style = self._style def get_attrs(self): return self._fore + self._back * 16 + self._style def set_attrs(self, value): self._fore = value & 7 self._back = (value >> 4) & 7 self._style = value & WinStyle.BRIGHT def reset_all(self, on_stderr=None): self.set_attrs(self._default) self.set_console(attrs=self._default) def fore(self, fore=None, on_stderr=False): if fore is None: fore = self._default_fore self._fore = fore self.set_console(on_stderr=on_stderr) def back(self, back=None, on_stderr=False): if back is None: back = self._default_back self._back = back self.set_console(on_stderr=on_stderr) def style(self, style=None, on_stderr=False): if style is None: style = self._default_style self._style = style self.set_console(on_stderr=on_stderr) def set_console(self, attrs=None, on_stderr=False): if attrs is None: attrs = self.get_attrs() handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleTextAttribute(handle, attrs) def get_position(self, handle): position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition # Because Windows coordinates are 0-based, # and win32.SetConsoleCursorPosition expects 1-based. position.X += 1 position.Y += 1 return position def set_cursor_position(self, position=None, on_stderr=False): if position is None: #I'm not currently tracking the position, so there is no default. #position = self.get_position() return handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleCursorPosition(handle, position) def cursor_up(self, num_rows=0, on_stderr=False): if num_rows == 0: return handle = win32.STDOUT if on_stderr: handle = win32.STDERR position = self.get_position(handle) adjusted_position = (position.Y - num_rows, position.X) self.set_cursor_position(adjusted_position, on_stderr) def erase_data(self, mode=0, on_stderr=False): # 0 (or None) should clear from the cursor to the end of the screen. # 1 should clear from the cursor to the beginning of the screen. # 2 should clear the entire screen. (And maybe move cursor to (1,1)?) # # At the moment, I only support mode 2. From looking at the API, it # should be possible to calculate a different number of bytes to clear, # and to do so relative to the cursor position. if mode[0] not in (2,): return handle = win32.STDOUT if on_stderr: handle = win32.STDERR # here's where we'll home the cursor coord_screen = win32.COORD(0,0) csbi = win32.GetConsoleScreenBufferInfo(handle) # get the number of character cells in the current buffer dw_con_size = csbi.dwSize.X * csbi.dwSize.Y # fill the entire screen with blanks win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen) # now set the buffer's attributes accordingly win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen ); # put the cursor at (0, 0) win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))
mit
ohmu/kafka-python
kafka/admin/new_topic.py
8
1306
from __future__ import absolute_import from kafka.errors import IllegalArgumentError class NewTopic(object): """ A class for new topic creation Arguments: name (string): name of the topic num_partitions (int): number of partitions or -1 if replica_assignment has been specified replication_factor (int): replication factor or -1 if replica assignment is specified replica_assignment (dict of int: [int]): A mapping containing partition id and replicas to assign to it. topic_configs (dict of str: str): A mapping of config key and value for the topic. """ def __init__( self, name, num_partitions, replication_factor, replica_assignments=None, topic_configs=None, ): if not (num_partitions == -1 or replication_factor == -1) ^ (replica_assignments is None): raise IllegalArgumentError('either num_partitions/replication_factor or replica_assignment must be specified') self.name = name self.num_partitions = num_partitions self.replication_factor = replication_factor self.replica_assignments = replica_assignments or {} self.topic_configs = topic_configs or {}
apache-2.0
gooddata/openstack-nova
nova/tests/unit/cmd/test_scheduler.py
2
2547
# 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 mock from nova.cmd import scheduler from nova import config from nova import test # required because otherwise oslo early parse_args dies @mock.patch.object(config, 'parse_args', new=lambda *args, **kwargs: None) class TestScheduler(test.NoDBTestCase): @mock.patch('nova.service.Service.create') @mock.patch('nova.service.serve') @mock.patch('nova.service.wait') @mock.patch('oslo_concurrency.processutils.get_worker_count', return_value=2) def test_workers_defaults(self, get_worker_count, mock_wait, mock_serve, service_create): scheduler.main() get_worker_count.assert_called_once_with() mock_serve.assert_called_once_with( service_create.return_value, workers=2) mock_wait.assert_called_once_with() @mock.patch('nova.service.Service.create') @mock.patch('nova.service.serve') @mock.patch('nova.service.wait') @mock.patch('oslo_concurrency.processutils.get_worker_count') def test_workers_override(self, get_worker_count, mock_wait, mock_serve, service_create): self.flags(workers=4, group='scheduler') scheduler.main() get_worker_count.assert_not_called() mock_serve.assert_called_once_with( service_create.return_value, workers=4) mock_wait.assert_called_once_with() @mock.patch('nova.service.Service.create') @mock.patch('nova.service.serve') @mock.patch('nova.service.wait') @mock.patch('oslo_concurrency.processutils.get_worker_count') def test_workers_caching_scheduler(self, get_worker_count, mock_wait, mock_serve, service_create): self.flags(driver='caching_scheduler', group='scheduler') scheduler.main() get_worker_count.assert_not_called() mock_serve.assert_called_once_with( service_create.return_value, workers=1) mock_wait.assert_called_once_with()
apache-2.0
ryfeus/lambda-packs
Rasterio_osgeo_shapely_PIL_pyproj_numpy/source/numpy/polynomial/chebyshev.py
30
62880
""" Objects for dealing with Chebyshev series. This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a `Chebyshev` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- - `chebdomain` -- Chebyshev series default domain, [-1,1]. - `chebzero` -- (Coefficients of the) Chebyshev series that evaluates identically to 0. - `chebone` -- (Coefficients of the) Chebyshev series that evaluates identically to 1. - `chebx` -- (Coefficients of the) Chebyshev series for the identity map, ``f(x) = x``. Arithmetic ---------- - `chebadd` -- add two Chebyshev series. - `chebsub` -- subtract one Chebyshev series from another. - `chebmul` -- multiply two Chebyshev series. - `chebdiv` -- divide one Chebyshev series by another. - `chebpow` -- raise a Chebyshev series to an positive integer power - `chebval` -- evaluate a Chebyshev series at given points. - `chebval2d` -- evaluate a 2D Chebyshev series at given points. - `chebval3d` -- evaluate a 3D Chebyshev series at given points. - `chebgrid2d` -- evaluate a 2D Chebyshev series on a Cartesian product. - `chebgrid3d` -- evaluate a 3D Chebyshev series on a Cartesian product. Calculus -------- - `chebder` -- differentiate a Chebyshev series. - `chebint` -- integrate a Chebyshev series. Misc Functions -------------- - `chebfromroots` -- create a Chebyshev series with specified roots. - `chebroots` -- find the roots of a Chebyshev series. - `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials. - `chebvander2d` -- Vandermonde-like matrix for 2D power series. - `chebvander3d` -- Vandermonde-like matrix for 3D power series. - `chebgauss` -- Gauss-Chebyshev quadrature, points and weights. - `chebweight` -- Chebyshev weight function. - `chebcompanion` -- symmetrized companion matrix in Chebyshev form. - `chebfit` -- least-squares fit returning a Chebyshev series. - `chebpts1` -- Chebyshev points of the first kind. - `chebpts2` -- Chebyshev points of the second kind. - `chebtrim` -- trim leading coefficients from a Chebyshev series. - `chebline` -- Chebyshev series representing given straight line. - `cheb2poly` -- convert a Chebyshev series to a polynomial. - `poly2cheb` -- convert a polynomial to a Chebyshev series. Classes ------- - `Chebyshev` -- A Chebyshev series class. See also -------- `numpy.polynomial` Notes ----- The implementations of multiplication, division, integration, and differentiation use the algebraic identities [1]_: .. math :: T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\ z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}. where .. math :: x = \\frac{z + z^{-1}}{2}. These identities allow a Chebyshev series to be expressed as a finite, symmetric Laurent series. In this module, this sort of Laurent series is referred to as a "z-series." References ---------- .. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev Polynomials," *Journal of Statistical Planning and Inference 14*, 2008 (preprint: http://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) """ from __future__ import division, absolute_import, print_function import warnings import numpy as np import numpy.linalg as la from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = [ 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval', 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d', 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion', 'chebgauss', 'chebweight'] chebtrim = pu.trimcoef # # A collection of functions for manipulating z-series. These are private # functions and do minimal error checking. # def _cseries_to_zseries(c): """Covert Chebyshev series to z-series. Covert a Chebyshev series to the equivalent z-series. The result is never an empty array. The dtype of the return is the same as that of the input. No checks are run on the arguments as this routine is for internal use. Parameters ---------- c : 1-D ndarray Chebyshev coefficients, ordered from low to high Returns ------- zs : 1-D ndarray Odd length symmetric z-series, ordered from low to high. """ n = c.size zs = np.zeros(2*n-1, dtype=c.dtype) zs[n-1:] = c/2 return zs + zs[::-1] def _zseries_to_cseries(zs): """Covert z-series to a Chebyshev series. Covert a z series to the equivalent Chebyshev series. The result is never an empty array. The dtype of the return is the same as that of the input. No checks are run on the arguments as this routine is for internal use. Parameters ---------- zs : 1-D ndarray Odd length symmetric z-series, ordered from low to high. Returns ------- c : 1-D ndarray Chebyshev coefficients, ordered from low to high. """ n = (zs.size + 1)//2 c = zs[n-1:].copy() c[1:n] *= 2 return c def _zseries_mul(z1, z2): """Multiply two z-series. Multiply two z-series to produce a z-series. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D but this is not checked. Returns ------- product : 1-D ndarray The product z-series. Notes ----- This is simply convolution. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S*S, A*A -> S S*A, A*S -> A """ return np.convolve(z1, z2) def _zseries_div(z1, z2): """Divide the first z-series by the second. Divide `z1` by `z2` and return the quotient and remainder as z-series. Warning: this implementation only applies when both z1 and z2 have the same symmetry, which is sufficient for present purposes. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D and have the same symmetry, but this is not checked. Returns ------- (quotient, remainder) : 1-D ndarrays Quotient and remainder as z-series. Notes ----- This is not the same as polynomial division on account of the desired form of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S/S -> S,S A/A -> S,A The restriction to types of the same symmetry could be fixed but seems like unneeded generality. There is no natural form for the remainder in the case where there is no symmetry. """ z1 = z1.copy() z2 = z2.copy() len1 = len(z1) len2 = len(z2) if len2 == 1: z1 /= z2 return z1, z1[:1]*0 elif len1 < len2: return z1[:1]*0, z1 else: dlen = len1 - len2 scl = z2[0] z2 /= scl quo = np.empty(dlen + 1, dtype=z1.dtype) i = 0 j = dlen while i < j: r = z1[i] quo[i] = z1[i] quo[dlen - i] = r tmp = r*z2 z1[i:i+len2] -= tmp z1[j:j+len2] -= tmp i += 1 j -= 1 r = z1[i] quo[i] = r tmp = r*z2 z1[i:i+len2] -= tmp quo /= scl rem = z1[i+1:i-1+len2].copy() return quo, rem def _zseries_der(zs): """Differentiate a z-series. The derivative is with respect to x, not z. This is achieved using the chain rule and the value of dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to differentiate. Returns ------- derivative : z-series The derivative Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by multiplying the value of zs by two also so that the two cancels in the division. """ n = len(zs)//2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs *= np.arange(-n, n+1)*2 d, r = _zseries_div(zs, ns) return d def _zseries_int(zs): """Integrate a z-series. The integral is with respect to x, not z. This is achieved by a change of variable using dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to integrate Returns ------- integral : z-series The indefinite integral Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by dividing the resulting zs by two. """ n = 1 + len(zs)//2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs = _zseries_mul(zs, ns) div = np.arange(-n, n+1)*2 zs[:n] /= div[:n] zs[n+1:] /= div[n+1:] zs[n] = 0 return zs # # Chebyshev series functions # def poly2cheb(pol): """ Convert a polynomial to a Chebyshev series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Chebyshev series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Chebyshev series. See Also -------- cheb2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> p = P.Polynomial(range(4)) >>> p Polynomial([ 0., 1., 2., 3.], [-1., 1.]) >>> c = p.convert(kind=P.Chebyshev) >>> c Chebyshev([ 1. , 3.25, 1. , 0.75], [-1., 1.]) >>> P.poly2cheb(range(4)) array([ 1. , 3.25, 1. , 0.75]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1): res = chebadd(chebmulx(res), pol[i]) return res def cheb2poly(c): """ Convert a Chebyshev series to a polynomial. Convert an array representing the coefficients of a Chebyshev series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Chebyshev series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2cheb Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> c = P.Chebyshev(range(4)) >>> c Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([ -2., -8., 4., 12.], [-1., 1.]) >>> P.cheb2poly(range(4)) array([ -2., -8., 4., 12.]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1) c1 = polyadd(tmp, polymulx(c1)*2) return polyadd(c0, polymulx(c1)) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Chebyshev default domain. chebdomain = np.array([-1, 1]) # Chebyshev coefficients representing zero. chebzero = np.array([0]) # Chebyshev coefficients representing one. chebone = np.array([1]) # Chebyshev coefficients representing the identity x. chebx = np.array([0, 1]) def chebline(off, scl): """ Chebyshev series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Chebyshev series for ``off + scl*x``. See Also -------- polyline Examples -------- >>> import numpy.polynomial.chebyshev as C >>> C.chebline(3,2) array([3, 2]) >>> C.chebval(-3, C.chebline(3,2)) # should be -3 -3.0 """ if scl != 0: return np.array([off, scl]) else: return np.array([off]) def chebfromroots(roots): """ Generate a Chebyshev series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Chebyshev form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Chebyshev form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, legfromroots, lagfromroots, hermfromroots, hermefromroots. Examples -------- >>> import numpy.polynomial.chebyshev as C >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.25, 0. , 0.25]) >>> j = complex(0,1) >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([ 1.5+0.j, 0.0+0.j, 0.5+0.j]) """ if len(roots) == 0: return np.ones(1) else: [roots] = pu.as_series([roots], trim=False) roots.sort() p = [chebline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [chebmul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = chebmul(tmp[0], p[-1]) p = tmp n = m return p[0] def chebadd(c1, c2): """ Add one Chebyshev series to another. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Chebyshev series of their sum. See Also -------- chebsub, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the sum of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebadd(c1,c2) array([ 4., 4., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] += c2 ret = c1 else: c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def chebsub(c1, c2): """ Subtract one Chebyshev series from another. Returns the difference of two Chebyshev series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their difference. See Also -------- chebadd, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the difference of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebsub(c1,c2) array([-2., 0., 2.]) >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2) array([ 2., 0., -2.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] -= c2 ret = c1 else: c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def chebmulx(c): """Multiply a Chebyshev series by x. Multiply the polynomial `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- .. versionadded:: 1.5.0 """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1] = c[0] if len(c) > 1: tmp = c[1:]/2 prd[2:] = tmp prd[0:-2] += tmp return prd def chebmul(c1, c2): """ Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) prd = _zseries_mul(z1, z2) ret = _zseries_to_cseries(prd) return pu.trimseq(ret) def chebdiv(c1, c2): """ Divide one Chebyshev series by another. Returns the quotient-with-remainder of two Chebyshev series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Chebyshev series coefficients representing the quotient and remainder. See Also -------- chebadd, chebsub, chebmul, chebpow Notes ----- In general, the (polynomial) division of one C-series by another results in quotient and remainder terms that are not in the Chebyshev polynomial basis set. Thus, to express these results as C-series, it is typically necessary to "reproject" the results onto said basis set, which typically produces "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not (array([ 3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> C.chebdiv(c2,c1) # neither "intuitive" (array([ 0., 2.]), array([-2., -4.])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0: raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2: return c1[:1]*0, c1 elif lc2 == 1: return c1/c2[-1], c1[:1]*0 else: z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) quo, rem = _zseries_div(z1, z2) quo = pu.trimseq(_zseries_to_cseries(quo)) rem = pu.trimseq(_zseries_to_cseries(rem)) return quo, rem def chebpow(c, pow, maxpower=16): """Raise a Chebyshev series to a power. Returns the Chebyshev series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.`` Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Chebyshev series of power. See Also -------- chebadd, chebsub, chebmul, chebdiv Examples -------- """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0: raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower: raise ValueError("Power is too large") elif power == 0: return np.array([1], dtype=c.dtype) elif power == 1: return c else: # This can be made more efficient by using powers of two # in the usual way. zs = _cseries_to_zseries(c) prd = zs for i in range(2, power + 1): prd = np.convolve(prd, zs) return _zseries_to_cseries(prd) def chebder(c, m=1, scl=1, axis=0): """ Differentiate a Chebyshev series. Returns the Chebyshev series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Chebyshev series of the derivative. See Also -------- chebint Notes ----- In general, the result of differentiating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3,4) >>> C.chebder(c) array([ 14., 12., 24.]) >>> C.chebder(c,3) array([ 96.]) >>> C.chebder(c,scl=-1) array([-14., -12., -24.]) >>> C.chebder(c,2,-1) array([ 12., 96.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2*j)*c[j] c[j - 2] += (j*c[j])/(j - 2) if n > 1: der[1] = 4*c[2] der[0] = c[1] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Chebyshev series. Returns the Chebyshev series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray C-series coefficients of the integral. Raises ------ ValueError If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- chebder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a`- perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3) >>> C.chebint(c) array([ 0.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,3) array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, 0.00625 ]) >>> C.chebint(c, k=3) array([ 3.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,lbnd=-2) array([ 8.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,scl=-2) array([-1., 1., -1., -1.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0: raise ValueError("The order of integration must be non-negative") if len(k) > cnt: raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0]*0 tmp[1] = c[0] if n > 1: tmp[2] = c[1]/4 for j in range(2, n): t = c[j]/(2*j + 1) tmp[j + 1] = c[j]/(2*(j + 1)) tmp[j - 1] -= c[j]/(2*(j - 1)) tmp[0] += k[i] - chebval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def chebval(x, c, tensor=True): """ Evaluate a Chebyshev series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- chebval2d, chebgrid2d, chebval3d, chebgrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: x2 = 2*x c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 c0 = c[-i] - c1 c1 = tmp + c1*x2 return c0 + c1*x def chebval2d(x, y, c): """ Evaluate a 2-D Chebyshev series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than 2 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points formed from pairs of corresponding values from `x` and `y`. See Also -------- chebval, chebgrid2d, chebval3d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = chebval(x, c) c = chebval(y, c, tensor=False) return c def chebgrid2d(x, y, c): """ Evaluate a 2-D Chebyshev series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * T_i(a) * T_j(b), where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in `c[i,j]`. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points in the Cartesian product of `x` and `y`. See Also -------- chebval, chebval2d, chebval3d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ c = chebval(x, c) c = chebval(y, c) return c def chebval3d(x, y, z, c): """ Evaluate a 3-D Chebyshev series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- chebval, chebval2d, chebgrid2d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = chebval(x, c) c = chebval(y, c, tensor=False) c = chebval(z, c, tensor=False) return c def chebgrid3d(x, y, z, c): """ Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- chebval, chebval2d, chebgrid2d, chebval3d Notes ----- .. versionadded::1.7.0 """ c = chebval(x, c) c = chebval(y, c) c = chebval(z, c) return c def chebvander(x, deg): """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = T_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the Chebyshev polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and ``chebval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of Chebyshev series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding Chebyshev polynomial. The dtype will be the same as the converted `x`. """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) # Use forward recursion to generate the entries. v[0] = x*0 + 1 if ideg > 0: x2 = 2*x v[1] = x for i in range(2, ideg + 1): v[i] = v[i-1]*x2 - v[i-2] return np.rollaxis(v, 0, v.ndim) def chebvander2d(x, y, deg): """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = T_i(x) * T_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the Chebyshev polynomials. If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Chebyshev series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- chebvander, chebvander3d. chebval2d, chebval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = chebvander(x, degx) vy = chebvander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def chebvander3d(x, y, z, deg): """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the Chebyshev polynomials. If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D Chebyshev series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- chebvander, chebvander3d. chebval2d, chebval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = chebvander(x, degx) vy = chebvander(y, degy) vz = chebvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x), where `n` is `deg`. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. deg : int or 1-D array_like Degree(s) of the fitting polynomials. If `deg` is a single integer all terms up to and including the `deg`'th term are included in the fit. For Numpy versions >= 1.11 a list of integers specifying the degrees of the terms to include may be used instead. rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (`M`,), optional Weights. If not None, the contribution of each point ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. The default value is None. .. versionadded:: 1.5.0 Returns ------- coef : ndarray, shape (M,) or (M, K) Chebyshev coefficients ordered from low to high. If `y` was 2-D, the coefficients for the data in column k of `y` are in column `k`. [residuals, rank, singular_values, rcond] : list These values are only returned if `full` = True resid -- sum of squared residuals of the least squares fit rank -- the numerical rank of the scaled Vandermonde matrix sv -- singular values of the scaled Vandermonde matrix rcond -- value of `rcond`. For more details, see `linalg.lstsq`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- polyfit, legfit, lagfit, hermfit, hermefit chebval : Evaluates a Chebyshev series. chebvander : Vandermonde matrix of Chebyshev series. chebweight : Chebyshev weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Chebyshev series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Chebyshev series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- """ x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 deg = np.asarray(deg) # check arguments. if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0: raise TypeError("deg must be an int or non-empty 1-D array of int") if deg.min() < 0: raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2: raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") if deg.ndim == 0: lmax = deg order = lmax + 1 van = chebvander(x, lmax) else: deg = np.sort(deg) lmax = deg[-1] order = len(deg) van = chebvander(x, lmax)[:, deg] # set up the least squares matrices in transposed form lhs = van.T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None: rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # Expand c to include non-fitted coefficients which are set to zero if deg.ndim > 0: if c.ndim == 2: cc = np.zeros((lmax + 1, c.shape[1]), dtype=c.dtype) else: cc = np.zeros(lmax + 1, dtype=c.dtype) cc[deg] = c c = cc # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full: return c, [resids, rank, s, rcond] else: return c def chebcompanion(c): """Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when `c` is a Chebyshev basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if `numpy.linalg.eigvalsh` is used to obtain them. Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high degree. Returns ------- mat : ndarray Scaled companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.array([1.] + [np.sqrt(.5)]*(n-1)) top = mat.reshape(-1)[1::n+1] bot = mat.reshape(-1)[n::n+1] top[0] = np.sqrt(.5) top[1:] = 1/2 bot[...] = top mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5 return mat def chebroots(c): """ Compute the roots of a Chebyshev series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * T_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Chebyshev series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> import numpy.polynomial.chebyshev as cheb >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0]/c[1]]) m = chebcompanion(c) r = la.eigvals(m) r.sort() return r def chebgauss(deg): """ Gauss-Chebyshev quadrature. Computes the sample points and weights for Gauss-Chebyshev quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with the weight function :math:`f(x) = 1/\sqrt{1 - x^2}`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded:: 1.7.0 The results have only been tested up to degree 100, higher degrees may be problematic. For Gauss-Chebyshev there are closed form solutions for the sample points and weights. If n = `deg`, then .. math:: x_i = \cos(\pi (2 i - 1) / (2 n)) .. math:: w_i = \pi / n """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg)) w = np.ones(ideg)*(np.pi/ideg) return x, w def chebweight(x): """ The weight function of the Chebyshev polynomials. The weight function is :math:`1/\sqrt{1 - x^2}` and the interval of integration is :math:`[-1, 1]`. The Chebyshev polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded:: 1.7.0 """ w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x)) return w def chebpts1(npts): """ Chebyshev points of the first kind. The Chebyshev points of the first kind are the points ``cos(x)``, where ``x = [pi*(k + .5)/npts for k in range(npts)]``. Parameters ---------- npts : int Number of sample points desired. Returns ------- pts : ndarray The Chebyshev points of the first kind. See Also -------- chebpts2 Notes ----- .. versionadded:: 1.5.0 """ _npts = int(npts) if _npts != npts: raise ValueError("npts must be integer") if _npts < 1: raise ValueError("npts must be >= 1") x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts) return np.cos(x) def chebpts2(npts): """ Chebyshev points of the second kind. The Chebyshev points of the second kind are the points ``cos(x)``, where ``x = [pi*k/(npts - 1) for k in range(npts)]``. Parameters ---------- npts : int Number of sample points desired. Returns ------- pts : ndarray The Chebyshev points of the second kind. Notes ----- .. versionadded:: 1.5.0 """ _npts = int(npts) if _npts != npts: raise ValueError("npts must be integer") if _npts < 2: raise ValueError("npts must be >= 2") x = np.linspace(-np.pi, 0, _npts) return np.cos(x) # # Chebyshev series class # class Chebyshev(ABCPolyBase): """A Chebyshev series class. The Chebyshev class provides the standard Python numerical methods '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the methods listed below. Parameters ---------- coef : array_like Chebyshev coefficients in order of increasing degree, i.e., ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``. domain : (2,) array_like, optional Domain to use. The interval ``[domain[0], domain[1]]`` is mapped to the interval ``[window[0], window[1]]`` by shifting and scaling. The default value is [-1, 1]. window : (2,) array_like, optional Window, see `domain` for its use. The default value is [-1, 1]. .. versionadded:: 1.6.0 """ # Virtual Functions _add = staticmethod(chebadd) _sub = staticmethod(chebsub) _mul = staticmethod(chebmul) _div = staticmethod(chebdiv) _pow = staticmethod(chebpow) _val = staticmethod(chebval) _int = staticmethod(chebint) _der = staticmethod(chebder) _fit = staticmethod(chebfit) _line = staticmethod(chebline) _roots = staticmethod(chebroots) _fromroots = staticmethod(chebfromroots) # Virtual properties nickname = 'cheb' domain = np.array(chebdomain) window = np.array(chebdomain)
mit